text:
if (typeof URI === "undefined") {
	var URI = require("../dist/es5/uri.all");
}

test("Acquire URI", function () {
	//URI = require("./uri").URI;
	ok(URI);
});

test("URI Parsing", function () {
	var components;

	//scheme
	components = URI.parse("uri:");
	strictEqual(components.error, undefined, "scheme errors");
	strictEqual(components.scheme, "uri", "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//userinfo
	components = URI.parse("//@");
	strictEqual(components.error, undefined, "userinfo errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, "@", "authority");
	strictEqual(components.userinfo, "", "userinfo");
	strictEqual(components.host, "", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//host
	components = URI.parse("//");
	strictEqual(components.error, undefined, "host errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, "", "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//port
	components = URI.parse("//:");
	strictEqual(components.error, undefined, "port errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, ":", "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "", "host");
	strictEqual(components.port, "", "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//path
	components = URI.parse("");
	strictEqual(components.error, undefined, "path errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//query
	components = URI.parse("?");
	strictEqual(components.error, undefined, "query errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, "", "query");
	strictEqual(components.fragment, undefined, "fragment");

	//fragment
	components = URI.parse("#");
	strictEqual(components.error, undefined, "fragment errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, "", "fragment");

	//fragment with character tabulation
	components = URI.parse("#\t");
	strictEqual(components.error, undefined, "path errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, "%09", "fragment");

	//fragment with line feed
	components = URI.parse("#\n");
	strictEqual(components.error, undefined, "path errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, "%0A", "fragment");

	//fragment with line tabulation
	components = URI.parse("#\v");
	strictEqual(components.error, undefined, "path errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, "%0B", "fragment");

	//fragment with form feed
	components = URI.parse("#\f");
	strictEqual(components.error, undefined, "path errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, "%0C", "fragment");

	//fragment with carriage return
	components = URI.parse("#\r");
	strictEqual(components.error, undefined, "path errors");
	strictEqual(components.scheme, undefined, "scheme");
	//strictEqual(components.authority, undefined, "authority");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, undefined, "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, "%0D", "fragment");

	//all
	components = URI.parse("uri://user:pass@example.com:123/one/two.three?q1=a1&q2=a2#body");
	strictEqual(components.error, undefined, "all errors");
	strictEqual(components.scheme, "uri", "scheme");
	//strictEqual(components.authority, "user:pass@example.com:123", "authority");
	strictEqual(components.userinfo, "user:pass", "userinfo");
	strictEqual(components.host, "example.com", "host");
	strictEqual(components.port, 123, "port");
	strictEqual(components.path, "/one/two.three", "path");
	strictEqual(components.query, "q1=a1&q2=a2", "query");
	strictEqual(components.fragment, "body", "fragment");

	//IPv4address
	components = URI.parse("//10.10.10.10");
	strictEqual(components.error, undefined, "IPv4address errors");
	strictEqual(components.scheme, undefined, "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "10.10.10.10", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//IPv6address
	components = URI.parse("//[2001:db8::7]");
	strictEqual(components.error, undefined, "IPv4address errors");
	strictEqual(components.scheme, undefined, "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "2001:db8::7", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//mixed IPv4address & IPv6address
	components = URI.parse("//[::ffff:129.144.52.38]");
	strictEqual(components.error, undefined, "IPv4address errors");
	strictEqual(components.scheme, undefined, "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "::ffff:129.144.52.38", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//mixed IPv4address & reg-name, example from terion-name (https://github.com/garycourt/uri-js/issues/4)
	components = URI.parse("uri://10.10.10.10.example.com/en/process");
	strictEqual(components.error, undefined, "mixed errors");
	strictEqual(components.scheme, "uri", "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "10.10.10.10.example.com", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "/en/process", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//IPv6address, example from bkw (https://github.com/garycourt/uri-js/pull/16)
	components = URI.parse("//[2606:2800:220:1:248:1893:25c8:1946]/test");
	strictEqual(components.error, undefined, "IPv6address errors");
	strictEqual(components.scheme, undefined, "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "2606:2800:220:1:248:1893:25c8:1946", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "/test", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//IPv6address, example from RFC 5952
	components = URI.parse("//[2001:db8::1]:80");
	strictEqual(components.error, undefined, "IPv6address errors");
	strictEqual(components.scheme, undefined, "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "2001:db8::1", "host");
	strictEqual(components.port, 80, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//IPv6address with zone identifier, RFC 6874
	components = URI.parse("//[fe80::a%25en1]");
	strictEqual(components.error, undefined, "IPv4address errors");
	strictEqual(components.scheme, undefined, "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "fe80::a%en1", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");

	//IPv6address with an unescaped interface specifier, example from pekkanikander (https://github.com/garycourt/uri-js/pull/22)
	components = URI.parse("//[2001:db8::7%en0]");
	strictEqual(components.error, undefined, "IPv6address interface errors");
	strictEqual(components.scheme, undefined, "scheme");
	strictEqual(components.userinfo, undefined, "userinfo");
	strictEqual(components.host, "2001:db8::7%en0", "host");
	strictEqual(components.port, undefined, "port");
	strictEqual(components.path, "", "path");
	strictEqual(components.query, undefined, "query");
	strictEqual(components.fragment, undefined, "fragment");
});

test("URI Serialization", function () {
	var components = {
		scheme : undefined,
		userinfo : undefined,
		host : undefined,
		port : undefined,
		path : undefined,
		query : undefined,
		fragment : undefined
	};
	strictEqual(URI.serialize(components), "", "Undefined Components");

	components = {
		scheme : "",
		userinfo : "",
		host : "",
		port : 0,
		path : "",
		query : "",
		fragment : ""
	};
	strictEqual(URI.serialize(components), "//@:0?#", "Empty Components");

	components = {
		scheme : "uri",
		userinfo : "foo:bar",
		host : "example.com",
		port : 1,
		path : "path",
		query : "query",
		fragment : "fragment"
	};
	strictEqual(URI.serialize(components), "uri://foo:bar@example.com:1/path?query#fragment", "All Components");

	strictEqual(URI.serialize({path:"//path"}), "/%2Fpath", "Double slash path");
	strictEqual(URI.serialize({path:"foo:bar"}), "foo%3Abar", "Colon path");
	strictEqual(URI.serialize({path:"?query"}), "%3Fquery", "Query path");

	//mixed IPv4address & reg-name, example from terion-name (https://github.com/garycourt/uri-js/issues/4)
	strictEqual(URI.serialize({host:"10.10.10.10.example.com"}), "//10.10.10.10.example.com", "Mixed IPv4address & reg-name");

	//IPv6address
	strictEqual(URI.serialize({host:"2001:db8::7"}), "//[2001:db8::7]", "IPv6 Host");
	strictEqual(URI.serialize({host:"::ffff:129.144.52.38"}), "//[::ffff:129.144.52.38]", "IPv6 Mixed Host");
	strictEqual(URI.serialize({host:"2606:2800:220:1:248:1893:25c8:1946"}), "//[2606:2800:220:1:248:1893:25c8:1946]", "IPv6 Full Host");

	//IPv6address with zone identifier, RFC 6874
	strictEqual(URI.serialize({host:"fe80::a%en1"}), "//[fe80::a%25en1]", "IPv6 Zone Unescaped Host");
	strictEqual(URI.serialize({host:"fe80::a%25en1"}), "//[fe80::a%25en1]", "IPv6 Zone Escaped Host");
});

test("URI Resolving", function () {
	//normal examples from RFC 3986
	var base = "uri://a/b/c/d;p?q";
	strictEqual(URI.resolve(base, "g:h"), "g:h", "g:h");
	strictEqual(URI.resolve(base, "g:h"), "g:h", "g:h");
	strictEqual(URI.resolve(base, "g"), "uri://a/b/c/g", "g");
	strictEqual(URI.resolve(base, "./g"), "uri://a/b/c/g", "./g");
	strictEqual(URI.resolve(base, "g/"), "uri://a/b/c/g/", "g/");
	strictEqual(URI.resolve(base, "/g"), "uri://a/g", "/g");
	strictEqual(URI.resolve(base, "//g"), "uri://g", "//g");
	strictEqual(URI.resolve(base, "?y"), "uri://a/b/c/d;p?y", "?y");
	strictEqual(URI.resolve(base, "g?y"), "uri://a/b/c/g?y", "g?y");
	strictEqual(URI.resolve(base, "#s"), "uri://a/b/c/d;p?q#s", "#s");
	strictEqual(URI.resolve(base, "g#s"), "uri://a/b/c/g#s", "g#s");
	strictEqual(URI.resolve(base, "g?y#s"), "uri://a/b/c/g?y#s", "g?y#s");
	strictEqual(URI.resolve(base, ";x"), "uri://a/b/c/;x", ";x");
	strictEqual(URI.resolve(base, "g;x"), "uri://a/b/c/g;x", "g;x");
	strictEqual(URI.resolve(base, "g;x?y#s"), "uri://a/b/c/g;x?y#s", "g;x?y#s");
	strictEqual(URI.resolve(base, ""), "uri://a/b/c/d;p?q", "");
	strictEqual(URI.resolve(base, "."), "uri://a/b/c/", ".");
	strictEqual(URI.resolve(base, "./"), "uri://a/b/c/", "./");
	strictEqual(URI.resolve(base, ".."), "uri://a/b/", "..");
	strictEqual(URI.resolve(base, "../"), "uri://a/b/", "../");
	strictEqual(URI.resolve(base, "../g"), "uri://a/b/g", "../g");
	strictEqual(URI.resolve(base, "../.."), "uri://a/", "../..");
	strictEqual(URI.resolve(base, "../../"), "uri://a/", "../../");
	strictEqual(URI.resolve(base, "../../g"), "uri://a/g", "../../g");

	//abnormal examples from RFC 3986
	strictEqual(URI.resolve(base, "../../../g"), "uri://a/g", "../../../g");
	strictEqual(URI.resolve(base, "../../../../g"), "uri://a/g", "../../../../g");

	strictEqual(URI.resolve(base, "/./g"), "uri://a/g", "/./g");
	strictEqual(URI.resolve(base, "/../g"), "uri://a/g", "/../g");
	strictEqual(URI.resolve(base, "g."), "uri://a/b/c/g.", "g.");
	strictEqual(URI.resolve(base, ".g"), "uri://a/b/c/.g", ".g");
	strictEqual(URI.resolve(base, "g.."), "uri://a/b/c/g..", "g..");
	strictEqual(URI.resolve(base, "..g"), "uri://a/b/c/..g", "..g");

	strictEqual(URI.resolve(base, "./../g"), "uri://a/b/g", "./../g");
	strictEqual(URI.resolve(base, "./g/."), "uri://a/b/c/g/", "./g/.");
	strictEqual(URI.resolve(base, "g/./h"), "uri://a/b/c/g/h", "g/./h");
	strictEqual(URI.resolve(base, "g/../h"), "uri://a/b/c/h", "g/../h");
	strictEqual(URI.resolve(base, "g;x=1/./y"), "uri://a/b/c/g;x=1/y", "g;x=1/./y");
	strictEqual(URI.resolve(base, "g;x=1/../y"), "uri://a/b/c/y", "g;x=1/../y");

	strictEqual(URI.resolve(base, "g?y/./x"), "uri://a/b/c/g?y/./x", "g?y/./x");
	strictEqual(URI.resolve(base, "g?y/../x"), "uri://a/b/c/g?y/../x", "g?y/../x");
	strictEqual(URI.resolve(base, "g#s/./x"), "uri://a/b/c/g#s/./x", "g#s/./x");
	strictEqual(URI.resolve(base, "g#s/../x"), "uri://a/b/c/g#s/../x", "g#s/../x");

	strictEqual(URI.resolve(base, "uri:g"), "uri:g", "uri:g");
	strictEqual(URI.resolve(base, "uri:g", {tolerant:true}), "uri://a/b/c/g", "uri:g");

	//examples by PAEz
	strictEqual(URI.resolve("//www.g.com/","/adf\ngf"), "//www.g.com/adf%0Agf", "/adf\\ngf");
	strictEqual(URI.resolve("//www.g.com/error\n/bleh/bleh",".."), "//www.g.com/error%0A/", "//www.g.com/error\\n/bleh/bleh");
});

test("URI Normalizing", function () {
	//test from RFC 3987
	strictEqual(URI.normalize("uri://www.example.org/red%09ros\xE9#red"), "uri://www.example.org/red%09ros%C3%A9#red");

	//IPv4address
	strictEqual(URI.normalize("//192.068.001.000"), "//192.68.1.0");

	//IPv6address, example from RFC 3513
	strictEqual(URI.normalize("http://[1080::8:800:200C:417A]/"), "http://[1080::8:800:200c:417a]/");

	//IPv6address, examples from RFC 5952
	strictEqual(URI.normalize("//[2001:0db8::0001]/"), "//[2001:db8::1]/");
	strictEqual(URI.normalize("//[2001:db8::1:0000:1]/"), "//[2001:db8::1:0:1]/");
	strictEqual(URI.normalize("//[2001:db8:0:0:0:0:2:1]/"), "//[2001:db8::2:1]/");
	strictEqual(URI.normalize("//[2001:db8:0:1:1:1:1:1]/"), "//[2001:db8:0:1:1:1:1:1]/");
	strictEqual(URI.normalize("//[2001:0:0:1:0:0:0:1]/"), "//[2001:0:0:1::1]/");
	strictEqual(URI.normalize("//[2001:db8:0:0:1:0:0:1]/"), "//[2001:db8::1:0:0:1]/");
	strictEqual(URI.normalize("//[2001:DB8::1]/"), "//[2001:db8::1]/");
	strictEqual(URI.normalize("//[0:0:0:0:0:ffff:192.0.2.1]/"), "//[::ffff:192.0.2.1]/");

	//Mixed IPv4 and IPv6 address
	strictEqual(URI.normalize("//[1:2:3:4:5:6:192.0.2.1]/"), "//[1:2:3:4:5:6:192.0.2.1]/");
	strictEqual(URI.normalize("//[1:2:3:4:5:6:192.068.001.000]/"), "//[1:2:3:4:5:6:192.68.1.0]/");
});

test("URI Equals", function () {
	//test from RFC 3986
	strictEqual(URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d"), true);

	//test from RFC 3987
	strictEqual(URI.equal("http://example.org/~user", "http://example.org/%7euser"), true);
});

test("Escape Component", function () {
	var chr;
	for (var d = 0; d <= 129; ++d) {
		chr = String.fromCharCode(d);
		if (!chr.match(/[\$\&\+\,\;\=]/)) {
			strictEqual(URI.escapeComponent(chr), encodeURIComponent(chr));
		} else {
			strictEqual(URI.escapeComponent(chr), chr);
		}
	}
	strictEqual(URI.escapeComponent("\u00c0"), encodeURIComponent("\u00c0"));
	strictEqual(URI.escapeComponent("\u07ff"), encodeURIComponent("\u07ff"));
	strictEqual(URI.escapeComponent("\u0800"), encodeURIComponent("\u0800"));
	strictEqual(URI.escapeComponent("\u30a2"), encodeURIComponent("\u30a2"));
});

test("Unescape Component", function () {
	var chr;
	for (var d = 0; d <= 129; ++d) {
		chr = String.fromCharCode(d);
		strictEqual(URI.unescapeComponent(encodeURIComponent(chr)), chr);
	}
	strictEqual(URI.unescapeComponent(encodeURIComponent("\u00c0")), "\u00c0");
	strictEqual(URI.unescapeComponent(encodeURIComponent("\u07ff")), "\u07ff");
	strictEqual(URI.unescapeComponent(encodeURIComponent("\u0800")), "\u0800");
	strictEqual(URI.unescapeComponent(encodeURIComponent("\u30a2")), "\u30a2");
});

//
// IRI
//

var IRI_OPTION = { iri : true, unicodeSupport : true };

test("IRI Parsing", function () {
	var components = URI.parse("uri://us\xA0er:pa\uD7FFss@example.com:123/o\uF900ne/t\uFDCFwo.t\uFDF0hree?q1=a1\uF8FF\uE000&q2=a2#bo\uFFEFdy", IRI_OPTION);
	strictEqual(components.error, undefined, "all errors");
	strictEqual(components.scheme, "uri", "scheme");
	//strictEqual(components.authority, "us\xA0er:pa\uD7FFss@example.com:123", "authority");
	strictEqual(components.userinfo, "us\xA0er:pa\uD7FFss", "userinfo");
	strictEqual(components.host, "example.com", "host");
	strictEqual(components.port, 123, "port");
	strictEqual(components.path, "/o\uF900ne/t\uFDCFwo.t\uFDF0hree", "path");
	strictEqual(components.query, "q1=a1\uF8FF\uE000&q2=a2", "query");
	strictEqual(components.fragment, "bo\uFFEFdy", "fragment");
});

test("IRI Serialization", function () {
	var components = {
		scheme : "uri",
		userinfo : "us\xA0er:pa\uD7FFss",
		host : "example.com",
		port : 123,
		path : "/o\uF900ne/t\uFDCFwo.t\uFDF0hree",
		query : "q1=a1\uF8FF\uE000&q2=a2",
		fragment : "bo\uFFEFdy\uE001"
	};
	strictEqual(URI.serialize(components, IRI_OPTION), "uri://us\xA0er:pa\uD7FFss@example.com:123/o\uF900ne/t\uFDCFwo.t\uFDF0hree?q1=a1\uF8FF\uE000&q2=a2#bo\uFFEFdy%EE%80%81");
});

test("IRI Normalizing", function () {
	strictEqual(URI.normalize("uri://www.example.org/red%09ros\xE9#red", IRI_OPTION), "uri://www.example.org/red%09ros\xE9#red");
});

test("IRI Equals", function () {
	//example from RFC 3987
	strictEqual(URI.equal("example://a/b/c/%7Bfoo%7D/ros\xE9", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d/ros%C3%A9", IRI_OPTION), true);
});

test("Convert IRI to URI", function () {
	//example from RFC 3987
	strictEqual(URI.serialize(URI.parse("uri://www.example.org/red%09ros\xE9#red", IRI_OPTION)), "uri://www.example.org/red%09ros%C3%A9#red");

	//Internationalized Domain Name conversion via punycode example from RFC 3987
	strictEqual(URI.serialize(URI.parse("uri://r\xE9sum\xE9.example.org", {iri:true, domainHost:true}), {domainHost:true}), "uri://xn--rsum-bpad.example.org");
});

test("Convert URI to IRI", function () {
	//examples from RFC 3987
	strictEqual(URI.serialize(URI.parse("uri://www.example.org/D%C3%BCrst"), IRI_OPTION), "uri://www.example.org/D\xFCrst");
	strictEqual(URI.serialize(URI.parse("uri://www.example.org/D%FCrst"), IRI_OPTION), "uri://www.example.org/D%FCrst");
	strictEqual(URI.serialize(URI.parse("uri://xn--99zt52a.example.org/%e2%80%ae"), IRI_OPTION), "uri://xn--99zt52a.example.org/%E2%80%AE");  //or uri://\u7D0D\u8C46.example.org/%E2%80%AE

	//Internationalized Domain Name conversion via punycode example from RFC 3987
	strictEqual(URI.serialize(URI.parse("uri://xn--rsum-bpad.example.org", {domainHost:true}), {iri:true, domainHost:true}), "uri://r\xE9sum\xE9.example.org");
});

//
// HTTP
//

if (URI.SCHEMES["http"]) {

	//module("HTTP");

	test("HTTP Equals", function () {
		//test from RFC 2616
		strictEqual(URI.equal("http://abc.com:80/~smith/home.html", "http://abc.com/~smith/home.html"), true);
		strictEqual(URI.equal("http://ABC.com/%7Esmith/home.html", "http://abc.com/~smith/home.html"), true);
		strictEqual(URI.equal("http://ABC.com:/%7esmith/home.html", "http://abc.com/~smith/home.html"), true);
		strictEqual(URI.equal("HTTP://ABC.COM", "http://abc.com/"), true);
		//test from RFC 3986
		strictEqual(URI.equal("http://example.com:/", "http://example.com:80/"), true);
	});

}

if (URI.SCHEMES["https"]) {

	//module("HTTPS");

	test("HTTPS Equals", function () {
		strictEqual(URI.equal("https://example.com", "https://example.com:443/"), true);
		strictEqual(URI.equal("https://example.com:/", "https://example.com:443/"), true);
	});

}

//
// URN
//

if (URI.SCHEMES["urn"]) {

	//module("URN");

	test("URN Parsing", function () {
		//example from RFC 2141
		var components = URI.parse("urn:foo:a123,456");
		strictEqual(components.error, undefined, "errors");
		strictEqual(components.scheme, "urn", "scheme");
		//strictEqual(components.authority, undefined, "authority");
		strictEqual(components.userinfo, undefined, "userinfo");
		strictEqual(components.host, undefined, "host");
		strictEqual(components.port, undefined, "port");
		strictEqual(components.path, undefined, "path");
		strictEqual(components.query, undefined, "query");
		strictEqual(components.fragment, undefined, "fragment");
		strictEqual(components.nid, "foo", "nid");
		strictEqual(components.nss, "a123,456", "nss");
	});

	test("URN Serialization", function () {
		//example from RFC 2141
		var components = {
			scheme : "urn",
			nid : "foo",
			nss : "a123,456"
		};
		strictEqual(URI.serialize(components), "urn:foo:a123,456");
	});

	test("URN Equals", function () {
		//test from RFC 2141
		strictEqual(URI.equal("urn:foo:a123,456", "urn:foo:a123,456"), true);
		strictEqual(URI.equal("urn:foo:a123,456", "URN:foo:a123,456"), true);
		strictEqual(URI.equal("urn:foo:a123,456", "urn:FOO:a123,456"), true);
		strictEqual(URI.equal("urn:foo:a123,456", "urn:foo:A123,456"), false);
		strictEqual(URI.equal("urn:foo:a123%2C456", "URN:FOO:a123%2c456"), true);
	});

	test("URN Resolving", function () {
		//example from epoberezkin
		strictEqual(URI.resolve('', 'urn:some:ip:prop'), 'urn:some:ip:prop');
		strictEqual(URI.resolve('#', 'urn:some:ip:prop'), 'urn:some:ip:prop');
		strictEqual(URI.resolve('urn:some:ip:prop', 'urn:some:ip:prop'), 'urn:some:ip:prop');
		strictEqual(URI.resolve('urn:some:other:prop', 'urn:some:ip:prop'), 'urn:some:ip:prop');
	});

	//
	// URN UUID
	//

	test("UUID Parsing", function () {
		//example from RFC 4122
		var components = URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
		strictEqual(components.error, undefined, "errors");
		strictEqual(components.scheme, "urn", "scheme");
		//strictEqual(components.authority, undefined, "authority");
		strictEqual(components.userinfo, undefined, "userinfo");
		strictEqual(components.host, undefined, "host");
		strictEqual(components.port, undefined, "port");
		strictEqual(components.path, undefined, "path");
		strictEqual(components.query, undefined, "query");
		strictEqual(components.fragment, undefined, "fragment");
		strictEqual(components.nid, "uuid", "nid");
		strictEqual(components.nss, undefined, "nss");
		strictEqual(components.uuid, "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "uuid");

		components = URI.parse("urn:uuid:notauuid-7dec-11d0-a765-00a0c91e6bf6");
		notStrictEqual(components.error, undefined, "errors");
	});

	test("UUID Serialization", function () {
		//example from RFC 4122
		var components = {
			scheme : "urn",
			nid : "uuid",
			uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"
		};
		strictEqual(URI.serialize(components), "urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6");

		components = {
			scheme : "urn",
			nid : "uuid",
			uuid : "notauuid-7dec-11d0-a765-00a0c91e6bf6"
		};
		strictEqual(URI.serialize(components), "urn:uuid:notauuid-7dec-11d0-a765-00a0c91e6bf6");
	});

	test("UUID Equals", function () {
		strictEqual(URI.equal("URN:UUID:F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6", "urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"), true);
	});

	test("URN NID Override", function () {
		var components = URI.parse("urn:foo:f81d4fae-7dec-11d0-a765-00a0c91e6bf6", {nid:"uuid"});
		strictEqual(components.error, undefined, "errors");
		strictEqual(components.scheme, "urn", "scheme");
		strictEqual(components.path, undefined, "path");
		strictEqual(components.nid, "foo", "nid");
		strictEqual(components.nss, undefined, "nss");
		strictEqual(components.uuid, "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "uuid");

		var components = {
			scheme : "urn",
			nid : "foo",
			uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"
		};
		strictEqual(URI.serialize(components, {nid:"uuid"}), "urn:foo:f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
	});
}

//
// Mailto
//

if (URI.SCHEMES["mailto"]) {

	//module("Mailto");

	test("Mailto Parse", function () {
		var components;

		//tests from RFC 6068

		components = URI.parse("mailto:chris@example.com");
		strictEqual(components.error, undefined, "error");
		strictEqual(components.scheme, "mailto", "scheme");
		strictEqual(components.userinfo, undefined, "userinfo");
		strictEqual(components.host, undefined, "host");
		strictEqual(components.port, undefined, "port");
		strictEqual(components.path, undefined, "path");
		strictEqual(components.query, undefined, "query");
		strictEqual(components.fragment, undefined, "fragment");
		deepEqual(components.to, ["chris@example.com"], "to");
		strictEqual(components.subject, undefined, "subject");
		strictEqual(components.body, undefined, "body");
		strictEqual(components.headers, undefined, "headers");

		components = URI.parse("mailto:infobot@example.com?subject=current-issue");
		deepEqual(components.to, ["infobot@example.com"], "to");
		strictEqual(components.subject, "current-issue", "subject");

		components = URI.parse("mailto:infobot@example.com?body=send%20current-issue");
		deepEqual(components.to, ["infobot@example.com"], "to");
		strictEqual(components.body, "send current-issue", "body");

		components = URI.parse("mailto:infobot@example.com?body=send%20current-issue%0D%0Asend%20index");
		deepEqual(components.to, ["infobot@example.com"], "to");
		strictEqual(components.body, "send current-issue\x0D\x0Asend index", "body");

		components = URI.parse("mailto:list@example.org?In-Reply-To=%3C3469A91.D10AF4C@example.com%3E");
		deepEqual(components.to, ["list@example.org"], "to");
		deepEqual(components.headers, {"In-Reply-To":"<3469A91.D10AF4C@example.com>"}, "headers");

		components = URI.parse("mailto:majordomo@example.com?body=subscribe%20bamboo-l");
		deepEqual(components.to, ["majordomo@example.com"], "to");
		strictEqual(components.body, "subscribe bamboo-l", "body");

		components = URI.parse("mailto:joe@example.com?cc=bob@example.com&body=hello");
		deepEqual(components.to, ["joe@example.com"], "to");
		strictEqual(components.body, "hello", "body");
		deepEqual(components.headers, {"cc":"bob@example.com"}, "headers");

		components = URI.parse("mailto:joe@example.com?cc=bob@example.com?body=hello");
		if (URI.VALIDATE_SUPPORT) ok(components.error, "invalid header fields");

		components = URI.parse("mailto:gorby%25kremvax@example.com");
		deepEqual(components.to, ["gorby%kremvax@example.com"], "to gorby%kremvax@example.com");

		components = URI.parse("mailto:unlikely%3Faddress@example.com?blat=foop");
		deepEqual(components.to, ["unlikely?address@example.com"], "to unlikely?address@example.com");
		deepEqual(components.headers, {"blat":"foop"}, "headers");

		components = URI.parse("mailto:Mike%26family@example.org");
		deepEqual(components.to, ["Mike&family@example.org"], "to Mike&family@example.org");

		components = URI.parse("mailto:%22not%40me%22@example.org");
		deepEqual(components.to, ['"not@me"@example.org'], "to " + '"not@me"@example.org');

		components = URI.parse("mailto:%22oh%5C%5Cno%22@example.org");
		deepEqual(components.to, ['"oh\\\\no"@example.org'], "to " + '"oh\\\\no"@example.org');

		components = URI.parse("mailto:%22%5C%5C%5C%22it's%5C%20ugly%5C%5C%5C%22%22@example.org");
		deepEqual(components.to, ['"\\\\\\"it\'s\\ ugly\\\\\\""@example.org'], "to " + '"\\\\\\"it\'s\\ ugly\\\\\\""@example.org');

		components = URI.parse("mailto:user@example.org?subject=caf%C3%A9");
		deepEqual(components.to, ["user@example.org"], "to");
		strictEqual(components.subject, "caf\xE9", "subject");

		components = URI.parse("mailto:user@example.org?subject=%3D%3Futf-8%3FQ%3Fcaf%3DC3%3DA9%3F%3D");
		deepEqual(components.to, ["user@example.org"], "to");
		strictEqual(components.subject, "=?utf-8?Q?caf=C3=A9?=", "subject");  //TODO: Verify this

		components = URI.parse("mailto:user@example.org?subject=%3D%3Fiso-8859-1%3FQ%3Fcaf%3DE9%3F%3D");
		deepEqual(components.to, ["user@example.org"], "to");
		strictEqual(components.subject, "=?iso-8859-1?Q?caf=E9?=", "subject");  //TODO: Verify this

		components = URI.parse("mailto:user@example.org?subject=caf%C3%A9&body=caf%C3%A9");
		deepEqual(components.to, ["user@example.org"], "to");
		strictEqual(components.subject, "caf\xE9", "subject");
		strictEqual(components.body, "caf\xE9", "body");

		if (URI.IRI_SUPPORT) {
			components = URI.parse("mailto:user@%E7%B4%8D%E8%B1%86.example.org?subject=Test&body=NATTO");
			deepEqual(components.to, ["user@xn--99zt52a.example.org"], "to");
			strictEqual(components.subject, "Test", "subject");
			strictEqual(components.body, "NATTO", "body");
		}

	});

	test("Mailto Serialize", function () {
		var components;

		//tests from RFC 6068
		strictEqual(URI.serialize({scheme : "mailto", to : ["chris@example.com"]}), "mailto:chris@example.com");
		strictEqual(URI.serialize({scheme : "mailto", to : ["infobot@example.com"], body : "current-issue"}), "mailto:infobot@example.com?body=current-issue");
		strictEqual(URI.serialize({scheme : "mailto", to : ["infobot@example.com"], body : "send current-issue"}), "mailto:infobot@example.com?body=send%20current-issue");
		strictEqual(URI.serialize({scheme : "mailto", to : ["infobot@example.com"], body : "send current-issue\x0D\x0Asend index"}), "mailto:infobot@example.com?body=send%20current-issue%0D%0Asend%20index");
		strictEqual(URI.serialize({scheme : "mailto", to : ["list@example.org"], headers : {"In-Reply-To" : "<3469A91.D10AF4C@example.com>"}}), "mailto:list@example.org?In-Reply-To=%3C3469A91.D10AF4C@example.com%3E");
		strictEqual(URI.serialize({scheme : "mailto", to : ["majordomo@example.com"], body : "subscribe bamboo-l"}), "mailto:majordomo@example.com?body=subscribe%20bamboo-l");
		strictEqual(URI.serialize({scheme : "mailto", to : ["joe@example.com"], headers : {"cc" : "bob@example.com", "body" : "hello"}}), "mailto:joe@example.com?cc=bob@example.com&body=hello");
		strictEqual(URI.serialize({scheme : "mailto", to : ["gorby%25kremvax@example.com"]}), "mailto:gorby%25kremvax@example.com");
		strictEqual(URI.serialize({scheme : "mailto", to : ["unlikely%3Faddress@example.com"], headers : {"blat" : "foop"}}), "mailto:unlikely%3Faddress@example.com?blat=foop");
		strictEqual(URI.serialize({scheme : "mailto", to : ["Mike&family@example.org"]}), "mailto:Mike%26family@example.org");
		strictEqual(URI.serialize({scheme : "mailto", to : ['"not@me"@example.org']}), "mailto:%22not%40me%22@example.org");
		strictEqual(URI.serialize({scheme : "mailto", to : ['"oh\\\\no"@example.org']}), "mailto:%22oh%5C%5Cno%22@example.org");
		strictEqual(URI.serialize({scheme : "mailto", to : ['"\\\\\\"it\'s\\ ugly\\\\\\""@example.org']}), "mailto:%22%5C%5C%5C%22it's%5C%20ugly%5C%5C%5C%22%22@example.org");
		strictEqual(URI.serialize({scheme : "mailto", to : ["user@example.org"], subject : "caf\xE9"}), "mailto:user@example.org?subject=caf%C3%A9");
		strictEqual(URI.serialize({scheme : "mailto", to : ["user@example.org"], subject : "=?utf-8?Q?caf=C3=A9?="}), "mailto:user@example.org?subject=%3D%3Futf-8%3FQ%3Fcaf%3DC3%3DA9%3F%3D");
		strictEqual(URI.serialize({scheme : "mailto", to : ["user@example.org"], subject : "=?iso-8859-1?Q?caf=E9?="}), "mailto:user@example.org?subject=%3D%3Fiso-8859-1%3FQ%3Fcaf%3DE9%3F%3D");
		strictEqual(URI.serialize({scheme : "mailto", to : ["user@example.org"], subject : "caf\xE9", body : "caf\xE9"}), "mailto:user@example.org?subject=caf%C3%A9&body=caf%C3%A9");
		if (URI.IRI_SUPPORT) {
			strictEqual(URI.serialize({scheme : "mailto", to : ["us\xE9r@\u7d0d\u8c46.example.org"], subject : "Test", body : "NATTO"}), "mailto:us%C3%A9r@xn--99zt52a.example.org?subject=Test&body=NATTO");
		}

	});

	test("Mailto Equals", function () {
		//tests from RFC 6068
		strictEqual(URI.equal("mailto:addr1@an.example,addr2@an.example", "mailto:?to=addr1@an.example,addr2@an.example"), true);
		strictEqual(URI.equal("mailto:?to=addr1@an.example,addr2@an.example", "mailto:addr1@an.example?to=addr2@an.example"), true);
	});

}


text:
layout: single
date: 2015-01-13
title: 'My Application Libraries'
summary: 'These are a few of my favorite things'
comments: true
---

Many developers have a standard set of libraries that they commonly use on their projects, and I'm no different.  I have both a generic set of libraries that I use on virtually every project, and then I have specialized go-tos when I face a specific need.

This is my list:

## Universal libraries

- Autofac
  - Dependency Injection is a wonderful thing and I've personally found Autofac to be the best of the best.  It also works in all the places!
- Automapper
  - Once you go Automapper you never go back!  I remember the first time I tried to build a home-brew solution to manage these kinds of object mappings ... that's what we in the biz call the "bad old days".

## WPF, Microsoft Universal Apps, & Windows Phone 8

- Caliburn.Micro
  - MVVM changed the face of desktop development, and IHMO Caliburn.Micro best sets up a project for success out of the gate.
  - Yes, it does do more than 'just' MVVM, but I like it the way it also sets you up for DI in the process.  Now if we could only get them to drop their default home-built DI solution for Autofac ...
- Fody / Fody Property Changed
  - If Caliburn.Micro blew my mind for MVVM, Fody's PropertyChanged add-in did the same thing for INotifyPropertyChanged.  I never understood why Microsoft didn't create a better system to manage the INotifyPropertyChanged syntax (I'm not saying it's awful, but after using auto-properties for years ... it's pretty awful).
  - Fody's aspect-oriented nature lends itself to solving this problem perfectly.  Added bonuses of no Visual Studio plug-ins to install and it's free-ness (I'm looking at you, PostSharp!), it quickly established itself as a necessity in my projects.

## Web
- Glimpse
  - Being able to see a summary of the entire request stack during development, including DB queries?  Please, sir, can I have some more?

## Database
- SQL Server Data Tools
  - Personally, I despise Entity Framework Code First, primarily due to migrations.  I think it's a neat concept with an implementation that is fundamentally flawed.  I was on a project that became virtually unmaintainable due to issues specifically around Code First and Migrations.  No thank you!  SSDT with a database project is, IMHO, a MUCH cleaner solution.
  - Let the database tools do the database stuff.  Let your ORM deal with talking to the database.  Is that so hard?

redpajama_set_name: RedPajamaGithub


text:
package com.sequenceiq.cloudbreak.conclusion.step;

import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NETWORK_CCM_NOT_ACCESSIBLE;
import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NETWORK_CCM_NOT_ACCESSIBLE_DETAILS;
import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NETWORK_CLOUDERA_COM_NOT_ACCESSIBLE;
import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NETWORK_CLOUDERA_COM_NOT_ACCESSIBLE_DETAILS;
import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NETWORK_NEIGHBOUR_NOT_ACCESSIBLE;
import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NETWORK_NEIGHBOUR_NOT_ACCESSIBLE_DETAILS;
import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NETWORK_NGINX_UNREACHABLE;
import static com.sequenceiq.cloudbreak.conclusion.step.ConclusionMessage.NODE_STATUS_MONITOR_UNREACHABLE;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cloudera.thunderhead.telemetry.nodestatus.NodeStatusProto.HealthStatus;
import com.cloudera.thunderhead.telemetry.nodestatus.NodeStatusProto.NetworkDetails;
import com.cloudera.thunderhead.telemetry.nodestatus.NodeStatusProto.NodeStatus;
import com.cloudera.thunderhead.telemetry.nodestatus.NodeStatusProto.NodeStatusReport;
import com.sequenceiq.cloudbreak.client.RPCResponse;
import com.sequenceiq.cloudbreak.message.CloudbreakMessagesService;
import com.sequenceiq.cloudbreak.node.status.NodeStatusService;

@Component
public class NetworkCheckerConclusionStep extends ConclusionStep {

    private static final Logger LOGGER = LoggerFactory.getLogger(NetworkCheckerConclusionStep.class);

    private static final String NGINX_UNREACHABLE_ERROR_MESSAGE = "nginx is unreachable";

    @Inject
    private NodeStatusService nodeStatusService;

    @Inject
    private CloudbreakMessagesService cloudbreakMessagesService;

    @Override
    public Conclusion check(Long resourceId) {
        RPCResponse<NodeStatusReport> networkReport;
        try {
            networkReport = nodeStatusService.getNetworkReport(resourceId);
            LOGGER.debug("Network report response: {}", networkReport.getFirstTextMessage());
        } catch (Exception e) {
            LOGGER.warn("Network report failed, error: {}", e.getMessage());
            if (e.getMessage().contains(NGINX_UNREACHABLE_ERROR_MESSAGE)) {
                String conclusion = cloudbreakMessagesService.getMessage(NETWORK_NGINX_UNREACHABLE);
                LOGGER.warn(conclusion);
                return failed(conclusion, e.getMessage());
            }
            return failed(cloudbreakMessagesService.getMessage(NODE_STATUS_MONITOR_UNREACHABLE), e.getMessage());
        }
        if (networkReport.getResult() == null) {
            LOGGER.info("Network report result was null");
            return succeeded();
        }

        List<String> networkFailures = new ArrayList<>();
        List<String> networkFailureDetails = new ArrayList<>();
        checkNetworkFailures(networkReport, networkFailures, networkFailureDetails);

        if (networkFailures.isEmpty()) {
            return succeeded();
        } else {
            return failed(networkFailures.toString(), networkFailureDetails.toString());
        }
    }

    private void checkNetworkFailures(RPCResponse<NodeStatusReport> networkReport, List<String> networkFailures, List<String> networkFailureDetails) {
        for (NodeStatus nodeStatus : networkReport.getResult().getNodesList()) {
            NetworkDetails networkDetails = nodeStatus.getNetworkDetails();
            String host = nodeStatus.getStatusDetails().getHost();
            LOGGER.debug("Check network report for host: {}, details: {}", host, networkDetails);
            if (networkDetails.getCcmEnabled() && HealthStatus.NOK.equals(networkDetails.getCcmAccessible())) {
                networkFailures.add(cloudbreakMessagesService.getMessageWithArgs(NETWORK_CCM_NOT_ACCESSIBLE, host));
                String details = cloudbreakMessagesService.getMessageWithArgs(NETWORK_CCM_NOT_ACCESSIBLE_DETAILS, networkDetails.getCcmAccessible(), host);
                networkFailureDetails.add(details);
                LOGGER.warn(details);
            }
            if (HealthStatus.NOK.equals(networkDetails.getClouderaComAccessible())) {
                networkFailures.add(cloudbreakMessagesService.getMessageWithArgs(NETWORK_CLOUDERA_COM_NOT_ACCESSIBLE, host));
                String details = cloudbreakMessagesService.getMessageWithArgs(NETWORK_CLOUDERA_COM_NOT_ACCESSIBLE_DETAILS,
                        networkDetails.getClouderaComAccessible(), host);
                networkFailureDetails.add(details);
                LOGGER.warn(details);
            }
            if (networkDetails.getNeighbourScan() && HealthStatus.NOK.equals(networkDetails.getAnyNeighboursAccessible())) {
                networkFailures.add(cloudbreakMessagesService.getMessageWithArgs(NETWORK_NEIGHBOUR_NOT_ACCESSIBLE, host));
                String details = cloudbreakMessagesService.getMessageWithArgs(NETWORK_NEIGHBOUR_NOT_ACCESSIBLE_DETAILS,
                        networkDetails.getAnyNeighboursAccessible(), host);
                networkFailureDetails.add(details);
                LOGGER.warn(details);
            }
        }
    }
}


text:
<!DOCTYPE html>

      <video class='test1'>Do not show this</video>
      <video class='test2'>Do not show this</video>
      <video class='test3'>Do not show this</video>
      <video class='test4'>Do not show this</video>
      <video class='test5'>Do not show this</video>

      <video class='test5'>Do not show this</video>

      <video class='test1'>Do not show this</video>
      <video class='test2'>Do not show this</video>
      <video class='test3'>Do not show this</video>
      <video class='test4'>Do not show this</video>
      <video class='test5'>Do not show this</video>


text:
#include "config.h"
#include "core/fetch/ResourceFetcher.h"

#include "core/fetch/FetchInitiatorInfo.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/ResourcePtr.h"
#include "platform/exported/WrappedResourceResponse.h"
#include "platform/heap/Handle.h"
#include "platform/network/ResourceRequest.h"
#include "platform/testing/URLTestHelpers.h"
#include "platform/weborigin/KURL.h"
#include "public/platform/Platform.h"
#include "public/platform/WebURLResponse.h"
#include "public/platform/WebUnitTestSupport.h"
#include <gtest/gtest.h>

namespace blink {

class ResourceFetcherTestMockFetchContext : public FetchContext {
public:
    static ResourceFetcherTestMockFetchContext* create()
    {
        return new ResourceFetcherTestMockFetchContext;
    }

    virtual ~ResourceFetcherTestMockFetchContext() { }

    bool allowImage(bool imagesEnabled, const KURL&) const override { return true; }
    bool canRequest(Resource::Type, const ResourceRequest&, const KURL&, const ResourceLoaderOptions&, bool forPreload, FetchRequest::OriginRestriction) const override { return true; }
    bool shouldLoadNewResource(Resource::Type) const override { return true; }

    void setCachePolicy(CachePolicy policy) { m_policy = policy; }
    CachePolicy cachePolicy() const override { return m_policy; }

private:
    ResourceFetcherTestMockFetchContext()
        : m_policy(CachePolicyVerify)
    { }

    CachePolicy m_policy;
};

class ResourceFetcherTest : public ::testing::Test {
};

class TestResourceFactory : public ResourceFactory {
public:
    TestResourceFactory(Resource::Type type = Resource::Raw)
        : ResourceFactory(type) { }

    Resource* create(const ResourceRequest& request, const String& charset) const override
    {
        return new Resource(request, type());
    }
};

TEST_F(ResourceFetcherTest, StartLoadAfterFrameDetach)
{
    KURL secureURL(ParsedURLString, "https://secureorigin.test/image.png");
    // Try to request a url. The request should fail, no resource should be returned,
    // and no resource should be present in the cache.
    ResourceFetcher* fetcher = ResourceFetcher::create(nullptr);
    FetchRequest fetchRequest = FetchRequest(ResourceRequest(secureURL), FetchInitiatorInfo());
    ResourcePtr<Resource> resource = fetcher->requestResource(fetchRequest, TestResourceFactory());
    EXPECT_EQ(resource.get(), static_cast<Resource*>(nullptr));
    EXPECT_EQ(memoryCache()->resourceForURL(secureURL), static_cast<Resource*>(nullptr));
}

TEST_F(ResourceFetcherTest, UseExistingResource)
{
    ResourceFetcher* fetcher = ResourceFetcher::create(ResourceFetcherTestMockFetchContext::create());

    KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
    ResourcePtr<Resource> resource = new Resource(url, Resource::Image);
    memoryCache()->add(resource.get());
    ResourceResponse response;
    response.setURL(url);
    response.setHTTPStatusCode(200);
    response.setHTTPHeaderField("Cache-Control", "max-age=3600");
    resource->responseReceived(response, nullptr);
    resource->finish();

    FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
    ResourcePtr<Resource> newResource = fetcher->requestResource(fetchRequest, TestResourceFactory(Resource::Image));
    EXPECT_EQ(resource, newResource);
    memoryCache()->remove(resource.get());
}

TEST_F(ResourceFetcherTest, Vary)
{
    ResourceFetcher* fetcher = ResourceFetcher::create(ResourceFetcherTestMockFetchContext::create());

    KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
    ResourcePtr<Resource> resource = new Resource(url, Resource::Raw);
    memoryCache()->add(resource.get());
    ResourceResponse response;
    response.setURL(url);
    response.setHTTPStatusCode(200);
    response.setHTTPHeaderField("Cache-Control", "max-age=3600");
    response.setHTTPHeaderField("Vary", "*");
    resource->responseReceived(response, nullptr);
    resource->finish();
    ASSERT_TRUE(resource->hasVaryHeader());

    FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
    Platform::current()->unitTestSupport()->registerMockedURL(url, WebURLResponse(), "");
    ResourcePtr<Resource> newResource = fetcher->requestResource(fetchRequest, TestResourceFactory());
    EXPECT_NE(resource, newResource);

    memoryCache()->remove(newResource.get());
    Platform::current()->unitTestSupport()->unregisterMockedURL(url);
}

TEST_F(ResourceFetcherTest, VaryOnBack)
{
    ResourceFetcherTestMockFetchContext* context = ResourceFetcherTestMockFetchContext::create();
    context->setCachePolicy(CachePolicyHistoryBuffer);
    ResourceFetcher* fetcher = ResourceFetcher::create(context);

    KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
    ResourcePtr<Resource> resource = new Resource(url, Resource::Raw);
    memoryCache()->add(resource.get());
    ResourceResponse response;
    response.setURL(url);
    response.setHTTPStatusCode(200);
    response.setHTTPHeaderField("Cache-Control", "max-age=3600");
    response.setHTTPHeaderField("Vary", "*");
    resource->responseReceived(response, nullptr);
    resource->finish();
    ASSERT_TRUE(resource->hasVaryHeader());

    FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
    ResourcePtr<Resource> newResource = fetcher->requestResource(fetchRequest, TestResourceFactory());
    EXPECT_EQ(resource, newResource);

    memoryCache()->remove(newResource.get());
}

TEST_F(ResourceFetcherTest, VaryImage)
{
    ResourceFetcher* fetcher = ResourceFetcher::create(ResourceFetcherTestMockFetchContext::create());

    KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
    ResourceResponse response;
    response.setURL(url);
    response.setHTTPStatusCode(200);
    response.setHTTPHeaderField("Cache-Control", "max-age=3600");
    response.setHTTPHeaderField("Vary", "*");
    URLTestHelpers::registerMockedURLLoadWithCustomResponse(url, "white-1x1.png", WebString::fromUTF8(""), WrappedResourceResponse(response));

    FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
    ResourcePtr<Resource> resource = fetcher->requestResource(fetchRequestOriginal, TestResourceFactory(Resource::Image));
    ASSERT_TRUE(resource.get());
    Platform::current()->unitTestSupport()->serveAsynchronousMockedRequests();
    ASSERT_TRUE(resource->hasVaryHeader());

    FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
    ResourcePtr<Resource> newResource = fetcher->requestResource(fetchRequest, TestResourceFactory(Resource::Image));
    EXPECT_EQ(resource, newResource);

    memoryCache()->remove(newResource.get());
    Platform::current()->unitTestSupport()->unregisterMockedURL(url);
}

TEST_F(ResourceFetcherTest, RevalidateWhileLoading)
{
    KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
    Platform::current()->unitTestSupport()->registerMockedURL(url, WebURLResponse(), "");

    ResourceFetcher* fetcher1 = ResourceFetcher::create(ResourceFetcherTestMockFetchContext::create());
    ResourceRequest request1(url);
    request1.setHTTPHeaderField("Cache-control", "no-cache");
    FetchRequest fetchRequest1 = FetchRequest(request1, FetchInitiatorInfo());
    ResourcePtr<Resource> resource1 = fetcher1->requestResource(fetchRequest1, TestResourceFactory(Resource::Image));
    ResourceResponse response;
    response.setURL(url);
    response.setHTTPStatusCode(200);
    response.setHTTPHeaderField("Cache-Control", "max-age=3600");
    response.setHTTPHeaderField("etag", "1234567890");
    resource1->responseReceived(response, nullptr);
    resource1->finish();

    ResourceFetcherTestMockFetchContext* context = ResourceFetcherTestMockFetchContext::create();
    context->setCachePolicy(CachePolicyRevalidate);
    ResourceFetcher* fetcher2 = ResourceFetcher::create(context);
    FetchRequest fetchRequest2(url, FetchInitiatorInfo());
    ResourcePtr<Resource> resource2 = fetcher2->requestResource(fetchRequest2, TestResourceFactory(Resource::Image));
    EXPECT_EQ(resource1, resource2);
}

} // namespace blink


text:
const {
  assertSummaryTable,
  assertBreadcrumbs,
} = require('../../support/assertions')
const fixtures = require('../../fixtures')
const selectors = require('../../../../selectors')
const urls = require('../../../../../src/lib/urls')

const HIERARCHY_STRINGS = {
  dnbDescription:
    'This hierarchy information from Dun & Bradstreet cannot be edited.',
  dnbEmpty: 'This company is not related to any other company records.',
  manualHierarchyDescription:
    'This hierarchy information is manually recorded (linked) by Data Hub users. This means it can be different from the Dun & Bradstreet hierarchy, which in the future will replace this manually recorded information.',
}

const assertAddress = ({ address, registeredAddress }) => {
  const addressSelector1 =
    '[data-test="addressesDetailsContainer"] td:nth-child(1)'
  const addressSelector2 =
    '[data-test="addressesDetailsContainer"] td:nth-child(2)'

  if (address) {
    cy.get(addressSelector1).contains('Registered').should('not.exist')
    address.map((line, index) => {
      cy.get(addressSelector1)
        .find(`li:nth-child(${index + 1})`)
        .should('have.text', line)
    })
  } else if (address === null) {
    cy.get(addressSelector1).should('not.exist')
  }

  if (registeredAddress) {
    cy.get(addressSelector2).contains('Registered').should('exist')
    registeredAddress.map((line, index) => {
      cy.get(addressSelector2)
        .find(`li:nth-child(${index + 1})`)
        .should('have.text', line)
    })
  } else if (registeredAddress === null) {
    cy.get(addressSelector2).should('not.exist')
  }
}

describe('Companies business details', () => {
  context(
    'when viewing business details for a Dun & Bradstreet GHQ company on the One List not in the UK',
    () => {
      before(() => {
        cy.visit(
          urls.companies.businessDetails(fixtures.company.oneListCorp.id)
        )
        it('should display the "Pending Change Request" text', () => {
          cy.contains('Checking for pending change requests')
        })
      })

      it('should render breadcrumbs', () => {
        assertBreadcrumbs({
          Home: urls.dashboard(),
          Companies: urls.companies.index(),
          [fixtures.company.oneListCorp.name]: urls.companies.detail(
            fixtures.company.oneListCorp.id
          ),
          'Business details': null,
        })
      })

      it('should display the "Business details" heading', () => {
        cy.get(selectors.localHeader().heading).should(
          'have.text',
          'Business details'
        )
      })

      it('should display the "Last updated" paragraph', () => {
        cy.contains('Last updated on: 26 Nov 2017').should('be.visible')
      })

      it('should not display the "Pending Change Request" box', () => {
        cy.contains(
          'Changes to these business details are currently being reviewed.'
        ).should('not.exist')
      })

      it('should display the "Are these business details right?" details summary', () => {
        cy.get(selectors.companyBusinessDetails().whereDoesInformation).should(
          'be.visible'
        )
      })

      it('should not display the "Unarchive" link', () => {
        cy.get(selectors.companyBusinessDetails().unarchiveLink).should(
          'not.exist'
        )
      })

      it('should display the "About" details container', () => {
        assertSummaryTable({
          dataTest: 'aboutDetailsContainer',
          heading: 'About One List Corp',
          showEditLink: true,
          content: {
            'Trading name': 'Not set',
            'Annual turnover': '£33.5M+',
            'Number of employees': '500+',
            Website: 'Not set',
            'Business description':
              'This is a dummy company for testing the One List',
            Segment: 'High export potential',
            'Sub-segment': 'Sustain: nurture & grow',
          },
        })
      })

      it('should display the "Addresses" details container', () => {
        assertSummaryTable({
          dataTest: 'addressesDetailsContainer',
          heading: 'Addresses',
          showEditLink: false,
        })
      })

      it('should display the address', () => {
        assertAddress({
          address: ["12 St George's Road", 'Paris', '75001', 'France'],
          registeredAddress: [
            "12 St George's Road",
            'Paris',
            '75001',
            'France',
          ],
        })
      })

      it('should not display the "DIT region" details container', () => {
        cy.get(
          selectors.detailsContainer('regionDetailsContainer').container
        ).should('not.exist')
      })

      it('should display the "DIT sector" details container', () => {
        assertSummaryTable({
          dataTest: 'sectorDetailsContainer',
          heading: 'DIT sector',
          showEditLink: true,
          content: ['Retail'],
        })
      })

      it('should display the "Global Account Manager - One List" details container', () => {
        assertSummaryTable({
          dataTest: 'oneListDetailsContainer',
          heading: 'Global Account Manager – One List',
          showEditLink: false,
          content: {
            'One List tier': 'Tier A - Strategic Account',
            'Global Account Manager':
              'Travis GreeneIST - Sector Advisory ServicesLondon',
          },
        })
      })

      it('should display the "Business hierarchy" details container heading', () => {
        assertSummaryTable({
          dataTest: 'businessHierarchyDetailsContainer',
          heading: 'Business hierarchy',
          showEditLink: true,
          content: {
            [HIERARCHY_STRINGS.dnbDescription]: null,
            [HIERARCHY_STRINGS.dnbEmpty]: null,
            [HIERARCHY_STRINGS.manualHierarchyDescription]: null,
            'Headquarter type': 'Global HQ',
            Subsidiaries: 'NoneLink a subsidiary',
          },
        })
      })

      it('should not display the "Documents from CDMS" details container', () => {
        cy.get(
          selectors.detailsContainer('documentsDetailsContainer').container
        ).should('not.exist')
      })

      it('should not display the "Archive company" details container', () => {
        cy.get('[data-test=archive-company-container]').should('not.exist')
      })
    }
  )

  context(
    'when viewing business details for a US company with administrative area information',
    () => {
      before(() => {
        cy.visit(urls.companies.businessDetails(fixtures.company.usCompany.id))
      })

      it('should display the state in the address', () => {
        assertAddress({
          address: [
            '12 First Street',
            'New York',
            '765413',
            'Texas',
            'United States',
          ],
          registeredAddress: [
            '12 First Street',
            'New York',
            '765413',
            'Texas',
            'United States',
          ],
        })
      })
    }
  )

  context(
    'when viewing business details for a Canadian company with administrative area information',
    () => {
      before(() => {
        cy.visit(
          urls.companies.businessDetails(fixtures.company.canadianCompany.id)
        )
      })

      it('should display province in the address', () => {
        assertAddress({
          address: [
            '12 Second Street',
            'Ottawa',
            '765413',
            'Ontario',
            'Canada',
          ],
          registeredAddress: [
            '12 Second Street',
            'Ottawa',
            '765413',
            'Ontario',
            'Canada',
          ],
        })
      })
    }
  )

  context(
    'when viewing business details for a Data Hub company on the One List in the UK',
    () => {
      before(() => {
        cy.visit(urls.companies.businessDetails(fixtures.company.venusLtd.id))
      })

      it('should not display the "Pending Change Request" text', () => {
        cy.contains('Checking for pending change requests').should('not.exist')
      })

      it('should render breadcrumbs', () => {
        assertBreadcrumbs({
          Home: urls.dashboard(),
          Companies: urls.companies.index(),
          [fixtures.company.venusLtd.name]: urls.companies.detail(
            fixtures.company.venusLtd.id
          ),
          'Business details': null,
        })
      })

      it('should display the "Business details" heading', () => {
        cy.get(selectors.localHeader().heading).should(
          'have.text',
          'Business details'
        )
      })

      it('should display the "Last updated" paragraph', () => {
        cy.contains('Last updated on: 15 Jul 2016').should('be.visible')
      })

      it('should not display the "Are these business details right?" details summary', () => {
        cy.get(selectors.companyBusinessDetails().whereDoesInformation).should(
          'not.exist'
        )
      })

      it('should not display the "Unarchive" link', () => {
        cy.get(selectors.companyBusinessDetails().unarchiveLink).should(
          'not.exist'
        )
      })

      it('should display the "About" details container', () => {
        assertSummaryTable({
          dataTest: 'aboutDetailsContainer',
          heading: 'About Venus Ltd',
          showEditLink: true,
          content: {
            'Business type': 'Company',
            'Trading name': 'Not set',
            'CDMS reference': 'ORG-10096257',
            'Annual turnover': 'Not set',
            'Number of employees': 'Not set',
            Website: 'Not set',
            'Business description': 'This is a dummy company for testing',
            Segment: 'No export segment or not known',
            'Sub-segment': 'No sub export segment or not known',
          },
        })
      })

      it('should display the "Addresses" details container', () => {
        assertSummaryTable({
          dataTest: 'addressesDetailsContainer',
          heading: 'Addresses',
          showEditLink: true,
        })
      })

      it('should display the address', () => {
        assertAddress({
          address: ['66 Marcham Road', 'Bordley', 'BD23 8RZ', 'United Kingdom'],
          registeredAddress: [
            '66 Marcham Road',
            'Bordley',
            'BD23 8RZ',
            'United Kingdom',
          ],
        })
      })

      it('should display the "DIT region" details container', () => {
        assertSummaryTable({
          dataTest: 'regionDetailsContainer',
          heading: 'DIT region',
          showEditLink: true,
          content: ['North West'],
        })
      })

      it('should display the "DIT sector" details container', () => {
        assertSummaryTable({
          dataTest: 'sectorDetailsContainer',
          heading: 'DIT sector',
          showEditLink: true,
          content: ['Retail'],
        })
      })

      it('should display the "Global Account Manager - One List" details container', () => {
        assertSummaryTable({
          dataTest: 'oneListDetailsContainer',
          heading: 'Global Account Manager – One List',
          showEditLink: true,
          content: {
            'One List tier': 'Tier A - Strategic Account',
            'Global Account Manager':
              'Travis GreeneIST - Sector Advisory ServicesLondon',
          },
        })
      })

      it('should display the "Business hierarchy" details container', () => {
        assertSummaryTable({
          dataTest: 'businessHierarchyDetailsContainer',
          heading: 'Business hierarchy',
          showEditLink: true,
          content: {
            [HIERARCHY_STRINGS.manualHierarchyDescription]: null,
            'Global HQ': 'Archived LtdRemove link',
          },
        })
      })

      it('should display the "Last updated" paragraph', () => {
        cy.contains('Last updated on: 15 Jul 2016').should('be.visible')
      })

      it('should display the "Documents from CDMS" details container', () => {
        assertSummaryTable({
          dataTest: 'documentsDetailsContainer',
          heading: 'Documents from CDMS',
          showEditLink: false,
          content: ['View files and documents (opens in a new window or tab)'],
        })
      })

      it('should display the "Archive company" details container', () => {
        cy.get('[data-test=archive-company-container]').should('be.visible')
      })
    }
  )

  context(
    'when viewing business details for a Dun & Bradstreet company not on the One List',
    () => {
      before(() => {
        cy.visit(urls.companies.businessDetails(fixtures.company.dnbCorp.id))
        it('should display the "Pending Change Request" text', () => {
          cy.contains('Checking for pending change requests')
        })
      })

      it('should render breadcrumbs', () => {
        assertBreadcrumbs({
          Home: urls.dashboard(),
          Companies: urls.companies.index(),
          [fixtures.company.dnbCorp.name]: urls.companies.detail(
            fixtures.company.dnbCorp.id
          ),
          'Business details': null,
        })
      })

      it('should display the "Business details" heading', () => {
        cy.get(selectors.localHeader().heading).should(
          'have.text',
          'Business details'
        )
      })

      it('should display the "Last updated" paragraph', () => {
        cy.contains('Last updated on: 26 Oct 2018').should('be.visible')
      })

      it('should display the "Are these business details right?" details summary', () => {
        cy.get(selectors.companyBusinessDetails().whereDoesInformation).should(
          'be.visible'
        )
      })

      it('should not display the "Unarchive" link', () => {
        cy.get(selectors.companyBusinessDetails().unarchiveLink).should(
          'not.exist'
        )
      })

      it('should display the "About" details container', () => {
        assertSummaryTable({
          dataTest: 'aboutDetailsContainer',
          heading: 'About DnB Corp',
          showEditLink: true,
          content: {
            'Trading name': 'DnBD&B',
            'Annual turnover':
              '£720,000This is an estimated numberWhat does that mean?Actual turnover is not available for this business. The number has been modelled by Dun & Bradstreet, based on similar businesses.',
            'Number of employees':
              '95This is an estimated numberWhat does that mean?Actual number of employees is not available for this business. The number has been modelled by Dun & Bradstreet, based on similar businesses.',
            Website: 'Not set',
            'Business description':
              'This is a dummy company for testing companies with DnB data',
            Segment: 'Not high export potential',
            'Sub-segment': 'Reassure: change the game',
          },
        })
      })

      it('should display the "Addresses" details container', () => {
        assertSummaryTable({
          dataTest: 'addressesDetailsContainer',
          heading: 'Addresses',
          showEditLink: false,
        })
      })

      it('should display the address', () => {
        assertAddress({
          address: ['1 Main Road', 'Rome', '001122', 'Italy'],
          registeredAddress: ['1 Main Road', 'Rome', '001122', 'Italy'],
        })
      })

      it('should not display the "DIT region" details container', () => {
        cy.get(
          selectors.detailsContainer('regionDetailsContainer').container
        ).should('not.exist')
      })

      it('should display the "DIT sector" details container', () => {
        assertSummaryTable({
          dataTest: 'sectorDetailsContainer',
          heading: 'DIT sector',
          showEditLink: true,
          content: ['Retail'],
        })
      })

      it('should not display the "Global Account Manager - One List" details container', () => {
        cy.get(
          selectors.detailsContainer('oneListDetailsContainer').container
        ).should('not.exist')
      })

      it('should display the "Business hierarchy" details container', () => {
        assertSummaryTable({
          dataTest: 'businessHierarchyDetailsContainer',
          heading: 'Business hierarchy',
          showEditLink: false,
          content: [
            HIERARCHY_STRINGS.dnbDescription,
            HIERARCHY_STRINGS.dnbEmpty,
          ],
        })
      })

      it('should not display the "Documents from CDMS" details container', () => {
        cy.get(
          selectors.detailsContainer('documentsDetailsContainer').container
        ).should('not.exist')
      })

      it('should not display the "Archive company" details container', () => {
        cy.get('[data-test=archive-company-container]').should('not.exist')
      })
    }
  )

  context(
    'when viewing business details for an automatically archived Data Hub company',
    () => {
      before(() => {
        cy.visit(
          urls.companies.businessDetails(
            fixtures.company.automaticallyArchivedLtd.id
          )
        )
      })

      it('should display it was automatically archived and the date', () => {
        cy.contains(
          'This company was automatically archived on 06 Jul 2018.'
        ).should('be.visible')
      })

      it('should display the reason it was archived', () => {
        cy.contains('Reason: Company is dissolved').should('be.visible')
      })
    }
  )

  context(
    'when viewing business details for an archived Data Hub company',
    () => {
      before(() => {
        cy.visit(
          urls.companies.businessDetails(fixtures.company.archivedLtd.id)
        )
      })

      it('should render breadcrumbs', () => {
        assertBreadcrumbs({
          Home: urls.dashboard(),
          Companies: urls.companies.index(),
          [fixtures.company.archivedLtd.name]: urls.companies.detail(
            fixtures.company.archivedLtd.id
          ),
          'Business details': null,
        })
      })

      it('should display the "Business details" heading', () => {
        cy.get(selectors.localHeader().heading).should(
          'have.text',
          'Business details'
        )
      })

      it('should display the "Last updated" paragraph', () => {
        cy.contains('Last updated on: 16 Jul 2017').should('be.visible')
      })

      it('should not display the "Are these business details right?" details summary', () => {
        cy.get(selectors.companyBusinessDetails().whereDoesInformation).should(
          'not.exist'
        )
      })

      it('should display the date the company was archived and by whom', () => {
        cy.contains(
          'This company was archived on 06 Jul 2018 by John Rogers'
        ).should('be.visible')
      })

      it('should display the reason it was dissolved', () => {
        cy.contains('Reason: Company is dissolved').should('be.visible')
      })

      it('should display the "Unarchive" link', () => {
        cy.contains('Unarchive').should('be.visible')
      })

      it('should display the "About" details container', () => {
        assertSummaryTable({
          dataTest: 'aboutDetailsContainer',
          heading: 'About Archived Ltd',
          showEditLink: false,
          content: {
            'Business type': 'Company',
            'Trading name': 'Not set',
            'Annual turnover': '£33.5M+',
            'Number of employees': '500+',
            Website: 'Not set',
            'Business description':
              'This is a dummy company for testing archived features',
            Segment: 'No export segment or not known',
            'Sub-segment': 'No sub export segment or not known',
          },
        })
      })

      it('should display the "Addresses" details container', () => {
        assertSummaryTable({
          dataTest: 'addressesDetailsContainer',
          heading: 'Addresses',
          showEditLink: false,
        })
      })

      it('should display the address', () => {
        assertAddress({
          address: ['16 Getabergsvagen', 'Geta', '22340', 'Malta'],
          registeredAddress: ['16 Getabergsvagen', 'Geta', '22340', 'Malta'],
        })
      })

      it('should not display the "DIT region" details container', () => {
        cy.get(
          selectors.detailsContainer('regionDetailsContainer').container
        ).should('not.exist')
      })

      it('should display the "DIT sector" details container', () => {
        assertSummaryTable({
          dataTest: 'sectorDetailsContainer',
          heading: 'DIT sector',
          showEditLink: false,
          content: ['Retail'],
        })
      })

      it('should display the "Global Account Manager - One List" details container', () => {
        assertSummaryTable({
          dataTest: 'oneListDetailsContainer',
          heading: 'Global Account Manager – One List',
          showEditLink: false,
          content: {
            'One List tier': 'Tier A - Strategic Account',
            'Global Account Manager':
              'Travis GreeneIST - Sector Advisory ServicesLondon',
          },
        })
      })

      it('should display the "Business hierarchy" details container', () => {
        assertSummaryTable({
          dataTest: 'businessHierarchyDetailsContainer',
          heading: 'Business hierarchy',
          showEditLink: false,
          content: {
            [HIERARCHY_STRINGS.manualHierarchyDescription]: null,
            'Headquarter type': 'Global HQ',
            Subsidiaries: '2 subsidiaries',
          },
        })
      })

      it('should not display the "Documents from CDMS" details container', () => {
        cy.get(
          selectors.detailsContainer('documentsDetailsContainer').container
        ).should('not.exist')
      })

      it('should not display the "Archive company" details container', () => {
        cy.get('[data-test=archive-company-container]').should('not.exist')
      })
    }
  )

  context(
    'when viewing business details for a company with minimal data',
    () => {
      before(() => {
        cy.visit(
          urls.companies.businessDetails(
            fixtures.company.minimallyMinimalLtd.id
          )
        )
      })

      it('should render breadcrumbs', () => {
        assertBreadcrumbs({
          Home: urls.dashboard(),
          Companies: urls.companies.index(),
          [fixtures.company.minimallyMinimalLtd.name]: urls.companies.detail(
            fixtures.company.minimallyMinimalLtd.id
          ),
          'Business details': null,
        })
      })

      it('should display the "Business details" heading', () => {
        cy.get(selectors.localHeader().heading).should(
          'have.text',
          'Business details'
        )
      })

      it('should display the "Last updated" paragraph', () => {
        cy.contains('Last updated on: 11 Dec 2015').should('be.visible')
      })

      it('should not display the "Are these business details right?" details summary', () => {
        cy.get(selectors.companyBusinessDetails().whereDoesInformation).should(
          'not.exist'
        )
      })

      it('should not display the "Unarchive" link', () => {
        cy.get(selectors.companyBusinessDetails().unarchiveLink).should(
          'not.exist'
        )
      })

      it('should display the "About" details container', () => {
        assertSummaryTable({
          dataTest: 'aboutDetailsContainer',
          heading: 'About Minimally Minimal Ltd',
          showEditLink: true,
          content: {
            'Trading name': 'Not set',
            'Annual turnover': 'Not set',
            'Number of employees': 'Not set',
            Website: 'Not set',
            'Business description': 'No description has been added',
            Segment: 'No export segment or not known',
            'Sub-segment': 'No sub export segment or not known',
          },
        })
      })

      it('should display the "Addresses" details container', () => {
        assertSummaryTable({
          dataTest: 'addressesDetailsContainer',
          heading: 'Addresses',
          showEditLink: true,
        })
      })

      it('should display the address', () => {
        assertAddress({
          address: ['United Kingdom'],
          registeredAddress: null,
        })
      })

      it('should display the "DIT region" details container', () => {
        assertSummaryTable({
          dataTest: 'regionDetailsContainer',
          heading: 'DIT region',
          showEditLink: true,
          content: ['Not set'],
        })
      })

      it('should display the "DIT sector" details container', () => {
        assertSummaryTable({
          dataTest: 'sectorDetailsContainer',
          heading: 'DIT sector',
          showEditLink: true,
          content: ['Advanced Engineering'],
        })
      })

      it('should not display the "Global Account Manager - One List" details container heading', () => {
        cy.get(
          selectors.detailsContainer('oneListDetailsContainer').container
        ).should('not.exist')
      })

      it('should display the "Business hierarchy" details container', () => {
        assertSummaryTable({
          dataTest: 'businessHierarchyDetailsContainer',
          heading: 'Business hierarchy',
          showEditLink: true,
          content: {
            [HIERARCHY_STRINGS.manualHierarchyDescription]: null,
            'Global HQ': 'NoneLink to the Global HQ',
          },
        })
      })

      it('should not display the "Documents from CDMS" details container', () => {
        cy.get(
          selectors.detailsContainer('documentsDetailsContainer').container
        ).should('not.exist')
      })

      it('should display the "Archive company" details container', () => {
        cy.get('[data-test=archive-company-container]').should('be.visible')
      })
    }
  )
})


text:
#include "router_core_private.h"
#include <stdio.h>

struct qdr_error_t {
    qdr_field_t *name;
    qdr_field_t *description;
    pn_data_t   *info;
};

ALLOC_DECLARE(qdr_error_t);
ALLOC_DEFINE(qdr_error_t);

qdr_error_t *qdr_error_from_pn(pn_condition_t *pn)
{
    if (!pn)
        return 0;

    qdr_error_t *error = new_qdr_error_t();
    ZERO(error);

    const char *name = pn_condition_get_name(pn);
    if (name && *name)
        error->name = qdr_field(name);

    const char *desc = pn_condition_get_description(pn);
    if (desc && *desc)
        error->description = qdr_field(desc);

    error->info = pn_data(0);
    pn_data_copy(error->info, pn_condition_info(pn));

    return error;
}

qdr_error_t *qdr_error(const char *name, const char *description)
{
    qdr_error_t *error = new_qdr_error_t();

    error->name        = qdr_field(name);
    error->description = qdr_field(description);
    error->info        = 0;

    return error;
}

void qdr_error_free(qdr_error_t *error)
{
    if (error == 0)
        return;

    qdr_field_free(error->name);
    qdr_field_free(error->description);
    if (error->info)
        pn_data_free(error->info);

    free_qdr_error_t(error);
}

void qdr_error_copy(qdr_error_t *from, pn_condition_t *to)
{
    if (from->name) {
        unsigned char *name = qd_iterator_copy(from->name->iterator);
        pn_condition_set_name(to, (char*) name);
        free(name);
    }

    if (from->description) {
        unsigned char *desc = qd_iterator_copy(from->description->iterator);
        pn_condition_set_description(to, (char*) desc);
        free(desc);
    }

    if (from->info)
        pn_data_copy(pn_condition_info(to), from->info);
}

char *qdr_error_description(qdr_error_t *err)
{
    if (!err || !err->description || !err->description->iterator)
        return 0;
    int   length = qd_iterator_length(err->description->iterator);
    char *text   = (char*) malloc(length + 1);
    qd_iterator_ncopy(err->description->iterator, (unsigned char*) text, length);
    text[length] = '\0';
    return text;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/emoji_image_view"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_gravity="center"
        tools:src="@tools:sample/avatars" />
</FrameLayout>


text:
Glossary
-------------

.. glossary::
    :sorted:

    package
        A Python package is a module defined by a directory, containing
        a ``__init__.py`` file, and can contain other modules or other
        packages within it.

        ::

            package/
                __init__.py
                subpackage/
                    __init__.py
                submodule.py

        see also, :term:`namespace package`

    distribution
        Separately installable sets of Python modules as stored in the
        Python package index, and installed by distutils or setuptools.

        *definition taken from* `PEP 382`_ *text*

    vendor package
        Groups of files installed by an operating system's packaging
        mechanism (e.g. Debian or Redhat packages install on Linux systems).

        *definition taken from* `PEP 382`_ *text*

    namespace package
        Mechanism for splitting a single Python package across multiple
        directories on disk. One or more distributions (see :term:`distribution`)
        may provide modules which exist inside the same :term:`namespace package`.

        *definition taken from* `PEP 382`_ *text*

    module
        An importable python namespace defined in a single file.

.. _PEP 382: http://www.python.org/dev/peps/pep-0382/


text:
var Hapi = require('hapi')
var Good = require('good')
var Vision = require('vision')
var Bcrypt = require('bcrypt')
var Users = require('./users-db')
var BasicAuth = require('hapi-auth-basic')

// create new server instance
var server = new Hapi.Server()

// add server's connection information
server.connection({
  host: 'localhost',
  port: 3000
})

// register plugins to server instance
server.register([
  {
    register: Good,
    options: {
      ops: {
        interval: 10000
      },
      reporters: {
        console: [
          {
            module: 'good-squeeze',
            name: 'Squeeze',
            args: [ { log: '*', response: '*', request: '*' } ]
          },
          {
            module: 'good-console'
          },
          'stdout'
        ]
      }
    }
  },
  {
    register: BasicAuth
  }
], function (err) {
  if (err) {
    server.log('error', 'failed to install plugins')

    throw err
  }

  server.log('info', 'Plugins registered')

  var basicValidation  = function (request, username, password, callback) {
    var user = Users[ username ]

    if (!user) {
      return callback(null, false)
    }

    Bcrypt.compare(password, user.password, function (err, isValid) {
      server.log('info', 'user authentication successful')
      callback(err, isValid, user)
    })
  }

  // Create auth strategy:
  // 1. without setting it as default
  server.auth.strategy('basic', 'basic', { validateFunc: basicValidation })
  // set default auth strategy separately
  // all routes added afterwards will follow the default, required auth strategy
  server.auth.default('basic')

  // 2. set it as default
  // all routes will automatically require and follow the default strategy
  // server.auth.strategy('basic', 'basic', true, { validateFunc: basicValidation })

  server.log('info', 'Registered auth strategy: basic auth')

  var routes = require('./routes')
  server.route(routes)
  server.log('info', 'Routes registered')

  // start your server after plugin registration
  server.start(function (err) {
    if (err) {
      server.log('error', 'failed to start server')
      server.log('error', err)

      throw err
    }

    server.log('info', 'Server running at: ' + server.info.uri)
  })
})


text:
package com.newsblur.util;

public enum ListOrderFilter {
    ASCENDING,
    DESCENDING
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Synops. Gen. Arthonia 7 (1890)

#### Original name
Spiloma gregarium var. concolor Turner

### Remarks
null


text:
from updatorr.handler_base import GenericPrivateTrackerHandler
from updatorr.utils import register_tracker_handler
import urllib2

class AnidubHandler(GenericPrivateTrackerHandler):
    """This class implements .torrent files downloads
    for http://tr.anidub.com tracker."""

    login_url = 'http://tr.anidub.com/takelogin.php'
    cookie_logged_in = 'uid'

    def get_download_link(self):
        """Tries to find .torrent file download link at forum thread page
        and return that one."""
        response, page_html = self.get_resource(self.resource_url)
        page_links = self.find_links(page_html)
        download_link = None
        for page_link in page_links:
            if 'login.php?returnto=' in page_link:
                download_link = None
                self.debug('Login is required to download torrent file.')
                if self.login(self.get_settings('login'), self.get_settings('password')):
                    download_link = self.get_download_link()
            if 'download.php?id=' in page_link:
                download_link = 'http://tr.anidub.com/%s' % urllib2.unquote(page_link).replace('&', '&')
        return download_link

register_tracker_handler('tr.anidub.com', AnidubHandler)


text:
package com.bbking.weixin.api.model;

import java.io.Serializable;

/**
 *
查询订单接口返回实体类

 *
 * @author yexiangyang
 * @create 2016-11-30
 */
public class OrderQueryRO implements Serializable {
    /**
     * 返回状态码
     */
    private String return_code;
    /**
     * 返回信息
     */
    private String return_msg;
    /**
     * 公众账号ID
     */
    private String appid;
    /**
     * 商户号
     */
    private String mch_id;
    /**
     * 子商户公众账号ID
     */
    private String sub_appid;
    /**
     * 子商户号
     */
    private String sub_mch_id;
    /**
     * 随机字符串
     */
    private String nonce_str;
    /**
     * 签名
     */
    private String sign;
    /**
     * 业务结果
     */
    private String result_code;
    /**
     * 错误代码
     */
    private String err_code;
    /**
     * 错误代码描述
     */
    private String err_code_des;
    /**
     * 设备号
     */
    private String device_info;
    /**
     * 用户标识
     */
    private String openid;
    /**
     * 是否关注公众账号
     */
    private String is_subscribe;
    /**
     * 用户子标识
     */
    private String sub_openid;
    /**
     * 是否关注子公众账号
     */
    private String sub_is_subscribe;
    /**
     * 交易类型
     */
    private String trade_type;
    /**
     * 交易状态
     */
    private String trade_state;
    /**
     * 付款银行
     */
    private String bank_type;
    /**
     * 商品详情
     */
    private String detail;
    /**
     * 总金额
     */
    private Integer total_fee;
    /**
     * 货币种类
     */
    private String fee_type;
    /**
     * 现金支付金额
     */
    private Integer cash_fee;
    /**
     * 现金支付货币类型
     */
    private String cash_fee_type;
    /**
     * 代金券或立减优惠金额
     */
    private Integer coupon_fee;
    /**
     * 代金券或立减优惠使用数量
     */
    private Integer coupon_count;
    /**
     * 代金券或立减优惠批次ID
     */
    private String coupon_batch_id_1;
    /**
     * 代金券或立减优惠ID
     */
    private String coupon_id_1;
    /**
     * 单个代金券或立减优惠支付金额
     */
    private String coupon_fee_1;
    /**
     * 微信支付订单号
     */
    private String transaction_id;
    /**
     * 商户订单号
     */
    private String out_trade_no;
    /**
     * 商家数据包
     */
    private String attach;
    /**
     * 支付完成时间
     */
    private String time_end;
    /**
     * 交易状态描述
     */
    private String trade_state_desc;

    public String getReturn_code() {
        return return_code;
    }

    public void setReturn_code(String return_code) {
        this.return_code = return_code;
    }

    public String getReturn_msg() {
        return return_msg;
    }

    public void setReturn_msg(String return_msg) {
        this.return_msg = return_msg;
    }

    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public String getMch_id() {
        return mch_id;
    }

    public void setMch_id(String mch_id) {
        this.mch_id = mch_id;
    }

    public String getSub_appid() {
        return sub_appid;
    }

    public void setSub_appid(String sub_appid) {
        this.sub_appid = sub_appid;
    }

    public String getSub_mch_id() {
        return sub_mch_id;
    }

    public void setSub_mch_id(String sub_mch_id) {
        this.sub_mch_id = sub_mch_id;
    }

    public String getNonce_str() {
        return nonce_str;
    }

    public void setNonce_str(String nonce_str) {
        this.nonce_str = nonce_str;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getResult_code() {
        return result_code;
    }

    public void setResult_code(String result_code) {
        this.result_code = result_code;
    }

    public String getErr_code() {
        return err_code;
    }

    public void setErr_code(String err_code) {
        this.err_code = err_code;
    }

    public String getErr_code_des() {
        return err_code_des;
    }

    public void setErr_code_des(String err_code_des) {
        this.err_code_des = err_code_des;
    }

    public String getDevice_info() {
        return device_info;
    }

    public void setDevice_info(String device_info) {
        this.device_info = device_info;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public String getIs_subscribe() {
        return is_subscribe;
    }

    public void setIs_subscribe(String is_subscribe) {
        this.is_subscribe = is_subscribe;
    }

    public String getSub_openid() {
        return sub_openid;
    }

    public void setSub_openid(String sub_openid) {
        this.sub_openid = sub_openid;
    }

    public String getSub_is_subscribe() {
        return sub_is_subscribe;
    }

    public void setSub_is_subscribe(String sub_is_subscribe) {
        this.sub_is_subscribe = sub_is_subscribe;
    }

    public String getTrade_type() {
        return trade_type;
    }

    public void setTrade_type(String trade_type) {
        this.trade_type = trade_type;
    }

    public String getTrade_state() {
        return trade_state;
    }

    public void setTrade_state(String trade_state) {
        this.trade_state = trade_state;
    }

    public String getBank_type() {
        return bank_type;
    }

    public void setBank_type(String bank_type) {
        this.bank_type = bank_type;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public Integer getTotal_fee() {
        return total_fee;
    }

    public void setTotal_fee(Integer total_fee) {
        this.total_fee = total_fee;
    }

    public String getFee_type() {
        return fee_type;
    }

    public void setFee_type(String fee_type) {
        this.fee_type = fee_type;
    }

    public Integer getCash_fee() {
        return cash_fee;
    }

    public void setCash_fee(Integer cash_fee) {
        this.cash_fee = cash_fee;
    }

    public String getCash_fee_type() {
        return cash_fee_type;
    }

    public void setCash_fee_type(String cash_fee_type) {
        this.cash_fee_type = cash_fee_type;
    }

    public Integer getCoupon_fee() {
        return coupon_fee;
    }

    public void setCoupon_fee(Integer coupon_fee) {
        this.coupon_fee = coupon_fee;
    }

    public Integer getCoupon_count() {
        return coupon_count;
    }

    public void setCoupon_count(Integer coupon_count) {
        this.coupon_count = coupon_count;
    }

    public String getCoupon_batch_id_1() {
        return coupon_batch_id_1;
    }

    public void setCoupon_batch_id_1(String coupon_batch_id_1) {
        this.coupon_batch_id_1 = coupon_batch_id_1;
    }

    public String getCoupon_id_1() {
        return coupon_id_1;
    }

    public void setCoupon_id_1(String coupon_id_1) {
        this.coupon_id_1 = coupon_id_1;
    }

    public String getCoupon_fee_1() {
        return coupon_fee_1;
    }

    public void setCoupon_fee_1(String coupon_fee_1) {
        this.coupon_fee_1 = coupon_fee_1;
    }

    public String getTransaction_id() {
        return transaction_id;
    }

    public void setTransaction_id(String transaction_id) {
        this.transaction_id = transaction_id;
    }

    public String getOut_trade_no() {
        return out_trade_no;
    }

    public void setOut_trade_no(String out_trade_no) {
        this.out_trade_no = out_trade_no;
    }

    public String getAttach() {
        return attach;
    }

    public void setAttach(String attach) {
        this.attach = attach;
    }

    public String getTime_end() {
        return time_end;
    }

    public void setTime_end(String time_end) {
        this.time_end = time_end;
    }

    public String getTrade_state_desc() {
        return trade_state_desc;
    }

    public void setTrade_state_desc(String trade_state_desc) {
        this.trade_state_desc = trade_state_desc;
    }
}


text:
package gnu.classpath.examples.swing;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;

/**
 * A simple demo showing various spinners in different states.
 */
public class SpinnerDemo
  extends JPanel
  implements ActionListener
{
  private JCheckBox spinnerState1;
  private JSpinner spinner1;
  private JSpinner spinner2;

  private JCheckBox spinnerState2;
  private JSpinner spinner3;
  private JSpinner spinner4;

  private JCheckBox spinnerState3;
  private JSpinner spinner5;
  private JSpinner spinner6;

  /**
   * Creates a new demo instance.
   */
  public SpinnerDemo()
  {
    super();
    createContent();
  }

  /**
   * When the demo is run independently, the frame is displayed, so we should
   * initialise the content panel (including the demo content and a close
   * button).  But when the demo is run as part of the Swing activity board,
   * only the demo content panel is used, the frame itself is never displayed,
   * so we can avoid this step.
   */
  void initFrameContent()
  {
    JPanel closePanel = new JPanel();
    JButton closeButton = new JButton("Close");
    closeButton.setActionCommand("CLOSE");
    closeButton.addActionListener(this);
    closePanel.add(closeButton);
    add(closePanel, BorderLayout.SOUTH);
  }

  /**
   * Returns a panel with the demo content.  The panel
   * uses a BorderLayout(), and the BorderLayout.SOUTH area
   * is empty, to allow callers to add controls to the
   * bottom of the panel if they want to (a close button is
   * added if this demo is being run as a standalone demo).
   */
  private void createContent()
  {
    setLayout(new BorderLayout());
    JPanel panel = new JPanel(new GridLayout(3, 1));
    panel.add(createPanel1());
    panel.add(createPanel2());
    panel.add(createPanel3());
    add(panel);
  }

  private JPanel createPanel1()
  {
    JPanel panel = new JPanel(new BorderLayout());
    this.spinnerState1 = new JCheckBox("Enabled", true);
    this.spinnerState1.setActionCommand("COMBO_STATE1");
    this.spinnerState1.addActionListener(this);
    panel.add(this.spinnerState1, BorderLayout.EAST);

    JPanel controlPanel = new JPanel();
    controlPanel.setBorder(BorderFactory.createTitledBorder(
        "Number Spinner: "));
    this.spinner1 = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 10.0, 0.5));
    this.spinner2 = new JSpinner(new SpinnerNumberModel(50, 0, 100, 5));
    this.spinner2.setFont(new Font("Dialog", Font.PLAIN, 20));
    controlPanel.add(this.spinner1);
    controlPanel.add(this.spinner2);

    panel.add(controlPanel);

    return panel;
  }

  private JPanel createPanel2()
  {
    JPanel panel = new JPanel(new BorderLayout());
    this.spinnerState2 = new JCheckBox("Enabled", true);
    this.spinnerState2.setActionCommand("COMBO_STATE2");
    this.spinnerState2.addActionListener(this);
    panel.add(this.spinnerState2, BorderLayout.EAST);

    JPanel controlPanel = new JPanel();
    controlPanel.setBorder(BorderFactory.createTitledBorder("Date Spinner: "));
    this.spinner3 = new JSpinner(new SpinnerDateModel(new Date(), null, null,
        Calendar.DATE));

    this.spinner4 = new JSpinner(new SpinnerDateModel(new Date(), null, null,
        Calendar.YEAR));
    this.spinner4.setFont(new Font("Dialog", Font.PLAIN, 20));

    controlPanel.add(this.spinner3);
    controlPanel.add(this.spinner4);

    panel.add(controlPanel);

    return panel;
  }

  private JPanel createPanel3()
  {
    JPanel panel = new JPanel(new BorderLayout());
    this.spinnerState3 = new JCheckBox("Enabled", true);
    this.spinnerState3.setActionCommand("COMBO_STATE3");
    this.spinnerState3.addActionListener(this);
    panel.add(this.spinnerState3, BorderLayout.EAST);

    JPanel controlPanel = new JPanel();
    controlPanel.setBorder(BorderFactory.createTitledBorder("List Spinner: "));
    this.spinner5 = new JSpinner(new SpinnerListModel(new Object[] {"Red",
        "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"}));

    this.spinner6 = new JSpinner(new SpinnerListModel(new Object[] {"Red",
        "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"}));
    this.spinner6.setValue("Yellow");
    this.spinner6.setFont(new Font("Dialog", Font.PLAIN, 20));

    controlPanel.add(this.spinner5);
    controlPanel.add(this.spinner6);

    panel.add(controlPanel);

    return panel;
  }

  public void actionPerformed(ActionEvent e)
  {
    if (e.getActionCommand().equals("COMBO_STATE1"))
    {
      spinner1.setEnabled(spinnerState1.isSelected());
      spinner2.setEnabled(spinnerState1.isSelected());
    }
    else if (e.getActionCommand().equals("COMBO_STATE2"))
    {
      spinner3.setEnabled(spinnerState2.isSelected());
      spinner4.setEnabled(spinnerState2.isSelected());
    }
    else if (e.getActionCommand().equals("COMBO_STATE3"))
    {
      spinner5.setEnabled(spinnerState3.isSelected());
      spinner6.setEnabled(spinnerState3.isSelected());
    }
    else if (e.getActionCommand().equals("CLOSE"))
    {
      System.exit(0);
    }
  }

  public static void main(String[] args)
  {
    SwingUtilities.invokeLater
    (new Runnable()
     {
       public void run()
       {
         SpinnerDemo app = new SpinnerDemo();
         app.initFrameContent();
         JFrame frame = new JFrame("Spinner Demo");
         frame.getContentPane().add(app);
         frame.pack();
         frame.setVisible(true);
       }
     });
  }

  /**
   * Returns a DemoFactory that creates a SpinnerDemo.
   *
   * @return a DemoFactory that creates a SpinnerDemo
   */
  public static DemoFactory createDemoFactory()
  {
    return new DemoFactory()
    {
      public JComponent createDemo()
      {
        return new SpinnerDemo();
      }
    };
  }
}