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> con...
@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 Ex...
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 NonCachi...
@Test public void testPolicyConditionCacheConfigDisabled() { assertThat(this.policyConditionCacheConfig.conditionCache(true), instanceOf(NonCachingGroovyConditionCache.class)); } @Test public void testPolicyConditionCacheConfigEnabled() { assertThat(this.policyConditionCacheConfig.conditionCache(false), instanceOf(InMe...
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...
@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); PolicyEvaluationR...
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> boundVaria...
@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 = "illega...
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; } fi...
@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", ...
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...
@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> iterato...
@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); asser...
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...
@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 plainChainResul...
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 (Qu...
@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...
StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } StrictTransportSecurityHeader(); @Override StrictTransportSecurity toValue(CharSequence value); @Override CharSequence toC...
@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(StrictTransport...
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.toA...
@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.n...
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 allowFr...
@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.has...
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 + "'"); } I...
@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() { Fr...
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 protoc...
@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....
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 : ...
@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() { S...
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 (sal...
@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...
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),...
@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)...
@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.va...
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 = (H...
@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(...
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); @Overrid...
@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.SE...
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; } @I...
@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....
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 ...
@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 testU...
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.g...
@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(r...
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 I...
@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_...
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 { Sys...
@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 (I...
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); ProgressButto...
@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 attr...
@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 getProgre...
@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...
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);...
@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);...
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("M...
@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.setProgressAnd...
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) @Re...
@Test public void testDelete() throws Exception { CommentModel model = new CommentModel(); model.setUsername("testuser"); model.setId("dqe345e456rf34rw"); model.setPageId("product0815"); model.setEmailAddress("example@example.com"); model.setComment("I am the comment"); String id = service.put(model); this.mvc.perform(...
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...
@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(...
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.listSpamCo...
@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...
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); s...
@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...
@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, T...
@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) ; Ass...
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() { whil...
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 p...
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 Singleto...
@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...
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...
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...
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_observatio...
@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(); Collec...
@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...
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> parseFeatur...
@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: " + parse...
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()...
@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 siz...
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> parseFeatu...
@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 p...
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 ident...
@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.get...
@Test public void shouldNotAddValuesTwiceWhenCreatingTimeseriesDuringDaylightSavingSwitch() throws Exception { SosTimeseries timeseries = createSosTimeseries(); GetObservationResponseToOxfFeatureCollectionReader reader = createReader(); String[] foiIds = new String[]{timeseries.getFeatureId()}; String[] procedureIds = ...
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...
@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 = createSosTimes...
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(Strin...
@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); stat...
@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.exitNotif...
@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;...
@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) xml...
@Test public void shouldUnwrapSensorMLFromDescribeSensorResponseAndSoapEnvelope() throws XmlException, IOException, XMLHandlingException { XmlObject response = XmlFileLoader.loadXmlFileViaClassloader(soapResponse, getClass()); response = DescribeSensorParser.unwrapSensorMLFrom(response); SensorMLDocument.class.cast(res...
SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String encodePlusInParameter(String parameter) { return parameter.replace("+", "%2B"); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Override String bui...
@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 buildGe...
@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 buildG...
@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 parameter...
@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 == '{') { openC...
@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...
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("'", ...
@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 ...
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(); S...
@Test public void shouldReplaceAllNonAlphaNumericsWithUnderscore() { assertThat(controllerUnderTest.replaceNonAlphaNumerics("#'+`´^°!§$%&/()=?-"), is("__________________")); } @Test public void shouldNotReplaceAlphaNumericsWithUnderscores() { assertThat(controllerUnderTest.replaceNonAlphaNumerics("ABCNksdfjiu0987230492...
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 = ...
@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(); ...
@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 ...
@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...
ArcGISSoeEReportingMetadataHandler extends MetadataHandler { @Override public SOSMetadata performMetadataCompletion() throws Exception { String sosUrl = getServiceUrl(); SOSMetadata metadata = initMetadata(); Collection<SosTimeseries> observingTimeseries = createObservingTimeseries(sosUrl); TimeseriesParametersLookup l...
@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")); Phen...
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; } ArcGISSoeEReporti...
@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)anthr...
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; } } Qu...
@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("MULT...
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 = responseDo...
@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(...
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(XmlOb...
@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);...
@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(); s...
@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.addParameterSh...
@Test public void shouldReplaceDefaultOM20ResponseFormatWithWaterML20() throws XmlException, IOException, OXFException { String request = builder.buildGetObservationRequest(parameters); EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(request); GetObservationDocument goDoc = (GetObservationDocument) readBodyN...
SoapSOSRequestBuilder_200 extends SOSRequestBuilder_200_OXFExtension { public String buildGetDataAvailabilityRequest(ParameterContainer parameters) throws OXFException { StringBuilder sb = new StringBuilder(); ParameterShell observedProperty = parameters.getParameterShellWithCommonName("observedProperty"); ParameterShe...
@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 =...
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.getLa...
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)...
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...
@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"; assertEqua...
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(); Collec...
@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.s...
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(); Collec...
@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(), p...
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(); Co...
@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: " + parse...
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); } ...
_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 TokenEntr...
@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...
_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.get...
_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, _1C...
@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); @Ove...
@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.getLan...
_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, S...
@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(squidChec...
@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)).thenRe...
_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> doGetToke...
@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 l...
@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); CoverageMeas...
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(...
@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(Proje...
@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(senso...
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, Covera...
@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 testFileInXTestDriverCoverage...
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 cla...
@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 DockerAccessExcepti...
@Test public void testLoadImage() { givenAnImageName("test"); givenArchiveFile("test.tar"); whenLoadImage(); thenNoException(); }