src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
CollectionsX { public static <T> List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2) { final ArrayList<T> list = new ArrayList<>(list1.size() + list2.size()); if (!list1.isEmpty()) { list.addAll(list1); } if (!list2.isEmpty()) { list.addAll(list2); } return list; } private CollectionsX(); static List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2); } | @Test public void should_return_concatenated_list() throws Exception { assertThat(CollectionsX.concat(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6))) .isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6)); } |
AppRouter { public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); } AppRouter(); @VisibleForTesting AppRouter(IntentFactory intentFactory); Intent loginIntent(Context context); } | @Test public void should_return_loginIntent() throws Exception { tested.loginIntent(mockedContext); verify(mockedIntentFactory).create(mockedContext, LoginActivity.class); } |
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); } | @Test public void should_return_false_when_email_is_null() throws Exception { assertThat(tested.isValid(null)).isFalse(); }
@Test public void should_return_false_when_email_is_invalid() throws Exception { assertThat(tested.isValid("abc")).isFalse(); }
@Test public void should_return_true_when_email_is_valid() throws Exception { assertThat(tested.isValid("[email protected]")).isTrue(); } |
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } @Bean GroovyConditionCache conditionCache(
@Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled); } | @Test public void testPolicyConditionCacheConfigDisabled() { assertThat(this.policyConditionCacheConfig.conditionCache(true), instanceOf(NonCachingGroovyConditionCache.class)); }
@Test public void testPolicyConditionCacheConfigEnabled() { assertThat(this.policyConditionCacheConfig.conditionCache(false), instanceOf(InMemoryGroovyConditionCache.class)); } |
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); String toDecisionKey(); @Override int hashCode(); @Override boolean equals(final Object obj); PolicyEvaluationRequestV1 getRequest(); LinkedHashSet<String> getPolicySetIds(); String getResourceId(); String getSubjectId(); String getZoneId(); static final String ANY_POLICY_SET_KEY; static final LinkedHashSet<String> EVALUATION_ORDER_ANY_POLICY_SET_KEY; } | @Test public void testKeyEqualsForSameRequests() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); request.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); PolicyEvaluationRequestV1 otherRequest = new PolicyEvaluationRequestV1(); otherRequest.setAction(ACTION_GET); otherRequest.setSubjectIdentifier(AGENT_MULDER); otherRequest.setResourceIdentifier(XFILES_ID); otherRequest.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey otherKey = new PolicyEvaluationRequestCacheKey(otherRequest, ZONE_NAME); assertTrue(key.equals(otherKey)); }
@Test public void testKeyEqualsForDifferentRequests() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); request.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); PolicyEvaluationRequestV1 otherRequest = new PolicyEvaluationRequestV1(); otherRequest.setAction(ACTION_GET); otherRequest.setSubjectIdentifier(AGENT_MULDER); otherRequest.setResourceIdentifier(XFILES_ID); PolicyEvaluationRequestCacheKey otherKey = new PolicyEvaluationRequestCacheKey(otherRequest, ZONE_NAME); assertFalse(key.equals(otherKey)); } |
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); } | @Test(dataProvider = "validScript") public void testParseValidScript(final String script, final Map<String, Object> boundVariables, final boolean expectedResult) throws ConditionParsingException { ConditionScript parsedScript = this.shell.parse(script); Assert.assertNotNull(parsedScript); }
@Test(dataProvider = "illegalScript", expectedExceptions = IllegalArgumentException.class) public void testParseBlankScript(final String script) throws ConditionParsingException { this.shell.parse(script); }
@Test(dataProvider = "blackListedScript", expectedExceptions = ConditionParsingException.class) public void testParseBlackListedScript(final String script) throws ConditionParsingException { this.shell.parse(script); } |
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); } | @Test(dataProvider = "validScript") public void testExecuteValidScript(final String script, final Map<String, Object> boundVariables, final boolean expectedResult) throws ConditionParsingException { Assert.assertEquals(this.shell.execute(script, boundVariables), expectedResult); }
@Test(dataProvider = "illegalScript", expectedExceptions = IllegalArgumentException.class) public void testExecuteBlankScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); }
@Test(dataProvider = "invalidScript", expectedExceptions = ClassCastException.class) public void testExecuteInvalidScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); }
@Test(dataProvider = "blackListedScript", expectedExceptions = ConditionParsingException.class) public void testExecuteBlackListedScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); } |
URL implements URLComponent, Validating, Comparable<URL> { public URL withProtocol(Protocol protocol) { if (protocol.equals(this.protocol)) { return this; } return new URL(userName, password, protocol, host, port, path, parameters, anchor); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); } | @Test public void testWithProtocol() { URL u = URL.parse("http: URL u2 = u.withProtocol(Protocols.WS); assertEquals(u.getPath(), u2.getPath()); assertNotEquals(u.getProtocol(), u2.getProtocol()); assertEquals(Protocols.HTTP, u.getProtocol()); assertEquals(Protocols.WS, u2.getProtocol()); } |
Path implements URLComponent, Iterable<PathElement> { public static Path parse(String path) { return Path.parse(path, false); } Path(PathElement... elements); Path(NormalizeResult n); static Path parse(String path); static Path parse(String path, boolean decode); Path toURLDecodedPath(); Iterator<PathElement> iterator(); PathElement lastElement(); Path normalize(); Path replace(String old, String nue); final Path elideEmptyElements(); Path prepend(String part); Path append(String part); static Path merge(Path... paths); boolean isParentOf(Path path); boolean isChildOf(Path path); int size(); PathElement[] getElements(); Path getChildPath(); String toStringWithLeadingSlash(); Path getParentPath(); boolean lastElementMatches(CharSequence s); boolean lastElementMatches(CharSequence s, boolean ignoreCase); @Override String toString(); static AbstractBuilder<PathElement, Path> builder(); @Override boolean isValid(); @Override String getComponentName(); boolean isProbableFileReference(); void appendTo(StringBuilder sb); PathElement getElement(int ix); PathElement getLastElement(); @Override boolean equals(Object obj); @Override int hashCode(); URI toURI(); URI toURIWithLeadingSlash(); String[] toStringArray(); } | @Test public void testLeadingAndTrailingSlashesDontAffectEquality() { Path a = Path.parse("foo/bar/baz"); Path b = Path.parse("/foo/bar/baz"); Path c = Path.parse("foo/bar/baz/"); Path d = Path.parse("/foo/bar/baz/"); Path e = Path.parse("foo/bar/baz/bean"); Path f = Path.parse("moo/bar/baz"); assertEquals(a, b); assertEquals(a, c); assertEquals(a, d); assertEquals(b, a); assertEquals(b, c); assertEquals(b, d); assertEquals(c, a); assertEquals(c, b); assertEquals(c, d); assertNotEquals(a, e); assertNotEquals(b, e); assertNotEquals(c, e); assertNotEquals(d, e); assertNotEquals(a, f); assertNotEquals(b, f); assertNotEquals(c, f); assertNotEquals(d, f); } |
ChainRunner { @Inject public ChainRunner(ExecutorService svc, ReentrantScope scope) { Checks.notNull("svc", svc); Checks.notNull("scope", scope); this.svc = svc; this.scope = scope; } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); } | @Test(timeout = 10000) public void testChainRunner() throws Exception, Throwable { AtomicBoolean cancelled = new AtomicBoolean(); ChainRunner cr = new ChainRunner(svc, scope); TestCallback chainWithDeferResults = new TestCallback(); TestCallback dontRespondChainResults = new TestCallback(); TestCallback plainChainResults = new TestCallback(); TestCallback errorChainResults = new TestCallback(); TestCallback rejectChainResults = new TestCallback(); TestCallback remnantChainResults = new TestCallback(); try (AutoCloseable cl = scope.enter()) { cr.submit(chain, chainWithDeferResults, cancelled); cr.submit(dontRespond, dontRespondChainResults, cancelled); cr.submit(plainChain, plainChainResults, cancelled); cr.submit(errorChain, errorChainResults, cancelled); cr.submit(rejectIt, rejectChainResults, cancelled); cr.submit(remnantChain, remnantChainResults, cancelled); cr.submit(remnantChain, remnantChainResults, cancelled); } chainWithDeferResults.assertGotResponse().assertActeurClass(AddedA.class).throwIfError().assertNotRejected(); dontRespondChainResults.assertNoResponse().throwIfError(); plainChainResults.throwIfError().assertGotResponse().assertActeurClass(AddedA.class).assertNotRejected(); errorChainResults.assertException(SpecialError.class); rejectChainResults.throwIfError().assertRejected(); remnantChainResults.throwIfError().assertRejected(); } |
ChainRunner { public <A extends AbstractActeur<T, R, S>, S extends ActeurState<T, R>, P extends Chain<? extends A, ?>, T, R extends T> void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled) { ActeurInvoker<A, S, P, T, R> cc = new ActeurInvoker<>(svc, scope, chain, onDone, cancelled); try (QuietAutoCloseable ac = scope.enter(chain, cc.deferral)) { if (firstSync) { try { cc.call(); } catch (Exception ex) { Exceptions.chuck(ex); } } else { svc.submit(scope.wrap(cc)); } } } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); } | @Test(timeout = 20000) public void testMultiChainRunner() throws Exception, Throwable { AtomicBoolean cancelled = new AtomicBoolean(); List<ArrayChain<AbstractActeur<Response, ResponseImpl, ActeurState<Response, ResponseImpl>>, ?>> l = new LinkedList<>(); for (int i = 0; i < 5; i++) { ArrayChain<AbstractActeur<Response, ResponseImpl, ActeurState<Response, ResponseImpl>>, ?> ch = new NamedChain("Chain " + i, deps, AbstractActeur.class) .add(FirstA.class).add(Rejecter.class).add(SecondWithoutTimeoutA.class).add(EndA.class); l.add(ch); } l.add(plainChain); ChainsRunner cr = new ChainsRunner(svc, scope, new ChainRunner(svc, scope)); TestCallback callback = new TestCallback(); cr.submit(l, callback, cancelled); callback.throwIfError().assertNotRejected().assertGotResponse(); l.remove(l.size() - 1); callback = new TestCallback(); cr.submit(l, callback, cancelled); callback.throwIfError().assertNoResponse(); } |
StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } StrictTransportSecurityHeader(); @Override StrictTransportSecurity toValue(CharSequence value); @Override CharSequence toCharSequence(StrictTransportSecurity value); } | @Test public void testStrictTransportHeader() { HeaderValueType<StrictTransportSecurity> h = new StrictTransportSecurityHeader(); assertEquals(StrictTransportSecurity.FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD, h.toValue(StrictTransportSecurity.FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD.toString())); assertEquals(StrictTransportSecurity.ONE_YEAR, h.toValue(StrictTransportSecurity.ONE_YEAR.toString())); } |
CookieHeaderNetty428 extends AbstractHeader<Cookie[]> { @Override public Cookie[] toValue(CharSequence value) { ServerCookieDecoder decoder = strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX; Set<Cookie> result = decoder.decode(notNull("value", value).toString()); return result == null ? EMPTY : result.toArray(new Cookie[result.size()]); } CookieHeaderNetty428(boolean strict); @Override CharSequence toCharSequence(Cookie[] value); @Override Cookie[] toValue(CharSequence value); } | @Test @SuppressWarnings("deprecation") public void testLegacyCookies() { CookieHeader h = new CookieHeader(); io.netty.handler.codec.http.DefaultCookie a = new io.netty.handler.codec.http.DefaultCookie("a", "a"); io.netty.handler.codec.http.DefaultCookie b = new io.netty.handler.codec.http.DefaultCookie("b", "b"); io.netty.handler.codec.http.DefaultCookie c = new io.netty.handler.codec.http.DefaultCookie("c", "c"); String val = h.toString(new io.netty.handler.codec.http.Cookie[]{a, b, c}); io.netty.handler.codec.http.Cookie[] result = h.toValue(val); assertNotNull(result); assertNotNull(val); assertTrue("Should contain all cookies:" + val, val.contains("a") && val.contains("b") && val.contains("c")); assertEquals(3, result.length); } |
FrameOptions { public static FrameOptions allowFrom(URI uri) { return new FrameOptions(FrameOptionType.ALLOW_FROM, notNull("uri", uri)); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; } | @Test public void testAllowFrom() { FrameOptions fo = FrameOptions.allowFrom(URI.create("http: assertEquals(URI.create("http: assertSame(FrameOptionType.ALLOW_FROM, fo.type()); assertEquals("ALLOW-FROM http: FrameOptions fo2 = FrameOptions.parse(fo.toString()); assertEquals(fo, fo2); assertEquals(fo.hashCode(), fo2.hashCode()); FrameOptions fo3 = FrameOptions.parse(fo.toString().toLowerCase()); assertEquals(fo, fo3); assertEquals(fo.hashCode(), fo3.hashCode()); assertEquals(fo.toString(), fo3.toString()); } |
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; } | @Test(expected=IllegalArgumentException.class) public void testMissingArgument() { FrameOptions.parse("DENY http: }
@Test(expected=IllegalArgumentException.class) public void testMissingArgumen2t() { FrameOptions.parse("SAMEORIGIN http: }
@Test(expected=IllegalArgumentException.class) public void testInvalidName() { FrameOptions.parse("PERCEIVE http: }
@Test(expected=IllegalArgumentException.class) public void testInvalidName2() { FrameOptions.parse("DENI http: }
@Test(expected=IllegalArgumentException.class) public void testInvalidUri() { FrameOptions.parse("ALLOW-FROM \\u0000 } |
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); } | @Test public void testHostEquality() { Label l1 = new Label("one"); Label l2 = new Label("one"); Label l3 = new Label("ONE"); Label l4 = new Label("oNe"); assertEquals(l1, l2); assertEquals(l2, l3); assertEquals(l3, l4); assertEquals(l1, l4); assertEquals(l2, l4); Host one = Host.parse("WWW.Test.CoM"); Host two = Host.parse("www.test.com"); assertEquals(one, two); }
@Test public void testParse() throws Exception { test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: }
@Test public void testHostParents() { Host h = Host.parse("www.timboudreau.com"); assertEquals(Host.parse("timboudreau.com"), h.getParentDomain()); Label[] l = h.getLabels(); assertEquals(new Label("com"), l[0]); assertEquals(new Label("timboudreau"), l[1]); assertEquals(new Label("www"), l[2]); assertEquals(new Label("com"), h.getTopLevelDomain()); assertEquals(new Label("timboudreau"), h.getDomain()); }
@Test public void testSameDomain() { Host h = Host.parse("weblogs.java.net"); assertTrue(h.isDomain("java.net")); assertTrue(h.isDomain("weblogs.java.net")); assertFalse(h.isDomain("bubble.java.net")); assertFalse(h.isDomain("java.com")); } |
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; } | @Test(expected=IllegalArgumentException.class) public void testInvalidParse1() { StrictTransportSecurity.parse(""); }
@Test(expected=NullArgumentException.class) public void testInvalidConstruct() { StrictTransportSecurity.parse(null); }
@Test(expected=IllegalArgumentException.class) public void testInvalidParse2() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=61; foodbar"); }
@Test(expected=IllegalArgumentException.class) public void testInvalidParse3() { StrictTransportSecurity.parse("foodbar; preload; includeSubDomains; max-age=61;"); }
@Test(expected=NumberFormatException.class) public void testInvalidParse4() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=073r8b;"); }
@Test(expected=NumberFormatException.class) public void testInvalidParse5() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=infinity;"); } |
PasswordHasher { public boolean checkPassword(String unhashed, String hashed) { try { String[] saltAndPassAndAlgorithm = findSalt(hashed); if (saltAndPassAndAlgorithm.length == 1) { byte[] bytes = hash(unhashed, algorithm); byte[] check = Base64.getDecoder().decode(hashed); return Arrays.equals(bytes, check); } if (saltAndPassAndAlgorithm.length != 3) { encryptPassword("DaCuBYLAlxBbT6lTyatauRp2iXCsf9WGDi8a2SyWeFVsoxGBk3Y3l1l9IHie" + "+aVuOGQBD8mZlrhj8yGjl1ghjw==", "3J5pgcx0", algorithm); return false; } String enc = encryptPassword(unhashed, saltAndPassAndAlgorithm[1], decodeAlgorithm(saltAndPassAndAlgorithm[0])); return slowEquals(enc, hashed); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } } @Inject PasswordHasher(Settings settings, Charset charset); boolean checkPassword(String unhashed, String hashed); String hash(String s); String encryptPassword(String password); static final String SETTINGS_KEY_PASSWORD_SALT; static final String SETTINGS_KEY_HASHING_ALGORITHM; static final String DEFAULT_HASHING_ALGORITHM; static final String SETTINGS_KEY_RANDOM_SALT_LENGTH; static final int DEFAULT_RANDOM_SALT_LENGTH; } | @Test public void testCheckPassword() throws IOException, NoSuchAlgorithmException { assertTrue(true); PasswordHasher h = new PasswordHasher(new SettingsBuilder().build(), Charset.forName("UTF-8")); String pw = "password"; String enc = h.encryptPassword(pw); assertNotNull(enc); String pw2 = "somethingElse"; String enc2 = h.encryptPassword(pw2); assertNotNull(enc2); assertNotEquals(enc, enc2); boolean matches = h.checkPassword(pw2, enc2); assertTrue(matches); matches = h.checkPassword(pw, enc); assertTrue(matches); matches = h.checkPassword(pw2, enc); assertFalse(matches); matches = h.checkPassword(pw, enc2); assertFalse(matches); String old = "a:Du4EC8d82VujiPSlommA2XHrQLtUvytrowONoiG5q0yjG3Ed:4jhJV/hZ4Ab0liMsX0HDG/qJCIvgPCqyAeVB69n+ZdOWNWTXOCypD+WlzJELpKQ1/8tHL6jI709ogWTiJt0/9Q=="; assertTrue("Something has broken password compatibility", h.checkPassword("somethingElse", old)); old = "a:3wWOjtsJci7mL3wknhhtCsZnNmywjXI9w39Y2SiUVIfOaA2s:XZ6i/sDDGW0tEGYW3Bbcg1BitWugNm8DNQnx1p7CowRj9b0tkUQXRwqez60rSmRnBqOSRDw/4FUcg43fdliCZw=="; assertTrue("Something has broken password compatibility", h.checkPassword("password", old)); } |
RotatingRealmProvider implements Provider<Realm> { @Override public Realm get() { Duration since1970 = Duration.ofMillis(System.currentTimeMillis()); long minutesSince1970 = since1970.toMinutes(); long intervals = minutesSince1970 / interval.toMinutes(); return new Realm(Strings.interleave(Long.toString(intervals, 36), salt)); } @Inject RotatingRealmProvider(Settings s); @Override Realm get(); static final String SETTINGS_KEY_ROTATE_INTERVAL_MINUTES; static final int DEFAULT_ROTATE_INTERVAL; } | @Test public void testDurationConversionWorks() { RotatingRealmProvider prov = new RotatingRealmProvider(Settings.EMPTY); Realm realm = prov.get(); assertEquals(realm, prov.get()); } |
PagePathAndMethodFilter { public boolean match(HttpRequest req) { String path = this.basePathFilter.apply(req.uri()); if (path == null) { return false; } path = trimLeadingAndTrailingSlashes(trimQuery(path)); Method method = Method.get(req); MethodPath mp = new MethodPath(method, path); if (nonMatchesCache.contains(mp)) { return false; } if (matchesCache.contains(mp)) { return true; } ByMethod bm = all.get(mp.method); if (bm == null) { nonMatchesCache.add(mp); return false; } if (bm.match(mp.path)) { matchesCache.add(mp); return true; } else { nonMatchesCache.add(mp); return false; } } PagePathAndMethodFilter(Function<String, String> basePathFilter); PagePathAndMethodFilter(); PagePathAndMethodFilter(String basePath); @Override String toString(); boolean match(HttpRequest req); List<Object> listFor(HttpRequest req); } | @Test @SuppressWarnings("unchecked") public void testTypeMatching() { for (Class<?> c : classes) { Class<? extends Page> pg = (Class<? extends Page>) c; ShouldMatch shoulds = pg.getAnnotation(ShouldMatch.class); if (shoulds != null) { Method mth = pg.getAnnotation(Methods.class).value()[0]; for (String uri : shoulds.value()) { HttpRequest req = req(mth, uri); assertTrue(mth + " " + uri + " should be matched but isn't", pgs.match(req)); } } ShouldNotMatch shouldntss = pg.getAnnotation(ShouldNotMatch.class); if (shouldntss != null) { Method mth = pg.getAnnotation(Methods.class).value()[0]; for (String uri : shouldntss.value()) { HttpRequest req = req(mth, uri); assertFalse(mth + " " + uri + " should be matched but isn't", pgs.match(req)); } } } } |
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); } | @Test public void testHighAsciiCharactersInPath() { PathElement el = new PathElement("foo"); assertTrue(el.isValid()); el = new PathElement(createHighAsciiString()); assertTrue(el.isValid()); }
@Test public void testHighAsciiCharactersInLabel() { Label lbl = new Label("foo"); assertTrue(lbl.isValid()); lbl = new Label(createHighAsciiString()); assertFalse(lbl.isValid()); } |
DefaultPathFactory implements PathFactory { @Override public URL constructURL(Path path) { return constructURL(path, secure); } @Inject DefaultPathFactory(Settings settings); @Override int portForProtocol(Protocol protocol); @Override Path toExternalPath(String path); @Override Path toExternalPath(Path path); @Override URL constructURL(Path path); @Override Path toPath(String uri); @Override URL constructURL(Protocol protocol, Path path); URL constructURL(Protocol protocol, Path path, boolean secure); URL constructURL(Protocol protocol, Path path, int port); @Override URL constructURL(Path path, boolean secure); @Override URL constructURL(String path, HttpEvent evt); } | @Test public void testNewerFeatures() throws Throwable { DefaultPathFactory f = new DefaultPathFactory(new SettingsBuilder() .add(ServerModule.SETTINGS_KEY_BASE_PATH, "/foo") .add(ServerModule.SETTINGS_KEY_GENERATE_SECURE_URLS, "true") .add(ServerModule.SETTINGS_KEY_URLS_HOST_NAME, "paths.example") .add(ServerModule.SETTINGS_KEY_URLS_EXTERNAL_PORT, 5720) .add(ServerModule.SETTINGS_KEY_URLS_EXTERNAL_SECURE_PORT, 5721) .build()); URL url = f.constructURL("/hey/you"); assertTrue(url.isValid()); String test1 = "https: String test2 = "https: assertEquals(test1 + "\tversus\n" + url, test1, url.toString()); assertEquals(url.toString(), f.constructURI("/hey/you").toString()); EventImpl fakeEvent = new EventImpl(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/up/down", new DefaultHttpHeaders().add(HttpHeaderNames.HOST, "timboudreau.org:5223")), f); url = f.constructURL("/whee?this=that&you=me", fakeEvent); assertTrue(url.isValid()); assertEquals("timboudreau.org", url.getHost().toString()); assertEquals(5223, url.getPort().intValue()); assertEquals(test2 + "\tversus\n" + url, test2, url.toString()); url = f.constructURL("/whee?this=that&you=me#woohoo", fakeEvent); assertTrue(url.isValid()); assertEquals("woohoo", url.getAnchor().toString()); assertNotNull(url + " has no parameters", url.getParameters()); assertTrue(url.getParameters().isValid()); fakeEvent = new EventImpl(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/up/down", new DefaultHttpHeaders() .add(Headers.X_FORWARDED_PROTO.name(), "http")), f); url = f.constructURL("/should/be/insecure", fakeEvent); assertEquals("/foo/should/be/insecure", url.getPath().toStringWithLeadingSlash()); assertEquals(HTTP, url.getProtocol()); assertEquals("paths.example", url.getHost().toString()); assertEquals(5720, url.getPort().intValue()); } |
ByteBufCodec implements Codec<ByteBuf> { @Override public ByteBuf decode(BsonReader reader, DecoderContext dc) { ByteBuf buf = alloc.buffer(); JsonWriterSettings settings = JsonWriterSettings.builder() .indent(false).build(); PlainJsonWriter json = new PlainJsonWriter(buf, settings); json.pipe(reader); return buf; } @Inject ByteBufCodec(ByteBufAllocator alloc); void writeDateTime(BsonWriter writer, ZonedDateTime t, EncoderContext ec); @Override void encode(BsonWriter writer, ByteBuf t, EncoderContext ec); @Override Class<ByteBuf> getEncoderClass(); @Override ByteBuf decode(BsonReader reader, DecoderContext dc); } | @Test public void test(@Named("stuff") MongoCollection<Document> stuff) throws InterruptedException, IOException { byte[] bytes = new byte[120]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) (120 - i); } List<Object> list = new LinkedList<>(); list.add(1); list.add(2); list.add(2); list.add("hello"); list.add(new Document("in", "list")); Document document = new Document("hello", "world") .append("boolValue", true) .append("list", list) .append("intValue", 32) .append("dbl", 32.000235D) .append("subdoc", new Document("other", "stuff")) .append("longValue", Long.valueOf(Integer.MAX_VALUE + 1L)) .append("_id", new ObjectId()) .append("bytes", bytes); CB<Void> cb = new CB<Void>(); stuff.insertOne(document, cb); cb.get(); Thread.sleep(200); MongoCollection<ByteBuf> bbc = stuff.withDocumentClass(ByteBuf.class); CB<ByteBuf> bb = new CB<ByteBuf>(); bbc.find(new Document("_id", document.get("_id"))) .batchSize(1) .projection(new Document("hello", 1) .append("boolValue", 1) .append("intValue", 1) .append("longValue", 1) .append("dbl", 1) .append("list", 1) .append("subdoc", 1) .append("bytes", 1) .append("_id", 1)) .first(bb); ByteBuf buf = bb.get(); assertNotNull(buf); String content = Streams.readString(new ByteBufInputStream(buf)); buf.resetReaderIndex(); Map m = new ObjectMapper().readValue(content, Map.class); for (Map.Entry<String, Object> e : document.entrySet()) { Object other = m.get(e.getKey()); assertNotNull(e.getKey() + " is null", other); Object value = e.getValue(); assertNotNull(value); switch (e.getKey()) { case "_id": assertTrue(value instanceof ObjectId); assertTrue(other instanceof String); value = value.toString(); break; case "bytes": assertTrue(other.getClass().getName(), other instanceof String); other = Base64.getDecoder().decode((String)other); continue; } if (value instanceof byte[]) { assertTrue(other instanceof byte[]); assertTrue(value instanceof byte[]); assertArrayEquals((byte[]) value, (byte[]) other); } else { assertEquals(other, value); } } } |
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); } | @Test public void testUnescape2() { StringBuilder sb = new StringBuilder(); for (char c = 1; c < 6; c++) { sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(unescaped, re_unescaped); }
@Test public void testUnescape3() { StringBuilder sb = new StringBuilder(); for (char c = 5; c < 25; c++) { sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(unescaped, re_unescaped); }
@Test public void testUnescape() { assertEquals("hello world", URLBuilder.unescape("hello%20world")); assertEquals(" ", URLBuilder.unescape("%20")); StringBuilder sb = new StringBuilder(); for (char c = 1; c < 255; c++) { if (c == 25) { continue; } sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(examine(unescaped, re_unescaped), unescaped, re_unescaped); } |
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } } | @Test public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() { PersonModel person = new PersonModel( "Kim", "Kardashian", new GregorianCalendar(1980, Calendar.OCTOBER, 21)); ValidationByResponseHandler validator = new ValidationByResponseHandler(); Response response = validator.validate(person); assertThat(response.getStatus()).isEqualTo(200); }
@Test public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() { PersonModel person = new PersonModel( null, "", null); ValidationByResponseHandler validator = new ValidationByResponseHandler(); Response response = validator.validate(person); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getEntity().toString()) .contains("Invalid Bean, constraint error(s) : ") .contains("birthDate may not be null.") .contains("firstName may not be null.") .contains("lastName size must be between 1 and 16."); } |
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } } | @Test public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() { PersonModel person = new PersonModel( "Kim", "Kardashian", new GregorianCalendar(1980, Calendar.OCTOBER, 21)); ValidationByExceptionHandler validator = new ValidationByExceptionHandler(); validator.validate(person); }
@Test public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() { PersonModel person = new PersonModel( null, "", null); ValidationByExceptionHandler validator = new ValidationByExceptionHandler(); try { validator.validate(person); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()) .contains("Invalid Bean, constraint error(s) : ") .contains("birthDate may not be null.") .contains("firstName may not be null.") .contains("lastName size must be between 1 and 16."); } } |
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); } | @Test public void test_batch_execution() { String[] args = { "10" }; HelloWorldBatch.main(args); }
@Test public void test_args_validation() { try { HelloWorldBatch.main(null); fail("error expected"); } catch (IllegalArgumentException e) { } try { HelloWorldBatch.main(new String[] {}); fail("error expected"); } catch (IllegalArgumentException e) { } try { HelloWorldBatch.main(new String[] { null }); fail("error expected"); } catch (IllegalArgumentException e) { } }
@Test(expected = RuntimeException.class) public void test_batch_execution_error() { HelloWorldBatch.main(new String[] { "ERROR" }); } |
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); } | @Test public void invalidProgressValue() { try { button.setProgress(101); fail("Setting progress > max should throw"); } catch (IllegalArgumentException e) { } }
@Test public void anotherInvalidProgressValue() { try { button.setProgress(-1); fail("Setting progress < 0 should throw"); } catch (IllegalArgumentException e) { } } |
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); } | @Test public void setMaxToUnderZero() { try { button.setMax(-1); fail("Setting max <= 0 should throw"); } catch (IllegalArgumentException e) { } }
@Test public void setMaxToZero() { try { button.setMax(0); fail("Setting max <= 0 should throw"); } catch (IllegalArgumentException e) { } } |
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); } | @Test public void onCheckedChangeListenerIsNotified() { CompoundButton.OnCheckedChangeListener publisher = mock(CompoundButton.OnCheckedChangeListener.class); button.setOnCheckedChangeListener(publisher); button.setPinned(true); verify(publisher).onCheckedChanged(button, true); button.setPinned(false); verify(publisher).onCheckedChanged(button, false); }
@Test public void onCheckedChangeListenerIsNotifiedOnToggle() { button.setPinned(true); CompoundButton.OnCheckedChangeListener publisher = mock(CompoundButton.OnCheckedChangeListener.class); button.setOnCheckedChangeListener(publisher); button.toggle(); verify(publisher).onCheckedChanged(button, false); } |
ProgressButton extends CompoundButton { @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); if (isSaveEnabled()) { SavedState ss = new SavedState(superState); ss.mMax = mMax; ss.mProgress = mProgress; return ss; } return superState; } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); } | @Test public void onSaveInstanceState() { button.setProgress(72); button.setMax(842); final Parcelable parcelable = button.onSaveInstanceState(); button.setProgress(2); button.setMax(50); assertThat(button.getProgress()).isEqualTo(2); assertThat(button.getMax()).isEqualTo(50); button.onRestoreInstanceState(parcelable); assertThat(button.getProgress()).isEqualTo(72); assertThat(button.getMax()).isEqualTo(842); } |
ProgressButton extends CompoundButton { public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); } | @Test public void settingInvalidProgressAndMax() { try { button.setProgressAndMax(10, 5); fail("Setting progress > max should throw"); } catch (IllegalArgumentException e) { } try { button.setProgressAndMax(0, 0); fail("Setting max = 0 should throw"); } catch (IllegalArgumentException e) { } try { button.setProgressAndMax(-1, 10); fail("Setting progress < 0 should throw"); } catch (IllegalArgumentException e) { } } |
WriteController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void delete(@PathVariable(value = "id") String id, HttpServletResponse response) throws IOException { service.delete(id); } @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) @ResponseBody String create(@RequestParam("comment") final String comment,
@RequestParam("pageId") final String pageId,
@RequestParam("emailAddress") final String emailAddress,
@RequestParam("username") final String username); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) void delete(@PathVariable(value = "id") String id,
HttpServletResponse response); @ExceptionHandler(EmptyResultDataAccessException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); } | @Test public void testDelete() throws Exception { CommentModel model = new CommentModel(); model.setUsername("testuser"); model.setId("dqe345e456rf34rw"); model.setPageId("product0815"); model.setEmailAddress("[email protected]"); model.setComment("I am the comment"); String id = service.put(model); this.mvc.perform(delete("/" + id)).andExpect(status().isOk()); assertNull(service.get(model.getId())); } |
ReadController { @RequestMapping(value = "/list/{id}") public List<CommentDTO> getComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get comments for pageId {}", pageId); counterService.increment("commentstore.list_comments"); List<CommentModel> r = service.list(pageId); if (r.isEmpty()) { LOGGER.info("get comments for pageId {} - not found", pageId); throw new FileNotFoundException("/list/" + pageId); } LOGGER.info("get comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn,
@RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); } | @Test public void testGetComments() throws Exception { CommentModel model = setupDummyModel(); List<CommentModel> mockReturn = new ArrayList<CommentModel>(); mockReturn.add(model); when(this.commentService.list( anyString())).thenReturn(mockReturn); this.mvc.perform(get("/list/" + model.getPageId())) .andExpect(status().is(200)) .andExpect(jsonPath("$[0].id", is(model.getId()))) .andExpect( jsonPath("$[0].created", is(SDF.format(model .getCreationDate().getTime())))) .andExpect(jsonPath("$[0].username", is(model.getUsername()))) .andExpect(jsonPath("$[0].comment", is(model.getComment()))) .andExpect( jsonPath("$[0].email_address", is(model.getEmailAddress()))); verify(this.commentService, times(1)).list( anyString()); } |
ReadController { @RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId); LOGGER.info("get spam comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn,
@RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); } | @Test public void testGetSpamComments() throws Exception { CommentModel model = setupDummyModel(); List<CommentModel> mockReturn = new ArrayList<CommentModel>(); mockReturn.add(model); when(this.commentService.list( anyString())).thenReturn(mockReturn); this.mvc.perform(get("/listspam/" + model.getPageId())) .andExpect(status().is(200)) .andExpect(jsonPath("$", hasSize(0))); ; } |
Logger { public static void addLogPrinter(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.add(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); } | @Test(expected = NullPointerException.class) public void nullAddLogPrinter() { Logger.addLogPrinter(null); } |
Logger { public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); } | @Test(expected = NullPointerException.class) public void nullRemoveLogPrinter() { Logger.removeLogPrint(null); } |
Logger { public static void d(String msg, Object...args) { logAdapter.d(msg, args); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); } | @Test public void dontAddLogPrinter() { String message = "Hello, world!"; Logger.d(message); assertLog() .hasNoMoreMessages(); } |
Decorator implements Component { @Override public double calc(String user ,int seniority) { return this.component.calc(user ,seniority); } Decorator(Component component); @Override double calc(String user ,int seniority); } | @Test public void test() { String user = "zlikun" ; int seniority = 7 ; Component component = new ComponetImpl() ; Assert.assertEquals(0 ,component.calc(user ,seniority) ,0); Decorator d1 = new MonthDecorator(component) ; Assert.assertEquals(1000 ,d1.calc(user ,seniority) ,0); Decorator d2 = new YearDecorator(d1) ; Assert.assertEquals(3000 ,d2.calc(user ,seniority) ,0); } |
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); static final Singleton2 getInstance(); } | @Test public void test_multi() { final ConcurrentMap<Singleton2 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(200) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton2.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertTrue(map.size() > 1); }
@Test public void test_single() { Assert.assertTrue(Singleton2.getInstance() == Singleton2.getInstance()); Assert.assertTrue(new Singleton2() != new Singleton2()); } |
TrainFactory { public String process() { StringBuilder sb = new StringBuilder() ; sb.append(builder.buildHeader()).append("-") ; sb.append(builder.buildBody()).append("-") ; sb.append(builder.buildFooter()) ; return sb.toString() ; } TrainFactory(TrainBuilder builder); String process(); } | @Test public void test() { TrainFactory factory = new TrainFactory(new TrainBuilder()) ; String train = factory.process() ; Assert.assertEquals("火车头-火车身-火车尾" ,train); } |
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); static final Singleton0 getInstance(); } | @Test public void test_single() { Assert.assertTrue(Singleton0.getInstance() == Singleton0.getInstance()); }
@Test public void test_multi() { final Set<Singleton0> set = new HashSet<>() ; ExecutorService exec = Executors.newFixedThreadPool(50) ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { set.add(Singleton0.getInstance()) ; } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,set.size()); } |
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); static final Singleton5 getInstance(); } | @Test public void test_single() { Assert.assertTrue(Singleton5.getInstance() == Singleton5.getInstance()); }
@Test public void test_multi() { final ConcurrentMap<Singleton5 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton5.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); } |
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); static final Singleton3 getInstance(); } | @Test public void test_single() { Assert.assertTrue(Singleton3.getInstance() == Singleton3.getInstance()); }
@Test public void test_multi() { final ConcurrentMap<Singleton3 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton3.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); } |
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); static final Singleton4 getInstance(); } | @Test public void test_single() { Assert.assertTrue(Singleton4.getInstance() == Singleton4.getInstance()); }
@Test public void test_multi() { final ConcurrentMap<Singleton4 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton4.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); } |
BasicRule_5_Builder extends BasicRuleBuilder { public BasicRule create_BR_5(Rule rule) throws Exception { try { String finalEml; String title = rule.getTitle(); String incomingObservationsCountPatternId = title + "_incoming_observations_count_stream"; String incomingObservationsEventName = title + "_incoming_observations_count"; String noObservationsReceivedStreamPatternId = title + "_no_observation_received_stream"; String observationsReceivedStreamPatternId = title + "_observation_received_stream"; String noObservationsNotificationPatternId = title + "_no_observation_notification"; String observationsNotificationPatternId = title + "_observation_notification"; String noObservationsReceivedEventName = title + "_no_observation_received"; String observationsReceivedEventName = title + "_observation_received"; String noObservationsOutputName = title + "_no_observation_output"; String observationsOutputName = title + "_observation_output"; EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); SimplePatternType incomingObservationCount = simplePatterns.getSimplePatternArray(0); processSimplePattern(incomingObservationCount, incomingObservationsCountPatternId, incomingObservationsEventName); processPropertyRestrictions(incomingObservationCount, rule.getTimeseriesMetadata()); processDurationValue(incomingObservationCount, rule); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); ComplexPattern noObservationsReceived = complexPatterns.getComplexPatternArray(0); processComplexPattern(noObservationsReceived, noObservationsReceivedStreamPatternId, noObservationsReceivedEventName); setSelectEventName(noObservationsReceived, incomingObservationsEventName); noObservationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); noObservationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processEqualToFilterGuard(noObservationsReceived, incomingObservationsEventName); ComplexPattern observationsReceived = complexPatterns.getComplexPatternArray(1); processComplexPattern(observationsReceived, observationsReceivedStreamPatternId, observationsReceivedEventName); setSelectEventName(observationsReceived, incomingObservationsEventName); observationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); observationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processNotEqualToFilterGuard(observationsReceived, incomingObservationsEventName); ComplexPattern noObservationsReceivedNotification = complexPatterns.getComplexPatternArray(2); processComplexPattern(noObservationsReceivedNotification, noObservationsNotificationPatternId, noObservationsReceivedEventName); setOutputName(noObservationsReceivedNotification, noObservationsOutputName); noObservationsReceivedNotification.getFirstPattern().setPatternReference(observationsReceivedStreamPatternId); noObservationsReceivedNotification.getSecondPattern().setPatternReference(noObservationsReceivedStreamPatternId); ComplexPattern observationsReceivedNotification = complexPatterns.getComplexPatternArray(3); processComplexPattern(observationsReceivedNotification, observationsNotificationPatternId, observationsReceivedEventName); setOutputName(observationsReceivedNotification, observationsOutputName); observationsReceivedNotification.getFirstPattern().setPatternReference(noObservationsReceivedStreamPatternId); observationsReceivedNotification.getSecondPattern().setPatternReference(observationsReceivedStreamPatternId); finalEml = emlTemplateDoc.xmlText(); User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR5", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } } BasicRule_5_Builder(); BasicRule create_BR_5(Rule rule); Rule getRuleByEML(BasicRule basicRule); } | @Test public void havingRule_parseEmlFromBasicRule_noXmlErrors() throws Exception { String eml = builder.create_BR_5(rule).getEml(); assertThat(XMLBeansParser.validate(XmlObject.Factory.parse(eml)), is(empty())); } |
QueryParser { public Collection<String> parseFeatures() { String featureValues = kvps.get(FEATURES.name()); return parseCommaSeparatedValues(featureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParseStationKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("features=").append("Heldra_41700105"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedStations = parser.parseFeatures(); assertTrue("Invalid size: " + parsedStations.size(), parsedStations.size() == 1); assertTrue("Stations could not be parsed.", parsedStations.contains("Heldra_41700105")); } |
QueryParser { public Collection<String> parsePhenomenons() { String phenomenonValues = kvps.get(PHENOMENONS.name()); return parseCommaSeparatedValues(phenomenonValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParsePhenomenonsKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("phenomenons=").append("Wasserstand"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedPhenomenons = parser.parsePhenomenons(); assertTrue("Invalid size: " + parsedPhenomenons.size(), parsedPhenomenons.size() == 1); assertTrue("Stations could not be parsed.", parsedPhenomenons.contains("Wasserstand")); } |
QueryParser { public Collection<String> parseProcedures() { String procedureValues = kvps.get(PROCEDURES.name()); return parseCommaSeparatedValues(procedureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParseProceduresKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("procedures=").append("Wasserstand-Heldra_41700105"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedProcedures = parser.parseProcedures(); assertTrue("Invalid size: " + parsedProcedures.size(), parsedProcedures.size() == 1); assertTrue("Stations could not be parsed.", parsedProcedures.contains("Wasserstand-Heldra_41700105")); } |
QueryParser { public TimeRange parseTimeRange() { String begin = kvps.get(BEGIN.name()); String end = kvps.get(END.name()); return TimeRange.createTimeRange(begin, end); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParsingBeginAndEndKvps() { StringBuilder validQuery = new StringBuilder(); validQuery.append("begin"); validQuery.append("="); validQuery.append("2012-10-01T12:01:00"); validQuery.append("&"); validQuery.append("end"); validQuery.append("="); validQuery.append("2014-10-01T12:01:00"); QueryParser parser = new QueryParser(validQuery.toString(), false); TimeRange parsedTimeRange = parser.parseTimeRange(); assertEquals("2012-10-01T12:01:00", parsedTimeRange.getStart()); assertEquals("2014-10-01T12:01:00", parsedTimeRange.getEnd()); } |
XmlHelper { public <T> T parseFirst(XmlObject from, String xPath, Class<T> ofType) { T[] results = parseAll(from, xPath, ofType); return results.length > 0 ? results[0] : null; } XmlHelper(Map<String, String> namespaceDecarations); String getShortName(IdentifierList identifiers); String getUniqueId(IdentifierList identifiers); String[] getRelatedFeatures(Capabilities identifiers); PointDocument getPoint(FeaturePropertyType member, CRSUtils referenceHelper); String[] getRelatedPhenomena(Outputs outputs); T parseFirst(XmlObject from, String xPath, Class<T> ofType); @SuppressWarnings("unchecked") T[] parseAll(XmlObject from, String xPath, Class<T> ofType); } | @Test public void shouldParseSystemViaXPath() { SystemType systemType = xmlHelper.parseFirst(smlDoc, "$this assertNotNull(systemType); } |
TimeseriesFactory { public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[0]); ObservedValueTuple observation = nextObservation; int counter = 0; Double sum = 0.0; LOGGER.debug("Compressionlevel none"); for (int i = 0; i < timeArray.length; i++) { prevObservation = observation; observation = nextObservation; if (i + 1 < timeArray.length) { nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[i + 1]); } counter++; Double resultVal = getValidData(observation.getValue(0).toString()); if (seriesType.equals("1")) { } else if (seriesType.equals("2")) { if (resultVal != null) { resultVal += sum; } else { resultVal = sum; } } else { } sum = resultVal; ITimePosition timePos = (ITimePosition) observation.getTime(); DateTime time = DateTime.parse(timePos.toISO8601Format()); timeSeries.add(new FixedMillisecond(time.getMillis()), resultVal); } LOGGER.debug("Compressed observations from " + timeArray.length + " to " + counter); return timeSeries; } TimeseriesFactory(ObservationSeriesCollection collection); TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType); TimeSeries compressToTimeSeries(SosTimeseries timeseries, boolean force, String seriesType); HashMap<Long, Double> compressToHashMap(String foiID,
String phenID, String procID); } | @Test public void shouldNotAddValuesTwiceWhenCreatingTimeseriesDuringDaylightSavingSwitch() throws Exception { SosTimeseries timeseries = createSosTimeseries(); GetObservationResponseToOxfFeatureCollectionReader reader = createReader(); String[] foiIds = new String[]{timeseries.getFeatureId()}; String[] procedureIds = new String[]{timeseries.getProcedureId()}; String[] observedPropertyIds = new String[]{timeseries.getPhenomenonId()}; OXFFeatureCollection obsColl = reader.getFeatureCollection(); ObservationSeriesCollection seriesCollection = new ObservationSeriesCollection(obsColl, foiIds, observedPropertyIds, procedureIds, true); assertThat(seriesCollection.getAllTuples().size(), is(277)); TimeseriesFactory factory = new TimeseriesFactory(seriesCollection); TimeSeries chartTimeseries = factory.createTimeSeries(timeseries, "1"); assertThat(chartTimeseries.getItemCount(), is(277)); } |
TimeseriesDataGenerator extends Generator { @Override public RepresentationResponse producePresentation(DesignOptions options) throws GeneratorException { LOGGER.debug("Starting producing representation with " + options); Map<String, OXFFeatureCollection> entireCollMap = new HashMap<String, OXFFeatureCollection>(); try { entireCollMap = getFeatureCollectionFor(options, false); } catch (AccessException e) { throw new GeneratorException("Error creating TimeSeriesDataResponse.", e); } Collection<OXFFeatureCollection> observationCollList = entireCollMap.values(); HashMap<String, HashMap<Long, Double>> allTimeSeries = new HashMap<String, HashMap<Long, Double>>(); for (OXFFeatureCollection coll : observationCollList) { List<String> foiList = new ArrayList<String>(); List<OXFPhenomenonPropertyType> phenomenonList = new ArrayList<OXFPhenomenonPropertyType>(); HashMap<String, List<String>> procMap = new HashMap<String, List<String>>(); for (OXFFeature observation : coll) { String foi = ((OXFFeature) observation.getAttribute(FEATURE_OF_INTEREST)).toString(); if (!foiList.contains(foi)) { foiList.add(foi); } String proc = (String) observation.getAttribute(PROCEDURE); if (procMap.containsKey(foi) == false) { procMap.put(foi, new ArrayList<String>()); } if (!procMap.get(foi).contains(proc)) { procMap.get(foi).add(proc); } OXFPhenomenonPropertyType obsProp = (OXFPhenomenonPropertyType) observation.getAttribute(OBSERVED_PROPERTY); if (!phenomenonList.contains(obsProp)) { phenomenonList.add(obsProp); } } for (String foi : foiList) { for (String procedure : procMap.get(foi)) { for (OXFPhenomenonPropertyType obsProp : phenomenonList) { ObservationSeriesCollection txCollection = new ObservationSeriesCollection(coll, new String[] { foi }, new String[] { obsProp.getURN() }, false); TimeseriesProperties selectedProperties = null; for (TimeseriesProperties property : options.getProperties()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(property.getOffFoiProcPhenCombination()); } if (property.getFeature().equals(foi) && property.getPhenomenon().equals(obsProp.getURN()) && property.getProcedure().equals(procedure)) { selectedProperties = property; String phenomenonId = selectedProperties.getPhenomenon(); try { TimeseriesFactory factory = new TimeseriesFactory(txCollection); HashMap<Long, Double> data = factory.compressToHashMap(foi, phenomenonId, procedure); allTimeSeries.put(selectedProperties.getTimeseriesId(), data); } catch (ParseException e) { throw new GeneratorException("Could not parse data.", e); } break; } else { if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Ignore unknown property constellation: ["); sb.append("foiId: ").append(foi); sb.append(", phenId: ").append(obsProp.getURN()); sb.append(", procId: ").append(procedure); sb.append(" ]. Expected timeseries properties: ["); sb.append("foiId: ").append(property.getFeature()); sb.append(", phenId: ").append(property.getPhenomenon()); sb.append(", procId: ").append(property.getProcedure()); sb.append(" ]"); LOGGER.debug(sb.toString()); } } } } } } } for (TimeseriesProperties prop : options.getProperties()) { if (!allTimeSeries.containsKey(prop.getTimeseriesId())) { allTimeSeries.put(prop.getTimeseriesId(), new HashMap<Long, Double>()); } } return new TimeSeriesDataResponse(allTimeSeries); } @Override RepresentationResponse producePresentation(DesignOptions options); } | @Test public void shouldCreateTimeseries() throws Exception { long begin = DateTime.parse("2007-10-27T10:00:00.000+02:00").getMillis(); long end = DateTime.parse("2007-10-28T09:00:00.000+01:00").getMillis(); TimeseriesDataGenerator generator = new TimeseriesDataGeneratorSeam(); SosTimeseries timeseries = createSosTimeseries(); DesignOptions options = new DesignOptions(createTimeseriesProperties(timeseries), begin, end, true); TimeSeriesDataResponse response = (TimeSeriesDataResponse) generator.producePresentation(options); HashMap<String, HashMap<Long, Double>> data = response.getPayloadData(); HashMap<Long, Double> timeseriesData = data.get(timeseries.getTimeseriesId()); assertThat(timeseriesData.size(), is(277)); } |
SosMetadataUpdate { protected static String createPostfix(String url) { if (url.startsWith("http: url = url.substring("http: } return url.replaceAll("/", "_").replaceAll("\\?", "_").replaceAll(":", "_").replaceAll("@", "_"); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); } | @Test public void testCreatePostfix() { String postfix = SosMetadataUpdate.createPostfix(validServiceUrl); assertEquals("my.server.net_52n-SOS-Vx.x_sos", postfix); } |
SosMetadataUpdate { protected static File getCacheTarget(String serviceUrl) { String postfix = createPostfix(serviceUrl); return new File(generateCacheFilePath(postfix)); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); } | @Test public void testGetCacheTarget() { File expected = new File(cacheTargetFile); File cacheTarget = SosMetadataUpdate.getCacheTarget(validServiceUrl); assertEquals(expected.getAbsoluteFile(), cacheTarget.getAbsoluteFile()); } |
SosMetadataUpdate { protected static void prepareCacheTargetDirectory() throws IOException { File cacheDirectory = getCacheDir(); if (!cacheDirectory.exists() && !cacheDirectory.mkdirs()) { throw new IOException("Unable to create cache directory."); } } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); } | @Test public void testPrepareCacheTarget() throws IOException { SosMetadataUpdate.prepareCacheTargetDirectory(); assertTrue(temporalCacheDirectory.exists()); } |
BasicRule_4_Builder extends BasicRuleBuilder { public BasicRule create(Rule rule) { String title = rule.getTitle(); this.overshootPatternId = title + this.overshootStream; this.undershootPatternId = title + this.undershootStream; this.entryNotificationPatternId = title + this.overshootNotificationStream; this.exitNotificationPatternId = title + this.undershootNotificationStream; this.overshootEventName = title + this.overshoot; this.undershootEventName = title + this.undershoot; this.entryEventName = title + this.overshootNotification; this.exitEventName = title + this.undershootNotification; this.output_enter = title + this.enter; this.output_exit = title + this.exit; try { EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); SimplePatternType staticInitPattern = simplePatterns.getSimplePatternArray(INDEX_SIMPLE_PATTERN_INTIAL_COUNT); processPropertyRestrictions(staticInitPattern, rule.getTimeseriesMetadata()); RuleFilter entryFilter = createEntryFilter(rule); SimplePatternType ruleUndershoot = simplePatterns.getSimplePatternArray(INDEX_ENTRY_CONDITION_PATTERN); processSimplePattern(ruleUndershoot, overshootPatternId, overshootEventName); processPropertyRestrictions(ruleUndershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleUndershoot.getGuard(), entryFilter, INPUT_STREAM_NAME); RuleFilter exitFilter = createExitFilter(rule); SimplePatternType ruleOvershoot = simplePatterns.getSimplePatternArray(INDEX_EXIT_CONDITION_PATTERN); processSimplePattern(ruleOvershoot, undershootPatternId, undershootEventName); processPropertyRestrictions(ruleOvershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleOvershoot.getGuard(), exitFilter, INPUT_STREAM_NAME); ComplexPattern entryClause = complexPatterns.getComplexPatternArray(INDEX_ENTRY_NOTIFICATION_PATTERN); processComplexPattern(entryClause, entryNotificationPatternId, entryEventName, output_enter); entryClause.getFirstPattern().setPatternReference(undershootPatternId); entryClause.getSecondPattern().setPatternReference(overshootPatternId); ComplexPattern exitClause = complexPatterns.getComplexPatternArray(INDEX_EXIT_NOTIFICATION_PATTERN); processComplexPattern(exitClause, exitNotificationPatternId, exitEventName, output_exit); exitClause.getFirstPattern().setPatternReference(overshootPatternId); exitClause.getSecondPattern().setPatternReference(undershootPatternId); ComplexPattern initialEntryClause = complexPatterns.getComplexPatternArray(INDEX_COMPLEX_PATTERN_INTIAL_ENTRY); processFilterGuard(initialEntryClause.getGuard(), entryFilter, INITIAL_STREAM_NAME); eml = emlTemplateDoc.xmlText(); finalEml = eml; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR4", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } BasicRule_4_Builder(); BasicRule create(Rule rule); Rule getRuleByEML(BasicRule basicRule); } | @Test public void havingRule_parseEmlFromBasicRule_noXmlErrors() throws Exception { String eml = builder.create(rule).getEml(); assertThat(XMLBeansParser.validate(XmlObject.Factory.parse(eml)), is(empty())); } |
DescribeSensorParser { public HashMap<String, ReferenceValue> parseReferenceValues() { final Capabilities[] capabilities = getSensorMLCapabilities(smlDoc.getSensorML()); final HashMap<String, ReferenceValue> map = new HashMap<String, ReferenceValue>(); if (capabilities == null || capabilities.length == 0) { return map; } for (final Capabilities capability : capabilities) { final AbstractDataRecordType abstractDataRecord = capability.getAbstractDataRecord(); if (abstractDataRecord instanceof SimpleDataRecordType) { final SimpleDataRecordType simpleDataRecord = (SimpleDataRecordType) abstractDataRecord; for (final AnyScalarPropertyType field : simpleDataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } else if (abstractDataRecord instanceof DataRecordType) { final DataRecordType dataRecord = (DataRecordType) abstractDataRecord; for (final DataComponentPropertyType field : dataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } } return map; } DescribeSensorParser(final InputStream inputStream, final SOSMetadata metadata); String buildUpSensorMetadataStationName(); String buildUpSensorMetadataUom(final String phenomenonID); String buildUpSensorMetadataHtmlUrl(final SosTimeseries timeseries); String createSensorDescriptionFileName(final SosTimeseries timeseries); Point buildUpSensorMetadataPosition(); HashMap<String, ReferenceValue> parseReferenceValues(); List<String> parseFOIReferences(); List<String> getPhenomenons(); static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject); void setReferencingHelper(final CRSUtils refHelper); } | @Test public void shouldParseReferenceValuesFromCapabilitiesSection() { assertThat(parser.parseReferenceValues().size(), is(5)); } |
DescribeSensorParser { public static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject) throws XmlException, XMLHandlingException, IOException { if (SoapUtil.isSoapEnvelope(xmlObject)) { xmlObject = SoapUtil.stripSoapEnvelope(xmlObject); } if (xmlObject instanceof SensorMLDocument) { return (SensorMLDocument) xmlObject; } if (xmlObject instanceof DescribeSensorResponseDocument) { DescribeSensorResponseDocument responseDoc = (DescribeSensorResponseDocument) xmlObject; DescribeSensorResponseType response = responseDoc.getDescribeSensorResponse(); DescribeSensorResponseType.Description[] descriptionArray = response.getDescriptionArray(); if (descriptionArray.length == 0) { LOGGER.warn("No SensorDescription available in response!"); } else { for (DescribeSensorResponseType.Description description : descriptionArray) { SensorDescriptionType.Data dataDescription = description.getSensorDescription().getData(); String namespace = "declare namespace gml='http: for (XmlObject xml : dataDescription.selectPath(namespace + "$this XmlCursor cursor = xml.newCursor(); String gmlId = cursor.getTextValue(); if ( !NcNameResolver.isNCName(gmlId)) { cursor.setTextValue(NcNameResolver.fixNcName(gmlId)); } } XmlObject object = XmlObject.Factory.parse(dataDescription.xmlText()); if (object instanceof SystemDocumentImpl) { SensorMLDocument smlDoc = SensorMLDocument.Factory.newInstance(); SensorMLDocument.SensorML.Member member = smlDoc.addNewSensorML().addNewMember(); member.set(XMLBeansParser.parse(object.newInputStream())); return smlDoc; } return SensorMLDocument.Factory.parse(dataDescription.newInputStream()); } } } LOGGER.warn("Failed to unwrap SensorML from '{}'. Return an empty description.", xmlObject.xmlText()); return SensorMLDocument.Factory.newInstance(); } DescribeSensorParser(final InputStream inputStream, final SOSMetadata metadata); String buildUpSensorMetadataStationName(); String buildUpSensorMetadataUom(final String phenomenonID); String buildUpSensorMetadataHtmlUrl(final SosTimeseries timeseries); String createSensorDescriptionFileName(final SosTimeseries timeseries); Point buildUpSensorMetadataPosition(); HashMap<String, ReferenceValue> parseReferenceValues(); List<String> parseFOIReferences(); List<String> getPhenomenons(); static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject); void setReferencingHelper(final CRSUtils refHelper); } | @Test public void shouldUnwrapSensorMLFromDescribeSensorResponseAndSoapEnvelope() throws XmlException, IOException, XMLHandlingException { XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(soapResponse, getClass()); response = DescribeSensorParser.unwrapSensorMLFrom(response); SensorMLDocument.class.cast(response); }
@Test public void shouldUnwrapSensorMLFromDescribeSensorResponse() throws XmlException, IOException, XMLHandlingException { XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(poxResponse, getClass()); response = DescribeSensorParser.unwrapSensorMLFrom(response); SensorMLDocument.class.cast(response); }
@Test public void shouldUnwrapSensorMLFromPlainSensorMLResponse() throws XmlException, IOException, XMLHandlingException { XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(smlResponse, getClass()); response = DescribeSensorParser.unwrapSensorMLFrom(response); SensorMLDocument.class.cast(response); } |
SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String encodePlusInParameter(String parameter) { return parameter.replace("+", "%2B"); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); } | @Test public void testEncodePlusInParameter() { String encoded = builder.encodePlusInParameter("a string with a \"+\""); assertEquals("a string with a \"%2B\"", encoded); } |
SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String fixTimeZone(String timeString) { StringBuilder sb = new StringBuilder(timeString); int insertionIndex = timeString.length() - 2; if (sb.charAt(insertionIndex - 1) != ':') { sb.insert(insertionIndex, ":"); } return sb.toString(); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); } | @Test public void testFixTimeZone() { String incorrectTime = "2012-08-06T13:49:30.0+0200"; String correctTime = builder.fixTimeZone(incorrectTime); assertEquals("2012-08-06T13:49:30.0+02:00", correctTime); } |
SOSRequestBuilderGET_200 implements ISOSRequestBuilder { public String encode(String parameter) { try { return encodePlusInParameter(URLEncoder.encode(parameter, "utf-8")); } catch (UnsupportedEncodingException e) { LOGGER.warn("Could not encode parameter {}!", parameter); return parameter; } } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); } | @Test public void testEncodeParameter() { String encoded = builder.encode("2012-08-06T13:49:30.0+02:00"); assertEquals("2012-08-06T13%3A49%3A30.0%2B02%3A00", encoded); String encodedCharacters = builder.encode("#$&'()+,/:;=?@[]"); assertEquals("%23%24%26%27%28%29%2B%2C%2F%3A%3B%3D%3F%40%5B%5D", encodedCharacters); } |
SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String createIso8601Duration(String start, String end) { StringBuilder sb = new StringBuilder(); sb.append(fixTimeZone(start)).append("/"); return sb.append(fixTimeZone(end)).toString(); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); String encode(String parameter); @Override String buildGetObservationByIDRequest(ParameterContainer parameters); @Override String buildInsertObservation(ParameterContainer parameters); @Override String buildRegisterSensor(ParameterContainer parameters); } | @Test public void testCreateIso8601Duration() { String start = "2012-08-06T13:49:30.0+02:00"; String end = "2012-08-01T13:49:30.0+02:00"; String duration = builder.createIso8601Duration(start, end); assertEquals("2012-08-06T13:49:30.0+02:00/2012-08-01T13:49:30.0+02:00", duration); } |
ClientUtils { public static String[] splitJsonObjects(String value) { int openCurlies = 0; List<String> objects = new ArrayList<String>(); StringBuilder object = new StringBuilder(); for (int i=0; i < value.length() ; i++) { char currentChar = value.charAt(i); object.append(currentChar); if (currentChar == '{') { openCurlies++; } if (currentChar == '}') { openCurlies--; } if (openCurlies == 0) { objects.add(object.toString()); object = new StringBuilder(); i++; } } return objects.toArray(new String[0]); } private ClientUtils(); static String getRandomHexColor(); static boolean isValidTimeFrameForZoomIn(long begin, long end); static String[] getDecodedParameters(PermalinkParameter parameter); static String[] getDecodedParameters(String parameter); static String[] splitJsonObjects(String value); static boolean isSesEnabled(); } | @Test public void shouldReadEmptyJson() { assertThat(splitJsonObjects("{}").length, is(1)); }
@Test public void shouldReadSingleJsonObject() { assertThat(splitJsonObjects("{\"parameter\":\"value\"}").length, is(1)); }
@Test public void shouldReadMultipleJsonObject() { assertThat(splitJsonObjects("{\"parameter\":\"value\"},{\\\"parameter\\\":\\\"value\\\"}").length, is(2)); }
@Test public void shouldReturnEmptyArrayIfInvalid() { assertThat(splitJsonObjects("{\"parameter\":\"value\"").length, is(0)); } |
QueryBuilder { String encodeValue(String value) { value = value.replace("%", "%25"); value = value.replace("+", "%2B"); value = value.replace(" ", "+"); value = value.replace("!", "%21"); value = value.replace("#", "%23"); value = value.replace("$", "%24"); value = value.replace("&", "%26"); value = value.replace("'", "%27"); value = value.replace("(", "%28"); value = value.replace(")", "%29"); value = value.replace(",", "%2C"); value = value.replace("/", "%2F"); value = value.replace(":", "%3A"); value = value.replace(";", "%3B"); value = value.replace("=", "%3D"); value = value.replace("?", "%3F"); value = value.replace("@", "%40"); value = value.replace("[", "%5B"); value = value.replace("]", "%5D"); return value; } void removeLastComma(StringBuilder builder); int length(); void appendCompressedParameter(); StringBuilder initialize(String baseUrl); @Override String toString(); } | @Test public void testEncodeValues() { queryBuilder = new QueryBuilder(); assertEquals("value+with+spaces", queryBuilder.encodeValue("value with spaces")); assertEquals("value%2Cwith%2Ccommas", queryBuilder.encodeValue("value,with,commas")); assertEquals("value+with+spaces%2Bplus+sign", queryBuilder.encodeValue("value with spaces+plus sign")); assertEquals("%21+%23+%24", queryBuilder.encodeValue("! # $")); assertEquals("%25+%26+%27+%28", queryBuilder.encodeValue("% & ' (")); assertEquals("%26+%27+%25+%28", queryBuilder.encodeValue("& ' % (")); } |
EventSubscriptionController { String replaceNonAlphaNumerics(String toReplace) { return toReplace.replaceAll("[^0-9a-zA-Z_]", "_"); } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String getProcedure(); String getFeatureOfInterest(); void setSelectedAbonnementName(String currentAbonnementName); String getSelectedAbonnementName(); boolean isSelectionValid(); void setSelectedSubscriptionTemplate(SubscriptionTemplate template); void updateSelectedRuleTemplate(SubscriptionTemplate template); String createSuggestedAbonnementName(); SimpleRuleType getSelectedRuleTemplate(); OverUndershootSelectionData getOverUndershootEntryConditions(); OverUndershootSelectionData getOverUndershootExitConditions(); SensorLossSelectionData getSensorLossConditions(); void clearSelectionData(); Rule createSimpleRuleFromSelection(); } | @Test public void shouldReplaceAllNonAlphaNumericsWithUnderscore() { assertThat(controllerUnderTest.replaceNonAlphaNumerics("#'+`´^°!§$%&/()=?-"), is("__________________")); }
@Test public void shouldNotReplaceAlphaNumericsWithUnderscores() { assertThat(controllerUnderTest.replaceNonAlphaNumerics("ABCNksdfjiu098723049234lkjdsf"), is("ABCNksdfjiu098723049234lkjdsf")); } |
EventSubscriptionController { String replaceAllUmlauts(String toReplace) { toReplace = toReplace.replaceAll("[ö]", "oe"); toReplace = toReplace.replaceAll("^Ö", "Oe"); toReplace = toReplace.replaceAll("[Ö]", "OE"); toReplace = toReplace.replaceAll("[ä]", "ae"); toReplace = toReplace.replaceAll("^Ä", "Ae"); toReplace = toReplace.replaceAll("[Ä]", "AE"); toReplace = toReplace.replaceAll("[ü]", "ue"); toReplace = toReplace.replaceAll("^Ü", "Ue"); toReplace = toReplace.replaceAll("[Ü]", "UE"); toReplace = toReplace.replaceAll("[ß]", "ss"); return toReplace; } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String getProcedure(); String getFeatureOfInterest(); void setSelectedAbonnementName(String currentAbonnementName); String getSelectedAbonnementName(); boolean isSelectionValid(); void setSelectedSubscriptionTemplate(SubscriptionTemplate template); void updateSelectedRuleTemplate(SubscriptionTemplate template); String createSuggestedAbonnementName(); SimpleRuleType getSelectedRuleTemplate(); OverUndershootSelectionData getOverUndershootEntryConditions(); OverUndershootSelectionData getOverUndershootExitConditions(); SensorLossSelectionData getSensorLossConditions(); void clearSelectionData(); Rule createSimpleRuleFromSelection(); } | @Test public void shouldReplaceAllUmlautsWithAlternatives() { assertThat(controllerUnderTest.replaceAllUmlauts("ÜüÖöÄäß"), is("UeueOEoeAEaess")); } |
EventSubscriptionController { String normalize(String toNormalize) { return replaceNonAlphaNumerics(replaceAllUmlauts(toNormalize)); } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String getProcedure(); String getFeatureOfInterest(); void setSelectedAbonnementName(String currentAbonnementName); String getSelectedAbonnementName(); boolean isSelectionValid(); void setSelectedSubscriptionTemplate(SubscriptionTemplate template); void updateSelectedRuleTemplate(SubscriptionTemplate template); String createSuggestedAbonnementName(); SimpleRuleType getSelectedRuleTemplate(); OverUndershootSelectionData getOverUndershootEntryConditions(); OverUndershootSelectionData getOverUndershootExitConditions(); SensorLossSelectionData getSensorLossConditions(); void clearSelectionData(); Rule createSimpleRuleFromSelection(); } | @Test public void shouldNormalizeUmlautsAndNonAlphaNumerics() { assertThat(controllerUnderTest.normalize("ÜüÖöÄäß#'+`´^°!§$%&/()=?-ABCNksdfjiu098723049234lkjdsf"), is("UeueOEoeAEaess__________________ABCNksdfjiu098723049234lkjdsf")); } |
SensorNetworkParser { public Map<String, ComponentType> parseSensorDescriptions(InputStream stream) { Map<String, ComponentType> sensorDescriptions = new HashMap<String, ComponentType>(); ComponentDocument[] components = parseNetworkComponentsFromDescribeSensorResponse(stream); for (ComponentDocument componentDocument : components) { ComponentType networkComponent = componentDocument.getComponent(); if (networkComponent.getIdentificationArray().length > 0) { Identification identification = networkComponent.getIdentificationArray(0); String id = xmlHelper.getUniqueId(identification.getIdentifierList()); if (id != null) { sensorDescriptions.put(id, networkComponent); } } } return sensorDescriptions; } Map<String, ComponentType> parseSensorDescriptions(InputStream stream); } | @Test public void givenSensorNetwork_parsingNetwork_parsedCorrectNumberOfNetworkMembers() throws XmlException, IOException { XmlObject network = XmlFileLoader.loadXmlFileViaClassloader(SENSOR_NETWORK_SUBSET, getClass()); Map<String, ComponentType> descriptions = new SensorNetworkParser().parseSensorDescriptions(network.newInputStream()); assertThat(descriptions.size(), is(4)); } |
ArcGISSoeEReportingMetadataHandler extends MetadataHandler { @Override public SOSMetadata performMetadataCompletion() throws Exception { String sosUrl = getServiceUrl(); SOSMetadata metadata = initMetadata(); Collection<SosTimeseries> observingTimeseries = createObservingTimeseries(sosUrl); TimeseriesParametersLookup lookup = metadata.getTimeseriesParametersLookup(); Map<Feature, Point> featureLocations = performGetFeatureOfInterest(lookup); List<Station> stations = new ArrayList<Station>(); LOGGER.debug("Destillate timeseries from #{} potential. This may take a while.", observingTimeseries.size()); for (Network network : networks.values()) { LOGGER.trace("############# PROCESS NETWORK #################"); LOGGER.debug("Build up cache for sensor network '{}'", network); String offeringId = network.getOffering(); for (String procedureId : network.getMembers()) { ComponentType component = sensorDescriptions.get(procedureId); completeProcedure(lookup.getProcedure(procedureId), component); if (component.getCapabilitiesArray() == null) { LOGGER.trace("No related features in capabilities block => Link all features available!"); LOGGER.warn("Not yet implemented."); continue; } SosTimeseries timeseries = new SosTimeseries(); timeseries.setOffering(lookup.getOffering(offeringId)); timeseries.setProcedure(lookup.getProcedure(procedureId)); Outputs outputs = component.getOutputs(); Capabilities sensorCapabilties = component.getCapabilitiesArray(0); for (String phenomenonId : xmlHelper.getRelatedPhenomena(outputs)) { Phenomenon phenomenon = lookup.getPhenomenon(phenomenonId); timeseries.setPhenomenon(phenomenon); OutputList outputList = outputs.getOutputList(); if (outputList.getOutputArray().length > 0) { ArcGISSoeDescribeSensorParser parser = createSensorMLParser(component); phenomenon.setUnitOfMeasure(parser.getUomFor(phenomenonId)); String name = outputList.getOutputArray(0).getName(); timeseries.setCategory(new Category(parseCategory(name), sosUrl)); phenomenon.setLabel(name); } String[] fois = xmlHelper.getRelatedFeatures(sensorCapabilties); for (String featureId : fois) { if ( !lookup.containsFeature(featureId)) { continue; } Feature feature = lookup.getFeature(featureId); Station station = metadata.getStation(featureId); if (station == null) { Point location = featureLocations.get(feature); LOGGER.trace("Create Station '{}' at '{}'.", featureId, location); station = new Station(featureId, sosUrl); station.setLocation(location); metadata.addStation(station); } station = metadata.getStation(featureId); SosTimeseries copy = timeseries.clone(); copy.setFeature(new Feature(featureId, sosUrl)); String service = metadata.getServiceUrl(); String version = metadata.getVersion(); copy.setSosService(new SosService(service, version)); LOGGER.trace("+++++++++++++ NEW TIMESERIES +++++++++++++++++"); LOGGER.trace("New Timeseries: '{}'.", copy.toString()); LOGGER.trace("Timeseries with procedure '{}'.", lookup.getProcedure(procedureId)); LOGGER.trace("Relate with phenomenon '{}'.", lookup.getPhenomenon(phenomenonId)); LOGGER.trace("Relate with offering '{}'.", lookup.getOffering(offeringId)); LOGGER.trace("Relate with feature '{}'.", lookup.getFeature(featureId)); LOGGER.trace("Relate with service '{}' ({}).", service, version); LOGGER.trace("With category '{}'.", copy.getCategory()); LOGGER.trace("Add to station '{}'.", station.getLabel()); LOGGER.trace("++++++++++++++++++++++++++++++++++++++++++++++"); station.addTimeseries(copy); } } } LOGGER.trace("##############################################"); } infoLogServiceSummary(metadata); metadata.setHasDonePositionRequest(true); return metadata; } ArcGISSoeEReportingMetadataHandler(SOSMetadata metadata); @Override void assembleTimeseriesMetadata(TimeseriesProperties properties); @Override SOSMetadata performMetadataCompletion(); boolean isCached(String procedure); @Override SOSMetadata updateMetadata(SOSMetadata metadata); } | @Test public void shouldPerformMetadataCompletion() throws Exception { SOSMetadata metadata = seam.performMetadataCompletion(); TimeseriesParametersLookup lookup = metadata.getTimeseriesParametersLookup(); Procedure procedure = lookup.getProcedure("http: assertThat(procedure.getLabel(), is("GB_StationProcess_1")); Phenomenon phenomenon = lookup.getPhenomenon("http: assertThat(phenomenon.getUnitOfMeasure(), is("ug.m-3")); } |
ArcGISSoeEReportingMetadataHandler extends MetadataHandler { protected String parseCategory(String phenomenonLabel) { Pattern pattern = Pattern.compile("\\((.*)\\)$"); Matcher matcher = pattern.matcher(parseLastBraceGroup(phenomenonLabel)); return matcher.find() ? matcher.group(1) : phenomenonLabel; } ArcGISSoeEReportingMetadataHandler(SOSMetadata metadata); @Override void assembleTimeseriesMetadata(TimeseriesProperties properties); @Override SOSMetadata performMetadataCompletion(); boolean isCached(String procedure); @Override SOSMetadata updateMetadata(SOSMetadata metadata); } | @Test public void shouldParseCategoryFromPhenomenonLabelWithSingleBraceGroup() { String category = seam.parseCategory("Cadmium lajsdf (aerosol)"); assertThat(category, is("aerosol")); }
@Test public void shouldParseCategoryFromPhenomenonLabelWithMultipleBraceGroup() { String category = seam.parseCategory("Benzo(a)anthracene in PM10 (air+aerosol)"); assertThat(category, is("air+aerosol")); }
@Test public void shouldParseWholePhenomenonWhenNoBraceGroupAvailable() { String category = seam.parseCategory("aerosol"); assertThat(category, is("aerosol")); } |
QueryParser { Map<String, String> parseKvps(String query) { Map<String, String> parsedKvps = new HashMap<String, String>(); if (query == null || query.isEmpty()) { return parsedKvps; } else { String[] splittedKvps = query.split("&"); for (String kvp : splittedKvps) { addKvp(kvp, parsedKvps); } return parsedKvps; } } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParseValidKvps() { String validQuery = "single=blah&multiple=value1,vlaue2"; Map<String, String> kvps = permalinkParser.parseKvps(validQuery); assertTrue("map does not contain value 'single'.", kvps.containsKey("SINGLE")); assertTrue("map does not contain value 'multiple'.", kvps.containsKey("MULTIPLE")); }
@Test public void testParseInvalidKvps() { String invalidQuery = "single&multiple=value1,vlaue2"; Map<String, String> kvps = permalinkParser.parseKvps(invalidQuery); assertFalse("map does not contain value 'single'.", kvps.containsKey("SINGLE")); assertTrue("map does not contain value 'multiple'.", kvps.containsKey("MULTIPLE")); }
@Test public void testParseEncodedKvps() { StringBuilder validQuery = new StringBuilder(); validQuery.append("single"); validQuery.append("="); validQuery.append("sadf"); validQuery.append("&"); validQuery.append("multiple"); validQuery.append("="); validQuery.append("value1"); validQuery.append("%2C"); validQuery.append("value2_part1+value2_part2"); validQuery.append("&"); validQuery.append("url"); validQuery.append("="); validQuery.append("http%3A QueryParser permalinkParser = new QueryParser(null, false); Map<String, String> kvps = permalinkParser.parseKvps(validQuery.toString()); assertTrue("map does not contain value 'single'.", kvps.containsKey("SINGLE")); assertTrue("map does not contain value 'multiple'.", kvps.containsKey("MULTIPLE")); assertTrue("map does not contain value 'url'.", kvps.containsKey("URL")); } |
FeatureParser { public Map<Feature, Point> parseFeatures(InputStream stream) { Map<Feature, Point> featureLocations = new HashMap<Feature, Point>(); try { GetFeatureOfInterestResponseDocument responseDoc = GetFeatureOfInterestResponseDocument.Factory.parse(stream); GetFeatureOfInterestResponseType response = responseDoc.getGetFeatureOfInterestResponse(); for (FeaturePropertyType member : response.getFeatureMemberArray()) { PointDocument pointDoc = xmlHelper.getPoint(member, crsUtil); Feature feature = parseFeatureFrom(member); Point location = getCrs84Location(pointDoc); featureLocations.put(feature, location); } } catch (XmlException e) { LOGGER.error("Could not parse GetFeatureOfInterestResponse.", e); } catch (IOException e) { LOGGER.error("Could not read GetFeatureOfInterestResponse.", e); } LOGGER.debug("Parsed #" + featureLocations.size() + " feature locations."); return featureLocations; } FeatureParser(String serviceUrl, CRSUtils crsHelper); Map<Feature, Point> parseFeatures(InputStream stream); } | @Test public void shouldParseLocations() throws XmlException, IOException { XmlObject featureResponse = loadXmlFileViaClassloader(GET_FOI_RESPONSE, getClass()); Map<Feature, Point> featureLocations = featureParser.parseFeatures(featureResponse.newInputStream()); if (featureLocations == null || featureLocations.isEmpty()) { fail("No features have been parsed!"); } else { assertThat(featureLocations.size(), is(3)); } } |
ArcGISSoeDescribeSensorParser { public String getUomFor(String phenomenonId) { String xPath = "$this String query = String.format(xPath, phenomenonId); Quantity output = xmlHelper.parseFirst(sensorML, query, Quantity.class); return output == null ? null : output.getUom().getCode(); } ArcGISSoeDescribeSensorParser(XmlObject sml); String getUomFor(String phenomenonId); String getShortName(); SensorML getSensorML(); } | @Test public void shouldParseFirstAvailableUomFromInconsistentMultipleOutputSection() { assertThat("UOM code is not correct!", parser.getUomFor(PHENOMENON), is("mg.m-3")); } |
ArcGISSoeDescribeSensorParser { public String getShortName() { String query = "$this Identifier identifier = xmlHelper.parseFirst(sensorML, query, Identifier.class); return identifier == null ? null : identifier.getTerm().getValue(); } ArcGISSoeDescribeSensorParser(XmlObject sml); String getUomFor(String phenomenonId); String getShortName(); SensorML getSensorML(); } | @Test public void shouldParseShortName() { assertThat("shortName is incorrect!", parser.getShortName(), is("GB_StationProcess_3746")); } |
HydroMetadataHandler extends MetadataHandler { protected Collection<SosTimeseries> getAvailableTimeseries(XmlObject result_xb, SosTimeseries timeserie, SOSMetadata metadata) throws XmlException, IOException { ArrayList<SosTimeseries> timeseries = new ArrayList<SosTimeseries>(); StringBuilder sb = new StringBuilder(); sb.append("declare namespace gda='"); sb.append(SoapSOSRequestBuilder_200.SOS_GDA_10_NS); sb.append("'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"); XmlObject[] response = result_xb.selectPath(sb.toString()); if (response == null || response.length ==0) { sb = new StringBuilder(); sb.append("declare namespace gda='"); sb.append(SoapSOSRequestBuilder_200.SOS_GDA_10_PREFINAL_NS); sb.append("'; $this/gda:GetDataAvailabilityResponse/gda:dataAvailabilityMember"); response = result_xb.selectPath(sb.toString()); } for (XmlObject xmlObject : response) { SosTimeseries addedtimeserie = new SosTimeseries(); String feature = getAttributeOfChildren(xmlObject, "featureOfInterest", "href").trim(); String phenomenon = getAttributeOfChildren(xmlObject, "observedProperty", "href").trim(); String procedure = getAttributeOfChildren(xmlObject, "procedure", "href").trim(); addedtimeserie.setFeature(new Feature(feature, metadata.getServiceUrl())); addedtimeserie.setPhenomenon(new Phenomenon(phenomenon, metadata.getServiceUrl())); addedtimeserie.setProcedure(new Procedure(procedure, metadata.getServiceUrl())); String category = getLastPartOf(phenomenon) + " (" + getLastPartOf(procedure) + ")"; addedtimeserie.setCategory(new Category(category, metadata.getServiceUrl())); addedtimeserie.setOffering(new Offering(timeserie.getOfferingId(), metadata.getServiceUrl())); addedtimeserie.setSosService(new SosService(timeserie.getServiceUrl(), metadata.getVersion())); addedtimeserie.getSosService().setLabel(metadata.getTitle()); timeseries.add(addedtimeserie); } return timeseries; } HydroMetadataHandler(SOSMetadata metadata); @Override void assembleTimeseriesMetadata(TimeseriesProperties properties); @Override SOSMetadata performMetadataCompletion(); @Override SOSMetadata updateMetadata(SOSMetadata metadata); } | @Test public void shouldParseGetDataAvailabilityResponse() throws Exception { Collection<SosTimeseries> timeseries = seam.getAvailableTimeseries(); assertThat(timeseries.size(), is(140)); } |
SoapSOSRequestBuilder_200 extends SOSRequestBuilder_200_OXFExtension { @Override public String buildGetObservationRequest(ParameterContainer parameters) throws OXFException { parameters.removeParameterShell(parameters.getParameterShellWithCommonName(GET_OBSERVATION_RESPONSE_FORMAT_PARAMETER)); parameters.addParameterShell(GET_OBSERVATION_RESPONSE_FORMAT_PARAMETER, WATERML_20_NS); String request = super.buildGetObservationRequest(parameters); EnvelopeDocument envelope = addSoapEnvelope(request, GET_OBS_SOAP_HEADER_ACTION); return envelope.xmlText(XmlUtil.PRETTYPRINT); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); String buildGetDataAvailabilityRequest(ParameterContainer parameters); void setUrl(String sosUrl); } | @Test public void shouldReplaceDefaultOM20ResponseFormatWithWaterML20() throws XmlException, IOException, OXFException { String request = builder.buildGetObservationRequest(parameters); EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(request); GetObservationDocument goDoc = (GetObservationDocument) readBodyNodeFrom(envelope, null); String actual = goDoc.getGetObservation().getResponseFormat(); Assert.assertThat(actual, is("http: } |
SoapSOSRequestBuilder_200 extends SOSRequestBuilder_200_OXFExtension { public String buildGetDataAvailabilityRequest(ParameterContainer parameters) throws OXFException { StringBuilder sb = new StringBuilder(); ParameterShell observedProperty = parameters.getParameterShellWithCommonName("observedProperty"); ParameterShell procedure = parameters.getParameterShellWithCommonName("procedure"); ParameterShell offering = parameters.getParameterShellWithCommonName("offering"); ParameterShell feature = parameters.getParameterShellWithCommonName("featureOfInterest"); ParameterShell version = parameters.getParameterShellWithCommonName("version"); ParameterShell phenomenonTime = parameters.getParameterShellWithCommonName("phenomenonTime"); sb.append("<gda:GetDataAvailability service=\"SOS\""); sb.append(" version=\"").append(version.getSpecifiedValue()).append("\""); sb.append(" xmlns:gda=\""); boolean gdaPrefinal = false; if (parameters.containsParameterShellWithCommonName("gdaPrefinalNamespace")) { ParameterShell gdaNamespace = parameters.getParameterShellWithCommonName("gdaPrefinalNamespace"); gdaPrefinal = Boolean.parseBoolean((String)gdaNamespace.getSpecifiedValue()); } if (gdaPrefinal) { LOGGER.warn("The correct GDA namespace is now: {}", SOS_GDA_10_NS); LOGGER.warn("Instance is configured to use the prefinal GDA namespace '{}'.", SOS_GDA_10_PREFINAL_NS); LOGGER.warn("You will get an exception once the SOS has been updated and dropped the old namespace."); sb.append(SOS_GDA_10_PREFINAL_NS); } else { sb.append(SOS_GDA_10_NS); } sb.append("\" >"); if (observedProperty != null) { sb.append("<gda:observedProperty>").append(observedProperty.getSpecifiedValue()).append("</gda:observedProperty>"); } if (procedure != null) { sb.append("<gda:procedure>").append(procedure.getSpecifiedValue()).append("</gda:procedure>"); } if (offering != null) { sb.append("<gda:offering>").append(offering.getSpecifiedValue()).append("</gda:offering>"); } if (feature != null) { sb.append("<gda:featureOfInterest>").append(feature.getSpecifiedValue()).append("</gda:featureOfInterest>"); } if (phenomenonTime != null) { sb.append("<swes:extension xmlns:swes=\"http: sb.append("<fes:During xmlns:fes=\"http: sb.append("<fes:ValueReference>phenomenonTime</fes:ValueReference>"); sb.append("<gml:TimePeriod gml:id=\"tp_1\" xmlns:gml=\"http: String[] phenomTime = phenomenonTime.getSpecifiedTypedValueArray(String[].class); sb.append("<gml:beginPosition>").append(phenomTime[0]).append("</gml:beginPosition>"); sb.append("<gml:endPosition>").append(phenomTime[1]).append("</gml:endPosition>"); sb.append("</gml:TimePeriod>"); sb.append("</fes:During>"); sb.append("</swes:extension>"); } sb.append("</gda:GetDataAvailability>"); EnvelopeDocument envelope = addSoapEnvelope(sb.toString(), GET_DATA_AVAILABILITY); return envelope.xmlText(XmlUtil.PRETTYPRINT); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetFeatureOfInterestRequest(ParameterContainer parameters); @Override String buildDescribeSensorRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); String buildGetDataAvailabilityRequest(ParameterContainer parameters); void setUrl(String sosUrl); } | @Test public void shouldHaveOfficialGDANamespace() throws XmlException, IOException, OXFException { parameters.addParameterShell("gdaPrefinalNamespace", "false"); String request = builder.buildGetDataAvailabilityRequest(parameters); EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(request); XmlObject gdaDoc = readBodyNodeFrom(envelope, null); XmlObject[] xml = gdaDoc.selectChildren("http: Assert.assertThat(xml.length, is(1)); XmlObject[] children = xml[0].selectChildren("http: Assert.assertThat(children.length, is(not(0))); }
@Test public void shouldHavePrefinalGDANamespace() throws XmlException, IOException, OXFException { parameters.addParameterShell("gdaPrefinalNamespace", "true"); String request = builder.buildGetDataAvailabilityRequest(parameters); EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(request); XmlObject gdaDoc = readBodyNodeFrom(envelope, null); XmlObject[] xml = gdaDoc.selectChildren("http: Assert.assertThat(xml.length, is(1)); XmlObject[] children = xml[0].selectChildren("http: Assert.assertThat(children.length, is(not(0))); } |
TimeseriesParameter implements Serializable { public String getLabel() { return label; } TimeseriesParameter(); TimeseriesParameter(String parameterId, String[] parametersToGenerateId); @JsonIgnore String getGlobalId(); void setLabel(String label); String getLabel(); } | @Test public void shouldParseLastUrnFragmentAsLabel() { TestParameter testParameter = new TestParameter("urn:123::999:id2134"); assertThat(testParameter.getLabel(), is("id2134")); }
@Test public void shouldParseLastHttpPathAsLabel() { TestParameter testParameter = new TestParameter("http: assertThat(testParameter.getLabel(), is("D_GB_Sample.xml")); }
@Test public void shouldParseHttpFragmentAsLabel() { TestParameter testParameter = new TestParameter("http: assertThat(testParameter.getLabel(), is("GB_SamplingFeature_281")); } |
TimeseriesParameter implements Serializable { @JsonIgnore public String getGlobalId() { return globalId; } TimeseriesParameter(); TimeseriesParameter(String parameterId, String[] parametersToGenerateId); @JsonIgnore String getGlobalId(); void setLabel(String label); String getLabel(); } | @Test public void shouldHaveTestSuffixWithinGlobalId() { TestParameter testParameter = new TestParameter("someParameterId"); assertThat(testParameter.getGlobalId(), startsWith("test_")); } |
ResultPage implements Serializable { public boolean isLastPage() { return offset + results.length >= total; } @SuppressWarnings("unused") private ResultPage(); ResultPage(T[] results, int offset, int total); int getOffset(); int getTotal(); T[] getResults(); boolean isLastPage(); } | @Test public void shouldIndicateThatMorePagesAreAvailable() { ResultPage<String> firstPage = getFirstPage(); assertThat(firstPage.isLastPage(), is(false)); }
@Test public void shouldIndicateLastPageWithOverlappingSize() { ResultPage<String> lastPage = getLastPageOverlapping(); assertThat(lastPage.isLastPage(), is(true)); }
@Test public void shouldIndicateLastPageWhenMatchingSize() { ResultPage<String> lastPage = getLastPageWithMatchingSize(); assertThat(lastPage.isLastPage(), is(true)); } |
QueryParser { String decodeValue(String value) { value = value.replace("%21", "!"); value = value.replace("%23", "#"); value = value.replace("%24", "$"); value = value.replace("%26", "&"); value = value.replace("%27", "'"); value = value.replace("%28", "("); value = value.replace("%29", ")"); value = value.replace("%2C", ","); value = value.replace("%2F", "/"); value = value.replace("%3A", ":"); value = value.replace("%3B", ";"); value = value.replace("%3D", "="); value = value.replace("%3F", "?"); value = value.replace("%40", "@"); value = value.replace("%5B", "["); value = value.replace("%5D", "]"); value = value.replace("+", " "); value = value.replace("%2B", "+"); value = value.replace("%25", "%"); return value; } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testDecodeQuery() { assertEquals("Unexpected decoded URL.", DECODED_SOS_URL, permalinkParser.decodeValue(ENCODED_SOS_URL)); String decodedCharacters = "! # $ % & ' ( ) * + , / : ; = ? @ [ ]"; String encodedCharacters = "%21+%23+%24+%25+%26+%27+%28+%29+*+%2B+%2C+/+%3A+%3B+%3D+%3F+@+%5B+%5D"; assertEquals("Unexpected decoding.", decodedCharacters, permalinkParser.decodeValue(encodedCharacters)); } |
QueryParser { public Collection<String> parseServices() { String serviceValues = kvps.get(SERVICES.name()); return parseCommaSeparatedValues(serviceValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParseServiceKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("services=").append(ENCODED_SOS_URL); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedServices = parser.parseServices(); assertTrue("Invalid size: " + parsedServices.size(), parsedServices.size() == 1); assertTrue("URL could not be parsed.", parsedServices.contains(DECODED_SOS_URL)); } |
QueryParser { public Collection<String> parseVersions() { String versionValues = kvps.get(VERSIONS.name()); return parseCommaSeparatedValues(versionValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParseVersionKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("versions=").append("2.0.0"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedVersions = parser.parseVersions(); assertTrue("Invalid size: " + parsedVersions.size(), parsedVersions.size() == 1); assertTrue("Versions could not be parsed.", parsedVersions.contains("2.0.0")); } |
QueryParser { public Collection<String> parseOfferings() { String offeringValues = kvps.get(OFFERINGS.name()); return parseCommaSeparatedValues(offeringValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); } | @Test public void testParseOfferingKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("offerings=").append("WASSERSTAND_ROHDATEN"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedOfferings = parser.parseOfferings(); assertTrue("Invalid size: " + parsedOfferings.size(), parsedOfferings.size() == 1); assertTrue("Offerings could not be parsed.", parsedOfferings.contains("WASSERSTAND_ROHDATEN")); } |
CheckList { public static List<Class> getChecks() { return ImmutableList.<Class> of( ParsingErrorCheck.class, XPathCheck.class ); } private CheckList(); static List<Class> getChecks(); static final String REPOSITORY_KEY; static final String REPOSITORY_NAME; static final String SONAR_WAY_PROFILE; } | @Test public void count() { int count = 0; List<File> files = (List<File>) FileUtils.listFiles(new File("src/main/java/org/sonar/_1C/checks/"), new String[] {"java"}, false); for (File file : files) { if (file.getName().endsWith("Check.java")) { count++; } } assertThat(CheckList.getChecks().size()).isEqualTo(count); }
@Test public void test() { List<Class> checks = CheckList.getChecks(); if(checks.size()==0) return; for (Class cls : checks) { String testName = '/' + cls.getName().replace('.', '/') + "Test.class"; assertThat(getClass().getResource(testName)) .overridingErrorMessage("No test for " + cls.getSimpleName()) .isNotNull(); } ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.1C", Locale.ENGLISH); List<String> keys = Lists.newArrayList(); List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks); for (Rule rule : rules) { keys.add(rule.getKey()); resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name"); assertThat(getClass().getResource("/org/sonar/l10n/1C/rules/1C/" + rule.getKey() + ".html")) .overridingErrorMessage("No description for " + rule.getKey()) .isNotNull(); assertThat(rule.getDescription()) .overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file") .isNull(); for (RuleParam param : rule.getParams()) { resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey()); assertThat(param.getDescription()) .overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file") .isEmpty(); } } assertThat(keys).doesNotHaveDuplicates(); } |
_1CTokenizer implements Tokenizer { public final void tokenize(SourceCode source, Tokens cpdTokens) { Lexer lexer = _1CLexer.create(new _1CConfiguration(charset)); String fileName = source.getFileName(); List<Token> tokens = lexer.lex(new File(fileName)); for (Token token : tokens) { TokenEntry cpdToken = new TokenEntry(getTokenImage(token), fileName, token.getLine()); cpdTokens.add(cpdToken); } cpdTokens.add(TokenEntry.getEOF()); } _1CTokenizer(Charset charset); final void tokenize(SourceCode source, Tokens cpdTokens); } | @Test public void test() { _1CTokenizer tokenizer = new _1CTokenizer(Charset.forName("UTF-8")); SourceCode source = mock(SourceCode.class); when(source.getFileName()).thenReturn(new File("src/test/resources/cpd/Person.bsl").getAbsolutePath()); Tokens tokens = new Tokens(); tokenizer.tokenize(source, tokens); assertThat(tokens.getTokens().size()).isGreaterThan(1); assertThat(tokens.getTokens().get(tokens.size() - 1)).isEqualTo(TokenEntry.getEOF()); } |
_1CRuleRepository extends RuleRepository { @Override public List<Rule> createRules() { return annotationRuleParser.parse(CheckList.REPOSITORY_KEY, CheckList.getChecks()); } _1CRuleRepository(AnnotationRuleParser annotationRuleParser); @Override List<Rule> createRules(); } | @Test public void test() { _1CRuleRepository ruleRepository = new _1CRuleRepository(new AnnotationRuleParser()); assertThat(ruleRepository.getKey()).isEqualTo("1c"); assertThat(ruleRepository.getName()).isEqualTo("Sonar"); List<Rule> rules = ruleRepository.createRules(); assertThat(rules.size()).isEqualTo(CheckList.getChecks().size()); } |
_1CPlugin extends SonarPlugin { public List<Class<? extends Extension>> getExtensions() { return ImmutableList.of( _1C.class, _1CSourceImporter.class, _1CColorizerFormat.class, _1CCpdMapping.class, _1CSquidSensor.class, _1CRuleRepository.class, _1CProfile.class, _1CCommonRulesEngineProvider.class, LCOVSensor.class, _1CTestDriverSensor.class, _1CTestSensor.class); } List<Class<? extends Extension>> getExtensions(); static final String FALSE; static final String FILE_SUFFIXES_KEY; static final String FILE_SUFFIXES_DEFVALUE; static final String PROPERTY_PREFIX; static final String LCOV_REPORT_PATH; static final String LCOV_REPORT_PATH_DEFAULT_VALUE; static final String _1CTESTDRIVER_REPORTS_PATH; static final String _1CTESTDRIVER_REPORTS_PATH_DEFAULT_VALUE; static final String _1CTEST_REPORTS_PATH; static final String _1CTEST_REPORTS_PATH_DEFAULT_VALUE; } | @Test public void testGetExtensions() throws Exception { assertThat(plugin.getExtensions().size()).isEqualTo(11); } |
_1CProfile extends ProfileDefinition { @Override public RulesProfile createProfile(ValidationMessages validation) { return annotationProfileParser.parse(CheckList.REPOSITORY_KEY, CheckList.SONAR_WAY_PROFILE, _1C.KEY, CheckList.getChecks(), validation); } _1CProfile(AnnotationProfileParser annotationProfileParser); @Override RulesProfile createProfile(ValidationMessages validation); } | @Test public void should_create_sonar_way_profile() { ValidationMessages validation = ValidationMessages.create(); RuleFinder ruleFinder = ruleFinder(); _1CProfile definition = new _1CProfile(new AnnotationProfileParser(ruleFinder)); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getLanguage()).isEqualTo(_1C.KEY); assertThat(profile.getName()).isEqualTo(RulesProfile.SONAR_WAY_NAME); assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY)) .hasSize(0); assertThat(validation.hasErrors()).isFalse(); } |
_1CSquidSensor implements Sensor { public boolean shouldExecuteOnProject(Project project) { return _1C.KEY.equalsIgnoreCase(project.getLanguageKey()); } _1CSquidSensor(RulesProfile profile, FileLinesContextFactory fileLinesContextFactory); boolean shouldExecuteOnProject(Project project); void analyse(Project project, SensorContext context); @Override String toString(); } | @Test public void should_execute_on_javascript_project() { Project project = new Project("key"); project.setLanguageKey("java"); assertThat(sensor.shouldExecuteOnProject(project)).isFalse(); project.setLanguageKey("1c"); assertThat(sensor.shouldExecuteOnProject(project)).isTrue(); } |
_1CSquidSensor implements Sensor { public void analyse(Project project, SensorContext context) { this.project = project; this.context = context; Collection<SquidAstVisitor<LexerlessGrammar>> squidChecks = annotationCheckFactory.getChecks(); List<SquidAstVisitor<LexerlessGrammar>> visitors = Lists.newArrayList(squidChecks); visitors.add(new FileLinesVisitor(project, fileLinesContextFactory)); this.scanner = _1CAstScanner.create(createConfiguration(project), visitors.toArray(new SquidAstVisitor[visitors.size()])); scanner.scanFiles(InputFileUtils.toFiles(project.getFileSystem().mainFiles(_1C.KEY))); Collection<SourceCode> squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class)); save(squidSourceFiles); } _1CSquidSensor(RulesProfile profile, FileLinesContextFactory fileLinesContextFactory); boolean shouldExecuteOnProject(Project project); void analyse(Project project, SensorContext context); @Override String toString(); } | @Test public void should_analyse() { ProjectFileSystem fs = mock(ProjectFileSystem.class); when(fs.getSourceCharset()).thenReturn(Charset.forName("UTF-8")); InputFile inputFile = InputFileUtils.create( new File("src/test/resources/cpd"), new File("src/test/resources/cpd/Person.bsl")); when(fs.mainFiles(_1C.KEY)).thenReturn(ImmutableList.of(inputFile)); Project project = new Project("1c"); project.setFileSystem(fs); SensorContext context = mock(SensorContext.class); sensor.analyse(project, context); verify(context).saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.FILES), Mockito.eq(1.0)); verify(context).saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.LINES), Mockito.eq(10.0)); verify(context).saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.NCLOC), Mockito.eq(3.0)); verify(context).saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.FUNCTIONS), Mockito.eq(1.0)); verify(context).saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.COMPLEXITY), Mockito.eq(0.0)); verify(context).saveMeasure(Mockito.any(Resource.class), Mockito.eq(CoreMetrics.COMMENT_LINES), Mockito.eq(3.0)); } |
_1CConfigurationModel extends AbstractConfigurationModel { public List<ConfigurationProperty> getProperties() { return ImmutableList.of(charsetProperty); } List<ConfigurationProperty> getProperties(); @Override Charset getCharset(); @Override Parser<? extends Grammar> doGetParser(); @Override List<Tokenizer> doGetTokenizers(); } | @Test public void test() { assertThat(model.getTokenizers().size()).isEqualTo(5); assertThat(model.getProperties()).hasSize(1); } |
LCOVParser { public Map<String, CoverageMeasuresBuilder> parse(List<String> lines) { Map<String, CoverageMeasuresBuilder> coveredFiles = Maps.newHashMap(); Map<String, BranchData> branches = Maps.newHashMap(); String filePath = null; CoverageMeasuresBuilder fileCoverage = CoverageMeasuresBuilder.create(); for (String line : lines) { if (line.startsWith(SF)) { fileCoverage = CoverageMeasuresBuilder.create(); filePath = line.substring(SF.length()); } else if (line.startsWith(DA)) { String execution = line.substring(DA.length()); String executionCount = execution.substring(execution.indexOf(',') + 1); String lineNumber = execution.substring(0, execution.indexOf(',')); fileCoverage.setHits(Integer.valueOf(lineNumber).intValue(), Integer.valueOf(executionCount).intValue()); } else if (line.startsWith(BRDA)) { String[] tokens = line.substring(BRDA.length()).trim().split(","); String lineNumber = tokens[0]; boolean taken = "1".equals(tokens[3]); BranchData branchData = branches.get(lineNumber); if (branchData == null) { branchData = new BranchData(); branches.put(lineNumber, branchData); } branchData.branches++; if (taken) { branchData.visitedBranches++; } } else if (END_RECORD.equals(line.trim())) { for (Map.Entry<String, BranchData> entry : branches.entrySet()) { fileCoverage.setConditions(Integer.valueOf(entry.getKey()), entry.getValue().branches, entry.getValue().visitedBranches); } branches.clear(); coveredFiles.put(filePath, fileCoverage); } } return coveredFiles; } Map<String, CoverageMeasuresBuilder> parseFile(File file); Map<String, CoverageMeasuresBuilder> parse(List<String> lines); } | @Test public void test() { Map<String, CoverageMeasuresBuilder> result = parser.parse(Arrays.asList( "SF:file1.js", "DA:1,1", "end_of_record", "SF:file2.js", "FN:2,(anonymous_1)", "FNDA:2,(anonymous_1)", "DA:1,1", "DA:2,0", "BRDA:11,1,0,1", "BRDA:11,1,0,0", "end_of_record")); assertThat(result).hasSize(2); CoverageMeasuresBuilder fileCoverage = result.get("file1.js"); assertThat(fileCoverage.getLinesToCover()).isEqualTo(1); assertThat(fileCoverage.getCoveredLines()).isEqualTo(1); assertThat(fileCoverage.getConditions()).isEqualTo(0); assertThat(fileCoverage.getCoveredConditions()).isEqualTo(0); fileCoverage = result.get("file2.js"); assertThat(fileCoverage.getLinesToCover()).isEqualTo(2); assertThat(fileCoverage.getCoveredLines()).isEqualTo(1); assertThat(fileCoverage.getConditions()).isEqualTo(2); assertThat(fileCoverage.getCoveredConditions()).isEqualTo(1); } |
LCOVParser { public Map<String, CoverageMeasuresBuilder> parseFile(File file) { final List<String> lines; try { lines = FileUtils.readLines(file); } catch (IOException e) { throw new SonarException("Could not read content from file: " + file, e); } return parse(lines); } Map<String, CoverageMeasuresBuilder> parseFile(File file); Map<String, CoverageMeasuresBuilder> parse(List<String> lines); } | @Test public void unreadable_file() { thrown.expect(SonarException.class); thrown.expectMessage("Could not read content from file: not-found"); parser.parseFile(new File("not-found")); } |
LCOVSensor implements Sensor { public boolean shouldExecuteOnProject(Project project) { return _1C.KEY.equalsIgnoreCase(project.getLanguageKey()) && StringUtils.isNotBlank(_1c.getSettings().getString(_1CPlugin.LCOV_REPORT_PATH)); } LCOVSensor(_1C _1c); boolean shouldExecuteOnProject(Project project); void analyse(Project project, SensorContext context); @Override String toString(); } | @Test public void test_should_execute() { Project project = mockProject(new Java()); assertThat(sensor.shouldExecuteOnProject(project)).isFalse(); project = mockProject(new _1C(settings)); assertThat(sensor.shouldExecuteOnProject(project)).isTrue(); settings.setProperty(_1CPlugin.LCOV_REPORT_PATH, ""); assertThat(sensor.shouldExecuteOnProject(project)).isFalse(); } |
LCOVSensor implements Sensor { public void analyse(Project project, SensorContext context) { File lcovFile = project.getFileSystem().resolvePath(_1c.getSettings().getString(_1CPlugin.LCOV_REPORT_PATH)); if (lcovFile.isFile()) { LCOVParser parser = new LCOVParser(); LOG.info("Analysing {}", lcovFile); Map<String, CoverageMeasuresBuilder> coveredFiles = parser.parseFile(lcovFile); analyseCoveredFiles(project, context, coveredFiles); } } LCOVSensor(_1C _1c); boolean shouldExecuteOnProject(Project project); void analyse(Project project, SensorContext context); @Override String toString(); } | @Test public void report_not_found() throws Exception { Project project = mockProject(new _1C(settings)); when(fileSystem.resolvePath("xTestDriver.conf-coverage.dat")) .thenReturn(new File("not-found")); sensor.analyse(project, context); verifyZeroInteractions(context); }
@Test public void testFileInXTestDriverCoverageReport() { when(fileSystem.mainFiles(_1C.KEY)).thenReturn(Arrays.asList(InputFileUtils.create(baseDir, "Person.bsl"))); Project project = mockProject(new _1C(settings)); when(fileSystem.resolvePath("xTestDriver.conf-coverage.dat")) .thenReturn(new File("src/test/resources/org/sonar/plugins/_1C/xtestdriver/xTestDriver.conf-coverage.dat")); sensor.analyse(project, context); verify(context, times(3)).saveMeasure((Resource) anyObject(), (Measure) anyObject()); }
@Test public void testFileNotInXTestDriverCoverageReport() { InputFile inputFile = InputFileUtils.create(baseDir, "another.bsl"); when(fileSystem.mainFiles(_1C.KEY)).thenReturn(Arrays.asList(inputFile)); Project project = mockProject(new _1C(settings)); when(fileSystem.resolvePath("xTestDriver.conf-coverage.dat")) .thenReturn(new File("src/test/resources/org/sonar/plugins/_1C/xtestdriver/xTestDriver.conf-coverage.dat")); when(context.getMeasure(org.sonar.api.resources.File.fromIOFile(inputFile.getFile(), project), CoreMetrics.LINES)).thenReturn( new Measure(CoreMetrics.LINES, (double) 20)); when(context.getMeasure(org.sonar.api.resources.File.fromIOFile(inputFile.getFile(), project), CoreMetrics.NCLOC)).thenReturn( new Measure(CoreMetrics.LINES, (double) 22)); sensor.analyse(project, context); verify(context).saveMeasure((Resource) anyObject(), eq(CoreMetrics.LINES_TO_COVER), eq(22.0)); verify(context).saveMeasure((Resource) anyObject(), eq(CoreMetrics.UNCOVERED_LINES), eq(22.0)); } |
LCOVSensor implements Sensor { @Override public String toString() { return getClass().getSimpleName(); } LCOVSensor(_1C _1c); boolean shouldExecuteOnProject(Project project); void analyse(Project project, SensorContext context); @Override String toString(); } | @Test public void test_toString() { assertThat(sensor.toString()).isEqualTo("LCOVSensor"); } |
_1CColorizerFormat extends CodeColorizerFormat { @Override public List<Tokenizer> getTokenizers() { return ImmutableList.of( new StringTokenizer("<span class=\"s\">", "</span>"), new CDocTokenizer("<span class=\"cd\">", "</span>"), new JavadocTokenizer("<span class=\"cppd\">", "</span>"), new CppDocTokenizer("<span class=\"cppd\">", "</span>"), new HtmlCommentTokenizer("<span class=\"cd\">", "</span>"), new KeywordsTokenizer("<span class=\"k\">", "</span>", _1CKeyword.keywordValues())); } _1CColorizerFormat(); @Override List<Tokenizer> getTokenizers(); } | @Test public void testGetTokenizers() { List<Tokenizer> list = (new _1CColorizerFormat()).getTokenizers(); assertThat(indexOf(list, JavadocTokenizer.class)).isLessThan(indexOf(list, CppDocTokenizer.class)); } |
DockerAccessWithHcClient implements DockerAccess { @Override public void loadImage(String image, File tarArchive) throws DockerAccessException { String url = urlBuilder.loadImage(); try { delegate.post(url, tarArchive, new BodyAndStatusResponseHandler(), HTTP_OK); } catch (IOException e) { throw new DockerAccessException(e, "Unable to load %s", tarArchive); } } DockerAccessWithHcClient(String apiVersion,
String baseUrl,
String certPath,
int maxConnections,
KitLogger log); @Override String getServerApiVersion(); @Override void buildImage(String image, File dockerArchive, BuildOptions options); @Override boolean hasImage(String name); @Override String getImageId(String name); @Override void loadImage(String image, File tarArchive); @Override void pullImage(String image, String authHeader, String registry); @Override void pushImage(String image, String authHeader, String registry, int retries); @Override void saveImage(String image, String filename); @Override void tag(String sourceImage, String targetImage, boolean force); @Override boolean removeImage(String image, boolean... forceOpt); } | @Test public void testLoadImage() { givenAnImageName("test"); givenArchiveFile("test.tar"); whenLoadImage(); thenNoException(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.