method2testcases
stringlengths 118
6.63k
|
---|
### Question:
Datastore { public RunQueryResponse runQuery(RunQueryRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("runQuery", request)) { return RunQueryResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("runQuery", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); }### Answer:
@Test public void runQuery() throws Exception { RunQueryRequest.Builder request = RunQueryRequest.newBuilder(); request.getQueryBuilder(); RunQueryResponse.Builder response = RunQueryResponse.newBuilder(); response.getBatchBuilder() .setEntityResultType(EntityResult.ResultType.FULL) .setMoreResults(QueryResultBatch.MoreResultsType.NOT_FINISHED); expectRpc("runQuery", request.build(), response.build()); } |
### Question:
DatastoreEmulator extends Datastore { @Deprecated public synchronized void start(String emulatorDir, String projectId, String... commandLineOptions) throws DatastoreEmulatorException { checkNotNull(emulatorDir, "emulatorDir cannot be null"); checkNotNull(projectId, "projectId cannot be null"); checkState(state == State.NEW, "Cannot call start() more than once."); try { startEmulatorInternal( emulatorDir + "/cloud_datastore_emulator", projectId, Arrays.asList(commandLineOptions)); state = State.STARTED; } finally { if (state != State.STARTED) { state = State.STOPPED; } } } DatastoreEmulator(RemoteRpc rpc, String localHost, DatastoreEmulatorOptions options); void clear(); @Deprecated synchronized void start(String emulatorDir, String projectId, String... commandLineOptions); synchronized void start(); synchronized void stop(); synchronized File getProjectDirectory(); }### Answer:
@Test public void testArgs() throws DatastoreEmulatorException { DatastoreEmulator datastore = new DatastoreEmulator(null, "blar", options) { @Override void startEmulatorInternal( String emulatorDir, String projectId, List<String> cmdLineOpts) { } }; try { datastore.start(null, "projectId"); fail("expected exception"); } catch (NullPointerException npe) { } try { datastore.start("path/to/emulator", null); fail("expected exception"); } catch (NullPointerException npe) { } datastore.start("path/to/emulator", "projectId"); } |
### Question:
RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); }### Answer:
@Test public void testException() { Status statusProto = Status.newBuilder() .setCode(Code.UNAUTHENTICATED_VALUE) .setMessage("The request does not have valid authentication credentials.") .build(); DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.UNAUTHENTICATED, exception.getCode()); assertEquals("The request does not have valid authentication credentials.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testInvalidProtoException() { DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream("<invalid proto>".getBytes()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals("Unable to parse Status protocol buffer: HTTP status code was 401.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testEmptyProtoException() { Status statusProto = Status.newBuilder().build(); DatastoreException exception = RemoteRpc.makeException( "url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 404); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals( "Unexpected OK error code with HTTP status code of 404. Message: .", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testEmptyProtoExceptionUnauthenticated() { Status statusProto = Status.newBuilder().build(); DatastoreException exception = RemoteRpc.makeException( "url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.UNAUTHENTICATED, exception.getCode()); assertEquals("Unauthenticated.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testPlainTextException() { DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream("Text Error".getBytes()), "text/plain", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals( "Non-protobuf error: Text Error. HTTP status code was 401.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); } |
### Question:
RemoteRpc { public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); httpRequest.setThrowExceptionOnExecuteError(false); httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = httpResponse.getContent()) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return httpResponse.getContent(); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); }### Answer:
@Test public void testGzip() throws IOException, DatastoreException { BeginTransactionResponse response = newBeginTransactionResponse(); InjectedTestValues injectedTestValues = new InjectedTestValues(gzip(response), new byte[1], true); RemoteRpc rpc = newRemoteRpc(injectedTestValues); InputStream is = rpc.call("beginTransaction", BeginTransactionResponse.getDefaultInstance()); BeginTransactionResponse parsedResponse = BeginTransactionResponse.parseFrom(is); is.close(); assertEquals(response, parsedResponse); assertEquals(-1, injectedTestValues.inputStream.read()); } |
### Question:
Patterns { public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); }### Answer:
@Test public void testMustacheTagPattern() { String text = "{{foo }} and {{#bar}}...{{/bar}}"; Pattern tagPattern = Patterns .newMustacheTagPattern(MustacheEngineBuilder.newBuilder() .build().getConfiguration()); Matcher matcher = tagPattern.matcher(text); StringBuffer result = new StringBuffer(); int occurences = 0; while (matcher.find()) { System.out.println(matcher.group(0)); matcher.appendReplacement(result, "FOUND"); occurences++; } matcher.appendTail(result); assertEquals(3, occurences); assertEquals("FOUND and FOUND...FOUND", result.toString()); } |
### Question:
IOUtils { public static String toString(Reader input) throws IOException { return toString(input, DEFAULT_BUFFER_SIZE); } private IOUtils(); static String toString(Reader input); static String toString(Reader input, int bufferSize); static String toString(Reader input, int bufferSize, boolean close); static void copy(Readable in, Appendable out, int bufferSize); }### Answer:
@Test public void testToString() throws IOException { assertEquals("foo", IOUtils.toString(new StringReader("foo"))); assertEquals("foo", IOUtils.toString(new StringReader("foo"), 1)); } |
### Question:
Checker { @SuppressWarnings("rawtypes") public static boolean isFalsy(Object value) { if (value == null) { return true; } else if (value instanceof Boolean) { return !(Boolean) value; } else if (value instanceof Collection) { return ((Collection) value).isEmpty(); } else if (value instanceof Iterable) { return !((Iterable) value).iterator().hasNext(); } else if (value.getClass().isArray()) { return Array.getLength(value) == 0; } else if (value instanceof CharSequence) { return ((CharSequence) value).length() == 0; } else if (value instanceof Number) { return isZero((Number) value); } return false; } private Checker(); static void checkArgument(boolean condition, String errorMessage); static void checkArgumentsNotNull(Object... arguments); static void checkArgumentNotNull(Object argument); static void checkArgumentNotEmpty(String argument); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); @SuppressWarnings("rawtypes") static boolean isFalsy(Object value); }### Answer:
@Test public void testIsFalsy() { assertTrue(Checker.isFalsy(null)); assertTrue(Checker.isFalsy(false)); assertTrue(Checker.isFalsy(new String[] {})); assertTrue(Checker.isFalsy(Collections.emptyList())); assertTrue(Checker.isFalsy("")); assertTrue(Checker.isFalsy(new StringBuilder())); assertTrue(Checker.isFalsy(0)); assertTrue(Checker.isFalsy(BigDecimal.ZERO)); assertTrue(Checker.isFalsy(new BigDecimal("0.000"))); assertFalse(Checker.isFalsy(Boolean.TRUE)); assertFalse(Checker.isFalsy(new Object[] { "foo" })); assertFalse(Checker.isFalsy(Collections.singleton("foo"))); assertFalse(Checker.isFalsy("foo")); assertFalse(Checker.isFalsy(new StringBuilder().append("foo"))); assertFalse(Checker.isFalsy(-10)); assertFalse(Checker.isFalsy(BigDecimal.TEN)); assertFalse(Checker.isFalsy(0.2)); assertFalse(Checker.isFalsy(new BigDecimal("-0.01"))); } |
### Question:
ReflectionResolver extends AbstractResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } MemberWrapper wrapper; MemberKey key = MemberKey.newInstance(contextObject, name); if (memberCache != null) { wrapper = memberCache.get(key).orElse(null); } else { wrapper = findWrapper(key).orElse(null); } if (wrapper == null) { return null; } try { return wrapper.getValue(contextObject); } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_REFLECT_INVOCATION_ERROR, e); } } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); static final int REFLECTION_RESOLVER_PRIORITY; static final String COMPUTING_CACHE_CONSUMER_ID; static final ConfigurationKey MEMBER_CACHE_MAX_SIZE_KEY; static final ConfigurationKey HINT_FALLBACK_ENABLED_KEY; static final String GET_PREFIX; static final String IS_PREFIX; }### Answer:
@Test public void testResolution() { ReflectionResolver resolver = new ReflectionResolver(); MustacheEngineBuilder.newBuilder().omitServiceLoaderConfigurationExtensions().addResolver(resolver).build(); Hammer hammer = new Hammer(); assertNull(resolver.resolve(null, "whatever", null)); assertNotNull(resolver.resolve(hammer, "age", null)); assertEquals(10, resolver.resolve(hammer, "age", null)); assertNull(resolver.resolve(hammer, "getAgeForName", null)); } |
### Question:
ReflectionResolver extends AbstractResolver { @Override public void init() { long memberCacheMaxSize = configuration .getLongPropertyValue(MEMBER_CACHE_MAX_SIZE_KEY); LOGGER.debug("Initialized [memberCacheMaxSize: {}]", memberCacheMaxSize); if (memberCacheMaxSize > 0) { memberCache = configuration.getComputingCacheFactory().create( COMPUTING_CACHE_CONSUMER_ID, ReflectionResolver::findWrapper, null, memberCacheMaxSize, null); } hintFallbackEnabled = configuration .getBooleanPropertyValue(HINT_FALLBACK_ENABLED_KEY); } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); static final int REFLECTION_RESOLVER_PRIORITY; static final String COMPUTING_CACHE_CONSUMER_ID; static final ConfigurationKey MEMBER_CACHE_MAX_SIZE_KEY; static final ConfigurationKey HINT_FALLBACK_ENABLED_KEY; static final String GET_PREFIX; static final String IS_PREFIX; }### Answer:
@Test(expected = IllegalStateException.class) public void testMultipleInit() { ReflectionResolver resolver = new ReflectionResolver(); MustacheEngineBuilder.newBuilder().omitServiceLoaderConfigurationExtensions().addResolver(resolver).build(); resolver.init(null); } |
### Question:
DateTimeFormatResolver extends TransformResolver { @Override public void init() { super.init(); customPattern = configuration .getStringPropertyValue(CUSTOM_PATTERN_KEY); LOGGER.info("Initialized [customPattern: {}]", customPattern); } DateTimeFormatResolver(); DateTimeFormatResolver(int priority); @Override Object transform(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); static final int DATE_TIME_FORMAT_RESOLVER_PRIORITY; static final ConfigurationKey CUSTOM_PATTERN_KEY; }### Answer:
@Test(expected = IllegalStateException.class) public void testMultipleInit() { DateTimeFormatResolver resolver = new DateTimeFormatResolver(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver).build(); resolver.init(null); } |
### Question:
IndexResolver extends AbstractResolver { protected boolean notAnIndex(String name) { return !isAnIndex(name); } IndexResolver(int priority); }### Answer:
@Test public void testNotAnIndex() { IndexResolver indexResolver = new IndexResolver(0) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { return null; } }; assertTrue(indexResolver.notAnIndex("-1")); assertTrue(indexResolver.notAnIndex("size")); assertTrue(indexResolver.notAnIndex(".1")); assertTrue(indexResolver.notAnIndex("1,5")); assertFalse(indexResolver.notAnIndex("1500")); } |
### Question:
DummyTransformResolver extends TransformResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null && matches(name)) { return marker; } else if (contextObject != null && contextObject.equals(marker)) { return performTransformation(contextObject, name, context); } return null; } DummyTransformResolver(int priority,
String... matchNames); DummyTransformResolver(int priority,
Transformer transformer, String... matchNames); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); }### Answer:
@Test public void testResolution() { MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver).build(); assertNull(resolver.resolve(null, "whatever", null)); Object marker = resolver.resolve(null, "ng", null); assertNotNull(marker); assertEquals("{{FOO}}", resolver.resolve(marker, "foo", null)); } |
### Question:
Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); static Builder<T> decorate(T delegate); static Decorator<T> decorate(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); @SuppressWarnings("unchecked") static T unwrap(T instance); @Override Object get(String key); @Override String toString(); static final String KEY_GET_DELEGATE; }### Answer:
@Test public void testGetDelegate() { Hammer hammer = new Hammer(); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{delegate.name}}") .render(decorate(hammer).compute("name", h -> h.getName().toUpperCase()).build(engine))); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{foo.name}}").render( decorate(hammer).delegateKey("foo").compute("name", h -> h.getName().toUpperCase()).build(engine))); }
@Test public void testNestedDecorator() { Hammer hammer = new Hammer(5); assertEquals("5:Edgar:bar", engine.compileMustache("{{age}}:{{foo}}:{{bar}}") .render(decorate(decorate(hammer).compute("foo", h -> h.getName()).build(engine)) .put("bar", "bar").build(engine))); } |
### Question:
MapResolver extends AbstractResolver { @SuppressWarnings("rawtypes") @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } if (contextObject instanceof Map) { Map map = (Map) contextObject; return map.get(name); } if (contextObject instanceof Mapper) { Mapper mapper = (Mapper) contextObject; return mapper.get(name); } return null; } MapResolver(); MapResolver(int priority); @SuppressWarnings("rawtypes") @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); static final int MAP_RESOLVER_PRIORITY; }### Answer:
@Test public void testResolution() { MapResolver resolver = new MapResolver(); assertNull(resolver.resolve(null, "foo", null)); assertNotNull( resolver.resolve(ImmutableMap.of("bar", "baz"), "bar", null)); assertNull( resolver.resolve(ImmutableMap.of("bar", "baz"), "qux", null)); } |
### Question:
Patterns { public static Pattern newSetDelimitersContentPattern() { return Pattern.compile("(\\S+)(\\s+)(\\S+)"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); }### Answer:
@Test public void testSetDelimitersPattern() { String set1 = "<% %>"; String set2 = "[ ]"; String set3 = "= ="; Pattern setDelimitersPattern = Patterns .newSetDelimitersContentPattern(); Matcher set1Matcher = setDelimitersPattern.matcher(set1); assertEquals(true, set1Matcher.find()); assertEquals("<%", set1Matcher.group(1)); assertEquals("%>", set1Matcher.group(3)); Matcher set2Matcher = setDelimitersPattern.matcher(set2); assertEquals(true, set2Matcher.find()); assertEquals("[", set2Matcher.group(1)); assertEquals("]", set2Matcher.group(3)); Matcher set3Matcher = setDelimitersPattern.matcher(set3); assertEquals(true, set3Matcher.find()); assertEquals("=", set3Matcher.group(1)); assertEquals("=", set3Matcher.group(3)); } |
### Question:
HelperExecutionHandler { static Iterator<String> splitHelperName(String name, Segment segment) { Character stringLiteral = null; boolean arrayLiteral = false; boolean space = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char character = name.charAt(i); if (character == ' ') { if (!space) { if (stringLiteral == null && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(character); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(character)) { if (stringLiteral != null) { if (character == stringLiteral.charValue()) { stringLiteral = null; } } else { stringLiteral = character; } } else if (stringLiteral == null && Strings.isListLiteralStart(character)) { arrayLiteral = true; } else if (stringLiteral == null && Strings.isListLiteralEnd(character)) { arrayLiteral = false; } space = false; buffer.append(character); } } if (buffer.length() > 0) { if (stringLiteral != null || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); }### Answer:
@Test public void testSplitHelperName() { assertHelperNameParts("name foo.bar", "name", "foo.bar"); assertHelperNameParts("name hash1=\"DD-MM-yyyy HH:mm\"", "name", "hash1=\"DD-MM-yyyy HH:mm\""); assertHelperNameParts("name key='value'", "name", "key='value'"); assertHelperNameParts("name key=''value''", "name", "key=''value''"); assertHelperNameParts("key='value foo=' 'bar'", "key='value foo='", "'bar'"); assertHelperNameParts("'key'='value foo=' 'bar'", "'key'='value foo='", "'bar'"); assertHelperNameParts("foo='bar = \n baz' qux", "foo='bar = \n baz'", "qux"); assertHelperNameParts("[ 'foo', 'bar', qux] foo", "[ 'foo', 'bar', qux]", "foo"); assertHelperNameParts("1 20 ['', '1'] foo", "1", "20", "['', '1']", "foo"); assertHelperNameParts("'[1, 2]'", "'[1, 2]'"); assertHelperNameParts("'[1, '2', 'alpha']'", "'[1, '2', 'alpha']'"); assertHelperNameParts("foo=[1, '2']", "foo=[1, '2']"); assertHelperNameParts("if \"var eq 'value_without_space'\"", "if", "\"var eq 'value_without_space'\""); assertHelperNameParts("key='value\" foo=' 'bar'", "key='value\" foo='", "'bar'"); assertHelperNameParts("if \"var eq 'value with space'\"", "if", "\"var eq 'value with space'\""); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> assertHelperNameParts("name key=''value'")) .check(() -> assertHelperNameParts("name key=value'")) .check(() -> assertHelperNameParts("name key='value foo")) .check(() -> assertHelperNameParts("name key=value' foo")) .check(() -> assertHelperNameParts("'name key=value")) .check(() -> assertHelperNameParts("key=\"value \" and\"")) .check(() -> assertHelperNameParts("foo='bar\"")); } |
### Question:
HelperExecutionHandler { static int getFirstDeterminingEqualsCharPosition(String part) { boolean stringLiteral = false; for (int i = 0; i < part.length(); i++) { if (Strings.isStringLiteralSeparator(part.charAt(i))) { if (i == 0) { return -1; } stringLiteral = !stringLiteral; } else { if (!stringLiteral && part.charAt(i) == '=') { return i; } } } return -1; } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); }### Answer:
@Test public void testGetFirstDeterminingEqualsCharPosition() { assertEquals(3, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("foo=bar")); assertEquals(3, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("foo='bar='")); assertEquals(1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("1='bar='")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("'m=n'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition(" ' m=n'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("'1'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("\"foo\"")); } |
### Question:
ConfigurationProperties { static String buildPropertyKey(String propertyName, String[] prefixParts) { return buildPropertyKey(propertyName, Strings.UNDERSCORE, prefixParts); } private ConfigurationProperties(); }### Answer:
@Test public void testBuildPropertyKey() { assertEquals("org.trimou.engine.config.myPropertyName", ConfigurationProperties.buildPropertyKey("MY_PROPERTY_NAME", new String[] { ConfigurationPropertiesTest.class .getPackage().getName() })); assertEquals("org.trimou.engine.config.myPropertyName", ConfigurationProperties.buildPropertyKey("MY.PROPERTY.NAME", ".", new String[] { ConfigurationPropertiesTest.class .getPackage().getName() })); } |
### Question:
ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); }### Answer:
@Test public void testConvertConfigValue() { assertEquals(10, ConfigurationProperties .convertConfigValue(Integer.class, "10")); assertEquals(10L, ConfigurationProperties.convertConfigValue(Long.class, "10")); assertEquals(Boolean.FALSE, ConfigurationProperties .convertConfigValue(Boolean.class, "10")); }
@Test(expected = IllegalStateException.class) public void testConvertConfigValueFails() { ConfigurationProperties.convertConfigValue(BigDecimal.class, "10"); } |
### Question:
ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public String getKey() { return key; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); }### Answer:
@Test public void testGetKey() { final AtomicReference<String> key = new AtomicReference<>(); MustacheEngineBuilder .newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver( new AbstractResolver( 1) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { key.set(context.getKey()); return null; } }).build().compileMustache("getkey", "{{my.key.foo}}") .render(null); assertEquals("my.key.foo", key.get()); } |
### Question:
ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public int getKeyPartIndex() { return keyPartIndex; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); }### Answer:
@Test public void testGetKeyPartIndex() { final List<Integer> indexes = new ArrayList<>(); MustacheEngineBuilder .newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(new AbstractResolver(1) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { indexes.add(context.getKeyPartIndex()); return "OK"; } }).build().compileMustache("getkeypartindex", "{{my.key.foo}}") .render(null); assertEquals(3L, indexes.size()); assertEquals(Integer.valueOf(0), indexes.get(0)); assertEquals(Integer.valueOf(1), indexes.get(1)); assertEquals(Integer.valueOf(2), indexes.get(2)); } |
### Question:
DefaultLiteralSupport extends AbstractConfigurationAware implements LiteralSupport { @Override public Object getLiteral(String value, MustacheTagInfo tagInfo) { if (Strings.isEmpty(value)) { return null; } Object literal = null; if (Strings.isStringLiteralSeparator(value.charAt(0))) { literal = value.substring(1, value.length() - 1); } else if (value.equals("true")) { literal = Boolean.TRUE; } else if (value.equals("false")) { literal = Boolean.FALSE; } else if (integerLiteralPattern.matcher(value).matches()) { try { literal = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse integer literal: " + value, e); } } else if (longLiteralPattern.matcher(value).matches()) { try { literal = Long .parseLong(value.substring(0, value.length() - 1)); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse long literal: " + value, e); } } return literal; } @Override Object getLiteral(String value, MustacheTagInfo tagInfo); }### Answer:
@Test public void testGetLiteral() { LiteralSupport literalSupport = new DefaultLiteralSupport(); assertNull(literalSupport.getLiteral("foo", null)); assertNull(literalSupport.getLiteral("1.0", null)); assertEquals(10, literalSupport.getLiteral("+10", null)); assertEquals(-2010, literalSupport.getLiteral("-2010", null)); assertEquals("foo", literalSupport.getLiteral("'foo'", null)); assertEquals("bar.me", literalSupport.getLiteral("\"bar.me\"", null)); assertEquals(10L, literalSupport.getLiteral("10L", null)); assertEquals(-2010L, literalSupport.getLiteral("-2010l", null)); assertNull(literalSupport.getLiteral("2.0", null)); assertEquals(Boolean.TRUE, literalSupport.getLiteral("true", null)); assertEquals(Boolean.FALSE, literalSupport.getLiteral("false", null)); } |
### Question:
BracketDotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS)) { return Iterables.singletonIterator(key); } boolean stringLiteral = false; boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (!stringLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } else { buffer.append(key.charAt(i)); } } } else { if (Strings.isStringLiteralSeparator(key.charAt(i))) { stringLiteral = !stringLiteral; } else { buffer.append(key.charAt(i)); } separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); }### Answer:
@Test public void testSplit() { BracketDotKeySplitter splitter = new BracketDotKeySplitter(); assertIterator(splitter.split("a..bar:.c"), "a", "bar:", "c"); assertIterator(splitter.split(". "), " "); assertIterator(splitter.split("."), "."); assertIterator(splitter.split("foo"), "foo"); assertIterator(splitter.split("foo[\"bar\"]"), "foo", "bar"); assertIterator(splitter.split("foo[\"a.b.c\"]"), "foo", "a.b.c"); assertIterator(splitter.split("foo[\"bar\"].baz"), "foo", "bar", "baz"); assertIterator(splitter.split("a[\"b\"].c.d[\"e\"][\"f\"]"), "a", "b", "c", "d", "e", "f"); assertIterator(splitter.split("foo['bar']"), "foo", "bar"); assertIterator(splitter.split("foo['bar dot'][\"qux\"].me"), "foo", "bar dot", "qux", "me"); } |
### Question:
DotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS) || !key.contains(Strings.DOT)) { return Iterables.singletonIterator(key); } boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } } else { buffer.append(key.charAt(i)); separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); }### Answer:
@Test public void testSplit() { DotKeySplitter splitter = new DotKeySplitter(); assertIterator(splitter.split("a..bar:.c"), "a", "bar:", "c"); assertIterator(splitter.split(". "), " "); assertIterator(splitter.split("."), "."); assertIterator(splitter.split("foo"), "foo"); } |
### Question:
Patterns { public static Pattern newHelperIntegerLiteralPattern() { return Pattern.compile("(\\+|-)?\\d{1,10}"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); }### Answer:
@Test public void testHelperIntOrLongLiteralPattern() { assertFalse(Patterns.newHelperIntegerLiteralPattern() .matcher("\"foo\"").matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("1") .matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("+12") .matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("-10000") .matches()); assertFalse(Patterns.newHelperIntegerLiteralPattern().matcher("1.0") .matches()); assertFalse(Patterns.newHelperIntegerLiteralPattern() .matcher("1000000000000").matches()); } |
### Question:
FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); @Override Reader locateRealPath(String realPath); static Builder builder(); }### Answer:
@Test public void testLocatorNoSuffix() throws IOException { TemplateLocator locator = FileSystemTemplateLocator.builder() .setRootPath("src/test/resources/locator/file").build(); MustacheEngineBuilder.newBuilder().addTemplateLocator(locator).build(); Set<String> ids = locator.getAllIdentifiers(); assertEquals(7, ids.size()); assertTrue(ids.contains("index.foo")); assertTrue(ids.contains("home.foo")); assertTrue(ids.contains("foo.foo")); assertTrue(ids.contains("detail.html")); assertTrue(ids.contains("encoding.html")); assertTrue(ids.contains("sub/bar.foo")); assertTrue(ids.contains("sub/subsub/qux.foo")); assertEquals("{{foo}}", read(locator.locate("index.foo"))); assertEquals("bar", read(locator.locate("home.foo"))); assertEquals("foo", read(locator.locate("foo.foo"))); assertEquals("<html/>", read(locator.locate("detail.html"))); assertEquals("{{foo}}", read(locator.locate("sub/bar.foo"))); assertEquals("{{bar}}", read(locator.locate("sub/subsub/qux.foo"))); }
@Test public void testCustomVirtualPathSeparator() throws IOException { TemplateLocator locator = FileSystemTemplateLocator.builder() .setPriority(1).setRootPath("src/test/resources/locator/file") .setSuffix("foo").build(); MustacheEngineBuilder.newBuilder().addTemplateLocator(locator) .setProperty(PathTemplateLocator.VIRTUAL_PATH_SEPARATOR_KEY, "*") .build(); Set<String> names = locator.getAllIdentifiers(); assertEquals(5, names.size()); assertTrue(names.contains("index")); assertTrue(names.contains("home")); assertTrue(names.contains("foo")); assertTrue(names.contains("sub*bar")); assertTrue(names.contains("sub*subsub*qux")); assertEquals("{{foo}}", read(locator.locate("index"))); assertEquals("bar", read(locator.locate("home"))); assertEquals("{{foo}}", read(locator.locate("sub*bar"))); assertEquals("{{bar}}", read(locator.locate("sub*subsub*qux"))); } |
### Question:
SegmentBases { static boolean isStandaloneLine(List<SegmentBase> line) { boolean standaloneCandidate = false; for (SegmentBase segment : line) { if (SegmentType.VALUE.equals(segment.getType())) { return false; } else if (SegmentType.TEXT.equals(segment.getType())) { if (!Strings.containsOnlyWhitespace(segment.getContent())) { return false; } } else if (isStandaloneCandidate(segment.getType())) { standaloneCandidate = true; } } return standaloneCandidate; } private SegmentBases(); }### Answer:
@Test public void testIsStandaloneLine() { assertTrue(SegmentBases.isStandaloneLine(ImmutableList.of( new SegmentBase(SegmentType.LINE_SEPARATOR, Strings.LINE_SEPARATOR_LF, 0, 0), new SegmentBase(SegmentType.TEXT, " ", 0, 0), new ContainerSegmentBase(SegmentType.SECTION, "test", 0, 0)))); assertFalse(SegmentBases.isStandaloneLine(ImmutableList.of( new SegmentBase(SegmentType.LINE_SEPARATOR, Strings.LINE_SEPARATOR_LF, 0, 0), new SegmentBase(SegmentType.TEXT, "Not empty", 0, 0), new ContainerSegmentBase(SegmentType.SECTION, "test", 0, 0)))); } |
### Question:
EnhancedStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); static final String COMPUTING_CACHE_CONSUMER_ID; }### Answer:
@Test public void testClearData() { EnhancedStatsCollector collector = new EnhancedStatsCollector(); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("bar", "BAR"); mustache.render(null); assertEquals(1, collector.getStats(mustache).getFinished()); collector.clearData(); assertNull(collector.getStats(mustache)); } |
### Question:
EnhancedStatsCollector extends AbstractStatsCollector { public Stats getStats(Mustache mustache) { Checker.checkArgumentNotNull(mustache); ConcurrentMap<Long, ExecutionData> times = data.getIfPresent(mustache .getGeneratedId()); if (times != null) { return parseData(mustache.getName(), mustache.getGeneratedId(), times.values()); } return null; } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); static final String COMPUTING_CACHE_CONSUMER_ID; }### Answer:
@Test public void testCustomPredicate() { EnhancedStatsCollector collector = new EnhancedStatsCollector( (t) -> false, TimeUnit.DAYS); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("qux", "Oops"); mustache.render(null); assertNull(collector.getStats(mustache)); } |
### Question:
SimpleStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); static final String COMPUTING_CACHE_CONSUMER_ID; }### Answer:
@Test public void testClearData() { SimpleStatsCollector collector = new SimpleStatsCollector(); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("bar", "BAR"); mustache.render(null); assertEquals(1, collector.getSimpleStats("bar").getExecutions()); collector.clearData(); assertNull(collector.getSimpleStats("bar")); } |
### Question:
SimpleStatsCollector extends AbstractStatsCollector { public SimpleStats getSimpleStats(String templateId) { ComputingCache<Long, AtomicLong> entry = data.getIfPresent(templateId); if (entry != null) { return new SimpleStats(templateId, entry.getAllPresent()); } return null; } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); static final String COMPUTING_CACHE_CONSUMER_ID; }### Answer:
@Test public void testCustomPredicate() { SimpleStatsCollector collector = new SimpleStatsCollector((t) -> false, TimeUnit.DAYS); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("qux", "Oops"); mustache.render(null); assertNull(collector.getSimpleStats("qux")); } |
### Question:
ObjectToDateConverter implements Converter<Object, Date> { @Override public Date convert(Object value) { Date converted = null; if (value instanceof Date) { converted = (Date) value; } else if (value instanceof Calendar) { converted = ((Calendar) value).getTime(); } else if (value instanceof LocalDateTime) { converted = Date.from(((LocalDateTime) value) .atZone(ZoneId.systemDefault()).toInstant()); } else if (value instanceof LocalDate) { converted = Date.from(((LocalDate) value) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } else if (value instanceof Long) { converted = new Date((Long) value); } else if (value instanceof BigDecimal) { converted = new Date(((BigDecimal) value).longValue()); } else if (value instanceof String && pattern != null) { try { converted = new SimpleDateFormat(pattern).parse((String) value); } catch (ParseException e) { throw new MustacheException( MustacheProblem.RENDER_GENERIC_ERROR, "Unable to parse the string value %s using pattern %s", value, pattern); } } return converted; } ObjectToDateConverter(); ObjectToDateConverter(String pattern); @Override Date convert(Object value); }### Answer:
@Test public void testConverter() { String pattern = "yyyy.MM.dd HH:mm:ss.SSS"; SimpleDateFormat format = new SimpleDateFormat(pattern); ObjectToDateConverter converter = new ObjectToDateConverter(pattern); Date now = new Date(); Calendar cal = Calendar.getInstance(); Calendar midnight = Calendar.getInstance(); midnight.set(Calendar.HOUR_OF_DAY, 0); midnight.set(Calendar.MINUTE, 0); midnight.set(Calendar.SECOND, 0); midnight.set(Calendar.MILLISECOND, 0); LocalDateTime dateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()); LocalDate date = LocalDateTime.ofInstant(midnight.toInstant(), ZoneId.systemDefault()).toLocalDate(); assertNull(converter.convert(Float.MIN_NORMAL)); assertEquals(now, converter.convert(BigDecimal.valueOf(now.getTime()))); assertEquals(now, converter.convert(now)); assertEquals(now, converter.convert(now.getTime())); assertEquals(cal.getTime(), converter.convert(cal)); assertEquals(now, converter.convert(format.format(now))); assertEquals(now, converter.convert(dateTime)); assertEquals(midnight.getTime(), converter.convert(date)); } |
### Question:
DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override Object convert(Object from); }### Answer:
@SuppressWarnings("unchecked") @Test public void testInterpolation() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addContextConverter(decorate(String.class) .compute("reverse", string -> new StringBuilder(string).reverse().toString()).build()) .addContextConverter(decorate(Hammer.class).put("translate", "kladivo") .compute("name", hammer -> hammer.getName().toUpperCase()).build()) .addContextConverter(decorate(List.class).compute("reversed", list -> { List<?> reversed = new ArrayList<>(list); Collections.reverse(reversed); return reversed; }).build()).build(); assertEquals("ooF", engine.compileMustache("{{reverse}}").render("Foo")); assertEquals("kladivo EDGAR 10", engine.compileMustache("{{translate}} {{name}} {{age}}").render(new Hammer())); assertEquals("bravo:charlie:alpha:", engine.compileMustache("{{#each this.reversed}}{{.}}:{{/each}}") .render(ImmutableList.of("alpha", "charlie", "bravo"))); assertEquals("EDGAR 1000", engine.compileMustache("{{name}} {{age}}") .render(decorate(new Hammer()).put("age", 1000).build(engine))); }
@Test public void testGetDelegate() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addContextConverter(decorate(Hammer.class).compute("name", h -> h.getName().toUpperCase()).build()) .build(); Hammer hammer = new Hammer(); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{delegate.name}}").render(hammer)); } |
### Question:
Strings { public static String replace(String text, String search, String replacement) { if (isEmpty(text) || isEmpty(search) || replacement == null) { return text; } int start = 0; int end = text.indexOf(search, start); if (end == -1) { return text; } StringBuilder builder = new StringBuilder(); while (end != -1) { builder.append(text.substring(start, end)); builder.append(replacement); start = end + search.length(); end = text.indexOf(search, start); } builder.append(text.substring(start)); return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; }### Answer:
@Test public void testReplace() { assertEquals("foobar", Strings.replace("foo:bar", ":", "")); } |
### Question:
LogHelper extends BasicValueHelper { public LogHelper(LoggerAdapter adapter, Level defaultLevel, boolean appendTemplateInfo) { Checker.checkArgumentsNotNull(adapter, defaultLevel); this.defaultLevel = defaultLevel; this.adapter = adapter; this.appendTemplateInfo = appendTemplateInfo; } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); }### Answer:
@Test public void testLogHelper() { String name = "MyLogger"; TestLoggerAdapter adapter = new TestLoggerAdapter(name); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().setDefaultLevel(Level.INFO) .setLoggerAdapter(adapter).build()) .build()) .build(); String msg = "Hello me!"; engine.compileMustache("log_helper1", "{{log \"" + msg + "\" level=\"WARN\"}}").render(null); assertEquals(Level.WARN, adapter.getLevels().get(0)); assertEquals(msg + " [log_helper1:1]", adapter.getMessages().get(0)); assertEquals(adapter.getParameters().get(0).length, 0); msg = "Hello {}!"; engine.compileMustache("log_helper2", "{{log this \"me\"}}") .render(msg); assertEquals(Level.INFO, adapter.getLevels().get(1)); assertEquals(msg + " [log_helper2:1]", adapter.getMessages().get(1)); assertEquals(adapter.getParameters().get(1).length, 1); engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().setAppendTemplateInfo(false) .setDefaultLevel(Level.INFO) .setLoggerAdapter(adapter).build()) .build()) .build(); engine.compileMustache("log_helper3", "{{log \"" + msg + "\"}}") .render(null); assertEquals(Level.INFO, adapter.getLevels().get(2)); assertEquals(msg, adapter.getMessages().get(2)); assertEquals(adapter.getParameters().get(2).length, 0); } |
### Question:
LogHelper extends BasicValueHelper { public static Builder builder() { return new Builder(); } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); }### Answer:
@Test public void testLogHelperValidation() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().build()).build()) .build(); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> engine.compileMustache("log_helper_validation01", "{{#log \"Foo\"}}{{/log}}")) .check(() -> engine.compileMustache("log_helper_validation02", "{{log}}")); } |
### Question:
DecoratorHelper extends BasicSectionHelper { public static <T> Builder<T> decorate(Class<T> delegateType) { return new Builder<>(o -> delegateType.isAssignableFrom(o.getClass())); } private DecoratorHelper(Predicate<Object> test, Map<String, Function<T, Object>> mappings, String delegateKey); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override void execute(Options options); }### Answer:
@SuppressWarnings("unchecked") @Test public void testHelper() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("decorateCat", decorate(Cat.class).put("const", "Cat") .compute("name", cat -> cat.getName().toUpperCase()) .compute("overweight", (cat) -> cat.getWeight() > 4500 ? cat.getWeight() - 4500 : 0).build()) .registerHelper("decorateIntList", decorate(List.class) .compute("sum", l -> l.stream().mapToInt(e -> Integer.valueOf(e.toString())).sum()).build()) .registerHelper("dummy", decorate(String.class).delegateKey("foo").compute("toUpperCase", s -> s.toLowerCase()).build()) .registerHelper("decorateStr", decorate(String.class) .compute("reverse", s -> new StringBuilder(s).reverse().toString()).build()) .build(); assertEquals("ooF", engine.compileMustache("{{#decorateStr}}{{reverse}}{{/decorateStr}}").render("Foo")); List<Cat> cats = new ArrayList<>(); cats.add(new Cat("Mikes", 3000)); cats.add(new Cat("Mourek", 5000)); assertEquals("Cat MIKES [3000g] has overweight 0g.Cat MOUREK [5000g] has overweight 500g.", engine.compileMustache( "{{#each}}{{#decorateCat}}{{const}} {{name}} [{{weight}}g] has overweight {{overweight}}g.{{/decorateCat}}{{/each}}") .render(cats)); try { engine.compileMustache("{{#decorateCat}}{{name}}{{/decorateCat}}").render("foo"); fail(); } catch (IllegalStateException expected) { } assertEquals("6:123", engine.compileMustache("{{#decorateIntList}}{{sum}}:{{#each}}{{.}}{{/each}}{{/decorateIntList}}") .render(Arrays.asList(1, 2, 3))); assertEquals("lu vs LU", engine.compileMustache("{{#dummy}}{{toUpperCase}} vs {{foo.toUpperCase}}{{/dummy}}").render("Lu")); } |
### Question:
EqualsHelper extends BasicSectionHelper { public EqualsHelper() { this(false); } EqualsHelper(); EqualsHelper(boolean testInequality); @Override void execute(Options options); }### Answer:
@Test public void testEqualsHelper() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addGlobalData("archiveType", ArchiveType.class) .registerHelpers(HelpersBuilder.empty().addIsEqual() .addIsNotEqual().build()) .build(); assertEquals("EQUALS", engine.compileMustache("equals_helper1", "{{#isEq this.age this.age}}EQUALS{{/isEq}}") .render(new Hammer())); assertEquals( "EQUALS", engine .compileMustache("equals_helper2", "{{#isEq this}}EQUALS{{/isEq}}") .render(new Hammer())); assertEquals("NOT_EQUALS", engine.compileMustache("equals_helper3", "{{#isNotEq this.age}}NOT_EQUALS{{/isNotEq}}") .render(new Hammer())); assertEquals("NOT_EQUALS", engine.compileMustache("equals_helper4", "{{#isNotEq this.age this.toString}}NOT_EQUALS{{/isNotEq}}") .render(new Hammer())); assertEquals("It's a WAR!", engine .compileMustache("equals_helper5", "{{#with this.archiveType}}" + "{{#isEq archiveType.WAR}}" + "It's a WAR!" + "{{/isEq}}" + "{{#isEq archiveType.EAR}}" + "It's an EAR!" + "{{/isEq}}" + "{{/with}}") .render(new Hammer())); } |
### Question:
InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); static InvokeHelper of(String defaultMethodName); @Override void execute(Options options); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); static final ConfigurationKey METHOD_CACHE_MAX_SIZE_KEY; }### Answer:
@Test public void testHelper() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addInvoke().build()) .build(); List<String> list = ImmutableList.of("foo", "bar", "baz"); Map<String, Object> data = ImmutableMap.of("string", "foo", "list", list); assertEquals("oo", engine .compileMustache("invoke_01", "{{invoke 1 m='substring'}}") .render("foo")); assertEquals("bar", engine.compileMustache("invoke_02", "{{invoke 1 m='get'}}") .render(list)); assertEquals("FOOBARBAZ", engine.compileMustache("invoke_03", "{{#invoke 'list' m='get'}}{{#each this}}{{toUpperCase}}{{/each}}{{/invoke}}") .render(data)); assertEquals("3", engine .compileMustache("invoke_04", "{{invoke on=list m='size'}}") .render(data)); assertEquals( "false", engine .compileMustache("invoke_05", "{{invoke on=list method='isEmpty'}}") .render(data)); assertEquals("boo", engine.compileMustache("invoke_06", "{{invoke 'f' 'b' on='foo' m='replace'}}") .render(null)); assertEquals("2", engine.compileMustache("invoke_07", "{{#invoke ':' on='foo:bar' m='split'}}{{this.length}}{{/invoke}}") .render(null)); }
@Test public void testDefaultMethodName() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("substring", InvokeHelper.of("substring")) .build()) .build(); assertEquals("345", engine .compileMustache("invoke_defmethodname_01", "{{substring 3}}") .render("012345")); assertEquals("lo", engine .compileMustache("invoke_defmethodname_01", "{{substring 3 on='hello' m='whatever'}}") .render(null)); } |
### Question:
NullCheckHelper extends MatchingSectionHelper { public NullCheckHelper() { this(false); } NullCheckHelper(); NullCheckHelper(boolean testNotNull); }### Answer:
@Test public void testNullCheckHelper() { MustacheEngine engine = MustacheEngineBuilder .newBuilder() .registerHelpers( HelpersBuilder.empty() .addIsNull() .addIsNotNull() .build()).build(); assertEquals( "NULL|NOTNULL", engine.compileMustache( "nullcheck_helper1", "{{#isNull this.getNull}}NULL{{/isNull}}|{{#isNotNull this.toString}}NOTNULL{{/isNotNull}}") .render(new Hammer())); assertEquals( "NULL", engine.compileMustache( "nullcheck_helper2", "{{#isNull this.getNull this.null}}NULL{{/isNull}}") .render(new Hammer())); assertEquals( "NULL", engine.compileMustache( "nullcheck_helper3", "{{#isNull this.getNull this.age logic=\"or\"}}NULL{{/isNull}}") .render(new Hammer())); assertEquals( "NOTNULL", engine.compileMustache( "nullcheck_helper3", "{{#isNotNull this.getNull this.age logic=\"or\"}}NOTNULL{{/isNotNull}}") .render(new Hammer())); assertEquals( "ISNULL", engine.compileMustache( "nullcheck_helper4", "{{#isNotNull this.getNull else='ISNULL'}}NOTNULL{{/isNotNull}}") .render(new Hammer())); } |
### Question:
CacheHelper extends BasicSectionHelper { public void invalidateFragments() { if (fragments == null) { return; } fragments.clear(); } @Override void execute(Options options); void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); void invalidateFragments(); void invalidateFragments(final String keyPart); static final ConfigurationKey FRAGMENT_CACHE_MAX_SIZE_KEY; }### Answer:
@Test public void testHelper() throws InterruptedException { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addCache().build()) .build(); CacheHelper cacheHelper = (CacheHelper) engine.getConfiguration() .getHelpers().get(HelpersBuilder.CACHE); final AtomicInteger hits = new AtomicInteger(); Mustache mustache = engine.compileMustache("cache_01", "{{#cache}}{{this.age}}{{/cache}}"); Hammer hammer = new Hammer() { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; assertEquals("10", mustache.render(hammer)); assertEquals("10", mustache.render(hammer)); hammer.setAge(11); assertEquals("10", mustache.render(hammer)); assertEquals(1, hits.get()); cacheHelper.invalidateFragments(); hammer.setAge(1); mustache = engine.compileMustache("cache_02", "{{#cache expire=1 unit='MILLISECONDS'}}{{this.age}}{{/cache}}"); assertEquals("1", mustache.render(hammer)); Thread.sleep(50); hammer.setAge(2); assertEquals("2", mustache.render(hammer)); cacheHelper.invalidateFragments(); hammer.setAge(5); mustache = engine.compileMustache("cache_03", "{{#cache guard=this.age}}{{this.age}}{{/cache}}"); assertEquals("5", mustache.render(hammer)); assertEquals("5", mustache.render(hammer)); hammer.setAge(50); assertEquals("50", mustache.render(hammer)); cacheHelper.invalidateFragments(); mustache = engine.compileMustache("cache_04", "{{#cache key=this.id}}{{this.age}}{{/cache}}"); hammer.setAge(1000); Hammer hammer2 = new Hammer(2000) { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; Hammer hammer3 = new Hammer(3000) { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; assertEquals("1000", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); hammer.setAge(1001); hammer2.setAge(2001); hammer3.setAge(3001); assertEquals("1000", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); cacheHelper.invalidateFragments(hammer.getId()); assertEquals("1001", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); } |
### Question:
HelpersBuilder { public static HelpersBuilder builtin() { return empty().addBuiltin(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); static final String EACH; static final String IF; static final String UNLESS; static final String WITH; static final String IS; static final String IS_EVEN; static final String IS_ODD; static final String SET; static final String INCLUDE; static final String EMBED; static final String IS_EQUAL; static final String IS_NOT_EQUAL; static final String IS_NULL; static final String IS_NOT_NULL; static final String CHOOSE; static final String WHEN; static final String OTHERWISE; static final String SWITCH; static final String CASE; static final String DEFAULT; static final String JOIN; static final String EVAL; static final String NUMERIC_EXPRESSION; static final String ASYNC; static final String INVOKE; static final String ALT; static final String MIN; static final String MAX; static final String CACHE; static final String REPEAT; static final String FMT; static final String TAG; }### Answer:
@Test public void testBuiltin() { Map<String, Helper> helpers = HelpersBuilder.builtin().build(); assertEquals(5, helpers.size()); assertTrue(helpers.containsKey(HelpersBuilder.EACH)); assertTrue(helpers.containsKey(HelpersBuilder.IF)); assertTrue(helpers.containsKey(HelpersBuilder.IS)); assertTrue(helpers.containsKey(HelpersBuilder.UNLESS)); assertTrue(helpers.containsKey(HelpersBuilder.WITH)); } |
### Question:
HelpersBuilder { public static HelpersBuilder extra() { return empty().addExtra(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); static final String EACH; static final String IF; static final String UNLESS; static final String WITH; static final String IS; static final String IS_EVEN; static final String IS_ODD; static final String SET; static final String INCLUDE; static final String EMBED; static final String IS_EQUAL; static final String IS_NOT_EQUAL; static final String IS_NULL; static final String IS_NOT_NULL; static final String CHOOSE; static final String WHEN; static final String OTHERWISE; static final String SWITCH; static final String CASE; static final String DEFAULT; static final String JOIN; static final String EVAL; static final String NUMERIC_EXPRESSION; static final String ASYNC; static final String INVOKE; static final String ALT; static final String MIN; static final String MAX; static final String CACHE; static final String REPEAT; static final String FMT; static final String TAG; }### Answer:
@Test public void testExtra() { Map<String, Helper> helpers = HelpersBuilder.extra().build(); assertEquals(27, helpers.size()); assertTrue(helpers.containsKey(HelpersBuilder.EMBED)); assertTrue(helpers.containsKey(HelpersBuilder.INCLUDE)); assertTrue(helpers.containsKey(HelpersBuilder.IS_EQUAL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NOT_EQUAL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NULL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NOT_NULL)); assertTrue(helpers.containsKey(HelpersBuilder.SET)); assertTrue(helpers.containsKey(HelpersBuilder.IS_EVEN)); assertTrue(helpers.containsKey(HelpersBuilder.IS_ODD)); assertTrue(helpers.containsKey(HelpersBuilder.SWITCH)); assertTrue(helpers.containsKey(HelpersBuilder.CHOOSE)); assertTrue(helpers.containsKey(HelpersBuilder.JOIN)); assertTrue(helpers.containsKey(HelpersBuilder.EVAL)); assertTrue(helpers.containsKey(HelpersBuilder.NUMERIC_EXPRESSION)); assertTrue(helpers.containsKey(HelpersBuilder.ASYNC)); assertTrue(helpers.containsKey(HelpersBuilder.INVOKE)); assertTrue(helpers.containsKey(HelpersBuilder.ALT)); assertTrue(helpers.containsKey(HelpersBuilder.MIN)); assertTrue(helpers.containsKey(HelpersBuilder.MAX)); assertTrue(helpers.containsKey(HelpersBuilder.CACHE)); assertTrue(helpers.containsKey(HelpersBuilder.REPEAT)); assertTrue(helpers.containsKey(HelpersBuilder.FMT)); assertTrue(helpers.containsKey(HelpersBuilder.TAG)); } |
### Question:
Strings { public static boolean containsWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (Character.isWhitespace(text.charAt(i))) { return true; } } return false; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; }### Answer:
@Test public void testContainsWhitespace() { assertTrue(Strings.containsWhitespace("foo bar")); assertTrue(Strings .containsWhitespace(System.getProperty("line.separator"))); assertFalse(Strings.containsWhitespace("foobar")); } |
### Question:
PrettyTimeHelper extends LocaleAwareValueHelper { public static Builder builder() { return new Builder(); } PrettyTimeHelper(); PrettyTimeHelper(PrettyTimeFactory prettyTimeFactory); PrettyTimeHelper(PrettyTimeFactory factory,
Converter<Object, Date> converter); @Override void init(Configuration configuration); @Override void execute(Options options); static Builder builder(); static final String COMPUTING_CACHE_CONSUMER_ID; static final String DEFAULT_NAME; }### Answer:
@Test public void testCustomConverter() { final Calendar day = Calendar.getInstance(); day.set(Calendar.YEAR, day.get(Calendar.YEAR) - 1); day.set(Calendar.MONTH, day.get(Calendar.MONTH) - 1); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setLocaleSupport(FixedLocaleSupport.from(Locale.ENGLISH)) .addResolver(new ThisResolver()) .registerHelper("pretty", PrettyTimeHelper.builder() .setConverter(from -> day.getTime()).build()) .build(); assertEquals("1 year ago", engine.compileMustache("pretty_conv", "{{pretty this}}") .render(Calendar.getInstance())); } |
### Question:
TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); }### Answer:
@Test public void availabilityOfTemplateInDefaultLocation() throws Exception { assertThat(provider.isTemplateAvailable("home", environment, getClass().getClassLoader(), resourceLoader), is(true)); assertThat(provider.isTemplateAvailable("prefix/prefixed", environment, getClass().getClassLoader(), resourceLoader), is(true)); }
@Test public void availabilityOfTemplateThatDoesNotExist() throws Exception { assertThat(provider.isTemplateAvailable("unknown", environment, getClass().getClassLoader(), resourceLoader), is(false)); }
@Test public void availabilityOfTemplateWithCustomPrefix() throws Exception { environment.setProperty("trimou.prefix", "classpath:/custom-templates/"); assertThat(provider.isTemplateAvailable("custom", environment, getClass().getClassLoader(), resourceLoader), is(true)); }
@Test public void availabilityOfTemplateWithCustomSuffix() throws Exception { environment.setProperty("trimou.suffix", ".html"); assertThat(provider.isTemplateAvailable("suffixed", environment, getClass().getClassLoader(), resourceLoader), is(true)); } |
### Question:
HttpServletRequestResolver extends AbstractResolver implements MustacheListener, Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject != null) { return null; } if (NAME_REQUEST.equals(name)) { HttpServletRequestWrapper wrapper = REQUEST_WRAPPER.get(); if (wrapper == null) { HttpServletRequest request = RequestHolder.getCurrentRequest(); if (request != null) { wrapper = new HttpServletRequestWrapper(request); REQUEST_WRAPPER.set(wrapper); } else { LOGGER.warn("Unable to get the current HTTP request"); } } return wrapper; } return null; } HttpServletRequestResolver(); HttpServletRequestResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void renderingStarted(MustacheRenderingEvent event); @Override boolean isValid(); static final int SERVLET_REQUEST_RESOLVER_PRIORITY; static final ConfigurationKey ENABLED_KEY; }### Answer:
@Test public void testNulltIsResolved() { HttpServletRequestResolver resolver = new HttpServletRequestResolver(); assertNull(resolver.resolve("whatever", "request", null)); assertNull(resolver.resolve(null, "foo", null)); } |
### Question:
JsonElementResolver extends IndexResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonElement)) { return null; } JsonElement element = (JsonElement) contextObject; if (element.isJsonArray() && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) element; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonElementIfNecessary(jsonArray.get(index), unwrapJsonPrimitive); } } else if (element.isJsonObject()) { JsonObject jsonObject = (JsonObject) element; JsonElement member = jsonObject.get(name); if (member != null) { return unwrapJsonElementIfNecessary(member, unwrapJsonPrimitive); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonElementIfNecessary(element, true); } return null; } JsonElementResolver(); JsonElementResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); static final int JSON_ELEMENT_RESOLVER_PRIORITY; static final String NAME_UNWRAP_THIS; static final ConfigurationKey UNWRAP_JSON_PRIMITIVE_KEY; }### Answer:
@Test public void testResolution() { JsonElementResolver resolver = new JsonElementResolver(); ResolutionContext ctx = new DummyResolutionContext(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setProperty(JsonElementResolver.UNWRAP_JSON_PRIMITIVE_KEY, true) .setProperty(GsonValueConverter.ENABLED_KEY, false) .addResolver(resolver).build(); assertNull(resolver.resolve(null, "foo", ctx)); assertNull(resolver.resolve("bar", "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(new JsonPrimitive(true), "unwrapThis", ctx)); assertNull(resolver.resolve(new JsonPrimitive(true), "whatever", ctx)); assertEquals(Placeholder.NULL, resolver.resolve(JsonNull.INSTANCE, "unwrapThis", ctx)); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("foo", "bar"); jsonObject.addProperty("baz", true); assertEquals("bar", resolver.resolve(jsonObject, "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(jsonObject, "baz", ctx)); JsonArray jsonArray = new JsonArray(); jsonArray.add(new JsonPrimitive(true)); jsonArray.add(new JsonPrimitive(1)); assertEquals(true, resolver.resolve(jsonArray, "0", ctx)); assertEquals(1, resolver.resolve(jsonArray, "1", ctx)); } |
### Question:
JsonValueResolver extends IndexResolver implements Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonValue)) { return null; } JsonValue jsonValue = (JsonValue) contextObject; if (ValueType.ARRAY.equals(jsonValue.getValueType()) && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) jsonValue; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonValueIfNecessary(jsonArray.get(index)); } } else if (ValueType.OBJECT.equals(jsonValue.getValueType())) { JsonObject jsonObject = (JsonObject) jsonValue; JsonValue member = jsonObject.get(name); if (member != null) { return unwrapJsonValueIfNecessary(member); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonValueIfNecessary(jsonValue); } return null; } JsonValueResolver(); JsonValueResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(Configuration configuration); @Override Set<ConfigurationKey> getConfigurationKeys(); static final int JSON_VALUE_RESOLVER_PRIORITY; static final ConfigurationKey ENABLED_KEY; static final String NAME_UNWRAP_THIS; }### Answer:
@Test public void testResolution() { JsonValueResolver resolver = new JsonValueResolver(); ResolutionContext ctx = new DummyResolutionContext(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver) .setProperty(JsonValueResolver.ENABLED_KEY, true).build(); assertNull(resolver.resolve(null, "foo", ctx)); assertNull(resolver.resolve("bar", "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(JsonValue.TRUE, "unwrapThis", ctx)); assertNull(resolver.resolve(JsonValue.TRUE, "whatever", ctx)); assertEquals(Placeholder.NULL, resolver.resolve(JsonValue.NULL, "unwrapThis", ctx)); JsonObject jsonObject = Json.createObjectBuilder().add("foo", "bar") .add("baz", true).build(); assertEquals("bar", resolver.resolve(jsonObject, "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(jsonObject, "baz", ctx)); JsonArray jsonArray = Json.createArrayBuilder().add(true).add(1) .build(); assertEquals(true, resolver.resolve(jsonArray, "0", ctx)); assertEquals(BigDecimal.ONE, resolver.resolve(jsonArray, "1", ctx)); } |
### Question:
SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); static final String DEFAULT_PREFIX; static final String DEFAULT_SUFFIX; }### Answer:
@Test public void availabilityOfTemplateInDefaultLocation() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(); final Reader r1 = loader.locate("home"); assertThat(readContent(r1), is("home")); final Reader r2 = loader.locate("prefix/prefixed"); assertThat(readContent(r2), is("prefixed")); }
@Test public void availabilityOfTemplateThatDoesNotExist() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(); assertThat(loader.locate("unknown"), is(nullValue())); }
@Test public void availabilityOfTemplateWithCustomPrefix() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(1, "classpath:/custom-templates/", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final Reader reader = loader.locate("custom"); assertThat(readContent(reader), is("custom")); }
@Test public void availabilityOfTemplateWithCustomSuffix() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(1, SpringResourceTemplateLocator.DEFAULT_PREFIX, ".html"); final Reader reader = loader.locate("suffixed"); assertThat(readContent(reader), is("suffixed")); } |
### Question:
Strings { public static boolean containsOnlyWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isWhitespace(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; }### Answer:
@Test public void testContainsOnlyWhitespace() { assertTrue(Strings.containsOnlyWhitespace(" ")); assertTrue(Strings.containsOnlyWhitespace( " " + System.getProperty("line.separator"))); assertFalse(Strings.containsOnlyWhitespace(" !")); } |
### Question:
TrimouViewResolver extends AbstractTemplateViewResolver { @Override public boolean isCache() { return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED) && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE) && super.isCache(); } TrimouViewResolver(); TrimouViewResolver(final MustacheEngine engine); @Override boolean isCache(); void setEngine(final MustacheEngine engine); @Override void setPrefix(final String prefix); @Override void setSuffix(final String suffix); }### Answer:
@Test public void cacheEnabled() throws Exception { assertThat(resolver.isCache(), is(true)); } |
### Question:
Strings { public static boolean containsOnlyDigits(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; }### Answer:
@Test public void testContainsOnlyDigits() { assertTrue(Strings.containsOnlyDigits("123")); assertFalse(Strings.containsOnlyDigits("5!")); } |
### Question:
Strings { public static String repeat(String text, int times, String separator) { if (isEmpty(text) || times < 0) { return text; } if (times == 0) { return EMPTY; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(text); if (i + 1 < times) { builder.append(separator); } } return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; }### Answer:
@Test public void testRepeat() { assertEquals("foo,foo", Strings.repeat("foo", 2, ",")); assertEquals("ooo", Strings.repeat("o", 3, "")); assertEquals("o", Strings.repeat("o", -3, "")); assertEquals("", Strings.repeat("ouch", 0, "")); } |
### Question:
Strings { public static String substringAfter(String text, String delimiter) { Checker.checkArgumentsNotNull(text, delimiter); int index = text.indexOf(delimiter); if (index == -1) { return EMPTY; } return text.substring(index + delimiter.length()); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; }### Answer:
@Test public void testSubstringAfter() { assertEquals("o", Strings.substringAfter("foo", "o")); assertEquals("", Strings.substringAfter("foo", "a")); } |
### Question:
Arrays { public static boolean contains(Object[] array, Object object) { if (array == null) { return false; } for (final Object element : array) { if ((object != null && object.equals(element)) || (object == null && element == null)) { return true; } } return false; } static boolean contains(Object[] array, Object object); static final Object[] EMPTY_OBJECT_ARRAY; }### Answer:
@Test public void testContains() { assertTrue(Arrays.contains(new Character[] { 'v', 'o', 'j', 't', 'a' }, 'a')); assertFalse( Arrays.contains(new Character[] { 'j', 'a', 's', 'a' }, null)); assertTrue(Arrays.contains(new Character[] { 'l', null }, null)); } |
### Question:
HelloWorld implements ActionBlock { public int execute(FlowContext ctx) throws FlowExecutionException { String name = (String) ctx.get(IN_NAME); String message = "Hello World! "; if (name != null) { message += name; } logger.debug("Message: {}", message); ctx.put(OUT_MESSAGE, message); return NEXT; } int execute(FlowContext ctx); }### Answer:
@Test public void testHelloWorld(){ HelloWorld helloWorld = new HelloWorld(); FlowContext context = new FlowContext(); context.put("name", "John"); try { int result = helloWorld.execute(context); context.get("message"); assertEquals(ActionBlock.NEXT, result); assertEquals("Hello World! John", context.get("message")); } catch (FlowExecutionException e) { e.printStackTrace(); } } |
### Question:
Vehicle { protected double getSpeedMph(double timeSec){ double v = 2.0*this.engine.getHorsePower()*746; v = v*timeSec*32.174/this.weightPounds; return Math.round(Math.sqrt(v)*0.68); } Vehicle(int weightPounds, Engine engine); int getWeightPounds(); Engine getEngine(); }### Answer:
@Test public void testGetSpeedMph(){ double timeSec = 10.0; int engineHorsePower = 246; int vehicleWeightPounds = 4000; Engine engine = new Engine(); engine.setHorsePower(engineHorsePower); Vehicle vehicle = new Vehicle(vehicleWeightPounds, engine); double speed = vehicle.getSpeedMph(timeSec); assertEquals("Assert vehicle (" + engineHorsePower + " hp, " + vehicleWeightPounds + " lb) speed in " + timeSec + " sec: ", 117, speed, 0.001 * speed); } |
### Question:
TrafficDensity3 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); }### Answer:
@Test public void testCalcSpeed(){ double timeSec = 10.0; TrafficDensity3 trafficDensity = new TrafficDensity3(); Vehicle vehicle = Mockito.mock(Vehicle.class); Mockito.when(vehicle.getSpeedMph(timeSec)).thenReturn(100d); double traction = 0.2; double speed = trafficDensity.calcSpeed(vehicle, traction, timeSec); assertEquals("Assert speed (traction=" + traction + ") in " + timeSec + " sec: ", 20, speed, 0.001 * speed); } |
### Question:
TrafficDensity3 { protected int calcLaneNumber(int lanesCount, double[] speedLimitByLane, double speed){ for(int i = 1; i <= lanesCount; i++){ if(speed <= speedLimitByLane[i - 1]){ return i; } } return lanesCount; } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); }### Answer:
@Test public void testCalcLaneNumber() { double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; double[] speedLimitByLane = {4.5, 8.5, 12.5}; int[] expectedLaneNumber = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}; TrafficDensityTestCalcLaneNumber trafficDensity = new TrafficDensityTestCalcLaneNumber(); for(int i = 0; i < speeds.length; i++){ int ln = trafficDensity.calcLaneNumber(speedLimitByLane.length, speedLimitByLane, speeds[i]); assertEquals("Assert lane number of speed " + speeds + " with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedLaneNumber[i], ln); } } |
### Question:
TrafficDensity3 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = new HashMap<>(); for(int i = 1; i <= lanesCount; i++){ trafficByLane.put(i, 0); } stream.limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> calcSpeed(tuw.getVehicle(), tuw.getTraction(), timeSec)) .forEach(speed -> trafficByLane.computeIfPresent(calcLaneNumber(lanesCount, speedLimitByLane, speed), (k, v) -> ++v)); return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); }### Answer:
@Test public void testCalcLaneNumber2() { int[] count ={0}; double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; Integer[] expectedCountByLane = {4, 4, 4}; TrafficDensity3 trafficDensity = new TrafficDensity3(){ @Override protected double calcSpeed(Vehicle vehicle, double traction, double timeSec) { return speeds[count[0]++]; } }; double timeSec = 10.0; int trafficUnitsNumber = speeds.length; double[] speedLimitByLane = {4.5, 8.5, 12.5}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + speeds.length + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } |
### Question:
TrafficDensity2 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); }### Answer:
@Test public void testCalcSpeed(){ double timeSec = 10.0; TrafficDensity2 trafficDensity = new TrafficDensity2(); Vehicle vehicle = Mockito.mock(Vehicle.class); Mockito.when(vehicle.getSpeedMph(timeSec)).thenReturn(100d); double traction = 0.2; double speed = trafficDensity.calcSpeed(vehicle, traction, timeSec); assertEquals("Assert speed (traction=" + traction + ") in " + timeSec + " sec: ", 20, speed, 0.001 * speed); } |
### Question:
TrafficDensity2 { private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){ for(int i = 1; i <= lanesNumber; i++){ if(speed <= speedLimit[i - 1]){ return new CountByLane(1, i); } } return new CountByLane(1, lanesNumber); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); }### Answer:
@Test public void testCountByLane() { int[] count ={0}; double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; TrafficDensity2 trafficDensity = new TrafficDensity2(){ @Override protected double calcSpeed(Vehicle vehicle, double traction, double timeSec) { return speeds[count[0]++]; } }; double timeSec = 10.0; int trafficUnitsNumber = speeds.length; double[] speedLimitByLane = {4.5, 8.5, 12.5}; Integer[] expectedCountByLane = {4, 4, 4}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + speeds.length + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } |
### Question:
TrafficDensity1 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = stream .limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> tuw.calcSpeed(timeSec)) .map(speed -> countByLane(lanesCount, speedLimitByLane, speed)) .collect(Collectors.groupingBy(CountByLane::getLane, Collectors.summingInt(CountByLane::getCount))); for(int i = 1; i <= lanesCount; i++){ trafficByLane.putIfAbsent(i, 0); } return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); }### Answer:
@Test public void testTrafficByLane() { TrafficDensity1 trafficDensity = new TrafficDensity1(); double timeSec = 10.0; int trafficUnitsNumber = 120; double[] speedLimitByLane = {30, 50, 65}; Integer[] expectedCountByLane = {30, 30, 60}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream2(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + trafficUnitsNumber + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } |
### Question:
Asn1Buffer { public void put( byte b ) { if ( pos == buffer.length ) { extend( 1 ); } pos++; buffer[buffer.length - pos] = b; } Asn1Buffer(); int getPos(); void setPos( int pos ); void put( byte b ); void put( byte[] bytes ); ByteBuffer getBytes(); int getSize(); void clear(); @Override String toString(); }### Answer:
@Test @Disabled public void testBytesPerf() { long t0 = System.currentTimeMillis(); for ( int j = 0; j < 1000; j++ ) { Asn1Buffer buffer = new Asn1Buffer(); for ( int i = 0; i < 409600; i++ ) { buffer.put( new byte[] { 0x01, ( byte ) i } ); } } long t1 = System.currentTimeMillis(); System.out.println( "Delta: " + ( t1 - t0 ) ); } |
### Question:
MaxValueCountItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxValueCountItem ) { MaxValueCountItem that = ( MaxValueCountItem ) o; return items.equals( that.items ); } return false; } MaxValueCountItem( Set<MaxValueCountElem> items ); Iterator<MaxValueCountElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( maxValueCountItemA.equals( maxValueCountItemC ) ); assertFalse( maxValueCountItemC.equals( maxValueCountItemA ) ); assertFalse( maxValueCountItemA.equals( maxValueCountItemD ) ); assertFalse( maxValueCountItemD.equals( maxValueCountItemA ) ); }
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( maxValueCountItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( maxValueCountItemA.equals( null ) ); } |
### Question:
RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( restrictedByItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( restrictedByItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( restrictedByItemA.equals( restrictedByItemC ) ); assertFalse( restrictedByItemC.equals( restrictedByItemA ) ); assertFalse( restrictedByItemA.equals( restrictedByItemD ) ); assertFalse( restrictedByItemD.equals( restrictedByItemA ) ); } |
### Question:
RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testHashCodeReflexive() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemACopy.hashCode() ); assertEquals( restrictedByItemACopy.hashCode(), restrictedByItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemACopy.hashCode() ); assertEquals( restrictedByItemACopy.hashCode(), restrictedByItemB.hashCode() ); assertEquals( restrictedByItemA.hashCode(), restrictedByItemB.hashCode() ); } |
### Question:
AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( attributeValueItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( attributeValueItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( attributeValueItemA.equals( attributeValueItemC ) ); assertFalse( attributeValueItemC.equals( attributeValueItemA ) ); assertFalse( attributeValueItemA.equals( attributeValueItemD ) ); assertFalse( attributeValueItemD.equals( attributeValueItemA ) ); } |
### Question:
AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testHashCodeReflexive() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemACopy.hashCode() ); assertEquals( attributeValueItemACopy.hashCode(), attributeValueItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemACopy.hashCode() ); assertEquals( attributeValueItemACopy.hashCode(), attributeValueItemB.hashCode() ); assertEquals( attributeValueItemA.hashCode(), attributeValueItemB.hashCode() ); } |
### Question:
ClassesItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof ClassesItem ) { ClassesItem that = ( ClassesItem ) o; if ( classes == null ) { return that.classes == null; } return classes.equals( that.classes ); } return false; } ClassesItem( ExprNode classes ); ExprNode getClasses(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( classesItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( classesItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( classesItemA.equals( classesItemC ) ); assertFalse( classesItemC.equals( classesItemA ) ); } |
### Question:
ClassesItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( classes != null ) { hash = hash * 17 + classes.hashCode(); } else { hash = hash * 17 + getClass().getName().hashCode(); } return hash; } ClassesItem( ExprNode classes ); ExprNode getClasses(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testHashCodeReflexive() throws Exception { assertEquals( classesItemA.hashCode(), classesItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( classesItemA.hashCode(), classesItemACopy.hashCode() ); assertEquals( classesItemACopy.hashCode(), classesItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( classesItemA.hashCode(), classesItemACopy.hashCode() ); assertEquals( classesItemACopy.hashCode(), classesItemB.hashCode() ); assertEquals( classesItemA.hashCode(), classesItemB.hashCode() ); } |
### Question:
MaxImmSubItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxImmSubItem ) { MaxImmSubItem that = ( MaxImmSubItem ) o; return this.value == that.value; } return false; } MaxImmSubItem( int value ); int getValue(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( maxImmSubItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( maxImmSubItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( maxImmSubItemA.equals( maxImmSubItemC ) ); assertFalse( maxImmSubItemC.equals( maxImmSubItemA ) ); } |
### Question:
MaxImmSubItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; hash = hash * 17 + value; return hash; } MaxImmSubItem( int value ); int getValue(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); }### Answer:
@Test public void testHashCodeReflexive() throws Exception { assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemACopy.hashCode() ); assertEquals( maxImmSubItemACopy.hashCode(), maxImmSubItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemACopy.hashCode() ); assertEquals( maxImmSubItemACopy.hashCode(), maxImmSubItemB.hashCode() ); assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemB.hashCode() ); } |
### Question:
LdapTlsHandshakeException extends LdapException { @Override public String getMessage() { String message = super.getMessage(); message += ", reason: " + failCause.getReasonPhrase(); Throwable rootCause = failCause.getRootCause(); if ( rootCause != null && rootCause != this ) { message += ": " + rootCause.getMessage(); } return message; } LdapTlsHandshakeException( String message, Throwable cause ); LdapTlsHandshakeFailCause getFailCause(); @Override String getMessage(); }### Answer:
@Test public void testClassifyNull() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", null ); assertThat( e.getMessage(), equalTo( "msg, reason: Unspecified" ) ); }
@Test public void testClassifyOther() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new IOException( "foo" ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Unspecified: foo" ) ); }
@Test public void testClassifyCertificateExpiredException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new CertificateExpiredException( "foo" ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Certificate expired: foo" ) ); }
@Test public void testClassifyCertificateNotYetValidException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new CertificateNotYetValidException( "foo" ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Certificate not yet valid: foo" ) ); }
@Test public void testClassifyCertPathBuilderException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new Exception( new CertPathBuilderException( "foo" ) ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Failed to build certification path: foo" ) ); }
@Test public void testClassifyCertPathValidatorException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new Exception( new Exception( new Exception( new Exception( new CertPathValidatorException( "foo", null, null, -1, BasicReason.ALGORITHM_CONSTRAINED ) ) ) ) ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Failed to verify certification path: foo" ) ); } |
### Question:
LdapTlsHandshakeExceptionClassifier { public static LdapTlsHandshakeFailCause classify( Throwable cause ) { return classify( cause, null ); } private LdapTlsHandshakeExceptionClassifier(); static LdapTlsHandshakeFailCause classify( Throwable cause ); static LdapTlsHandshakeFailCause classify( Throwable cause, X509Certificate certificate ); }### Answer:
@Test public void testClassifyNull() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier.classify( null ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.UNSPECIFIED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Unspecified" ) ); assertThat( classification.getRootCause(), equalTo( null ) ); }
@Test public void testClassifyOther() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new IOException( "foo" ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.UNSPECIFIED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Unspecified" ) ); assertThat( classification.getRootCause(), instanceOf( IOException.class ) ); }
@Test public void testClassifyCertificateExpiredException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new CertificateExpiredException( "foo" ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.EXPIRED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Certificate expired" ) ); assertThat( classification.getRootCause(), instanceOf( CertificateExpiredException.class ) ); }
@Test public void testClassifyCertificateNotYetValidException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new CertificateNotYetValidException( "foo" ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.NOT_YET_VALID ) ); assertThat( classification.getReasonPhrase(), equalTo( "Certificate not yet valid" ) ); assertThat( classification.getRootCause(), instanceOf( CertificateNotYetValidException.class ) ); }
@Test public void testClassifyCertPathBuilderException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new Exception( new CertPathBuilderException( "foo" ) ) ); assertThat( classification.getReason(), equalTo( ( Reason ) LdapApiReason.NO_VALID_CERTIFICATION_PATH ) ); assertThat( classification.getReasonPhrase(), equalTo( "Failed to build certification path" ) ); assertThat( classification.getRootCause(), instanceOf( CertPathBuilderException.class ) ); }
@Test public void testClassifyCertPathValidatorException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier.classify( new Exception( new Exception( new Exception( new Exception( new CertPathValidatorException( "foo", null, null, -1, BasicReason.ALGORITHM_CONSTRAINED ) ) ) ) ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.ALGORITHM_CONSTRAINED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Failed to verify certification path" ) ); assertThat( classification.getRootCause(), instanceOf( CertPathValidatorException.class ) ); } |
### Question:
SearchResultEntryImpl extends AbstractResponse implements SearchResultEntry { @Override public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( !super.equals( obj ) ) { return false; } if ( !( obj instanceof SearchResultEntry ) ) { return false; } SearchResultEntry resp = ( SearchResultEntry ) obj; return entry.equals( resp.getEntry() ); } SearchResultEntryImpl(); SearchResultEntryImpl( final int id ); @Override Entry getEntry(); @Override void setEntry( Entry entry ); @Override Dn getObjectName(); @Override void setObjectName( Dn objectName ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testEqualsSameObject() { SearchResultEntryImpl resp = new SearchResultEntryImpl( 5 ); assertTrue( resp.equals( resp ), "the same object should be equal" ); } |
### Question:
SearchResultEntryImpl extends AbstractResponse implements SearchResultEntry { @Override public int hashCode() { int hash = 37; if ( entry != null ) { hash = hash * 17 + entry.hashCode(); } hash = hash * 17 + super.hashCode(); return hash; } SearchResultEntryImpl(); SearchResultEntryImpl( final int id ); @Override Entry getEntry(); @Override void setEntry( Entry entry ); @Override Dn getObjectName(); @Override void setObjectName( Dn objectName ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testHashCodeSameObject() { SearchResultEntryImpl resp = new SearchResultEntryImpl( 5 ); assertTrue( resp.hashCode() == resp.hashCode() ); } |
### Question:
ModifyRequestImpl extends AbstractAbandonableRequest implements ModifyRequest { @Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !super.equals( obj ) ) { return false; } ModifyRequest req = ( ModifyRequest ) obj; if ( name != null && req.getName() == null ) { return false; } if ( name == null && req.getName() != null ) { return false; } if ( name != null && req.getName() != null && !name.equals( req.getName() ) ) { return false; } if ( req.getModifications().size() != mods.size() ) { return false; } Iterator<Modification> list = req.getModifications().iterator(); for ( int i = 0; i < mods.size(); i++ ) { Modification item = list.next(); if ( item == null ) { if ( mods.get( i ) != null ) { return false; } } else if ( !item.equals( mods.get( i ) ) ) { return false; } } return true; } ModifyRequestImpl(); @Override Collection<Modification> getModifications(); @Override Dn getName(); @Override ModifyRequest setName( Dn name ); @Override ModifyRequest addModification( Modification mod ); @Override ModifyRequest addModification( Attribute attr, ModificationOperation modOp ); @Override ModifyRequest add( String attributeName, String... attributeValue ); ModifyRequest add( String attributeName, byte[]... attributeValue ); @Override ModifyRequest add( Attribute attr ); @Override ModifyRequest replace( String attributeName ); @Override ModifyRequest replace( String attributeName, String... attributeValue ); ModifyRequest replace( String attributeName, byte[]... attributeValue ); @Override ModifyRequest replace( Attribute attr ); @Override ModifyRequest removeModification( Modification mod ); @Override ModifyRequest remove( String attributeName, String... attributeValue ); ModifyRequest remove( String attributeName, byte[]... attributeValue ); @Override ModifyRequest remove( Attribute attr ); @Override ModifyRequest remove( String attributeName ); @Override ModifyRequest increment( String attributeName ); @Override ModifyRequest increment( String attributeName, int increment ); @Override ModifyRequest increment( Attribute attr ); @Override ModifyRequest increment( Attribute attr, int increment ); @Override ModifyRequest setMessageId( int messageId ); @Override ModifyRequest addControl( Control control ); @Override ModifyRequest addAllControls( Control[] controls ); @Override ModifyRequest removeControl( Control control ); @Override MessageTypeEnum getResponseType(); @Override ModifyResponse getResultResponse(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testEqualsSameObj() throws LdapException { ModifyRequestImpl req = getRequest(); assertTrue( req.equals( req ) ); }
@Test public void testEqualsExactCopy() throws LdapException { ModifyRequestImpl req0 = getRequest(); ModifyRequestImpl req1 = getRequest(); assertTrue( req0.equals( req1 ) ); } |
### Question:
ModifyRequestImpl extends AbstractAbandonableRequest implements ModifyRequest { @Override public int hashCode() { int hash = 37; if ( name != null ) { hash = hash * 17 + name.hashCode(); } hash = hash * 17 + mods.size(); for ( int i = 0; i < mods.size(); i++ ) { hash = hash * 17 + ( ( DefaultModification ) mods.get( i ) ).hashCode(); } hash = hash * 17 + super.hashCode(); return hash; } ModifyRequestImpl(); @Override Collection<Modification> getModifications(); @Override Dn getName(); @Override ModifyRequest setName( Dn name ); @Override ModifyRequest addModification( Modification mod ); @Override ModifyRequest addModification( Attribute attr, ModificationOperation modOp ); @Override ModifyRequest add( String attributeName, String... attributeValue ); ModifyRequest add( String attributeName, byte[]... attributeValue ); @Override ModifyRequest add( Attribute attr ); @Override ModifyRequest replace( String attributeName ); @Override ModifyRequest replace( String attributeName, String... attributeValue ); ModifyRequest replace( String attributeName, byte[]... attributeValue ); @Override ModifyRequest replace( Attribute attr ); @Override ModifyRequest removeModification( Modification mod ); @Override ModifyRequest remove( String attributeName, String... attributeValue ); ModifyRequest remove( String attributeName, byte[]... attributeValue ); @Override ModifyRequest remove( Attribute attr ); @Override ModifyRequest remove( String attributeName ); @Override ModifyRequest increment( String attributeName ); @Override ModifyRequest increment( String attributeName, int increment ); @Override ModifyRequest increment( Attribute attr ); @Override ModifyRequest increment( Attribute attr, int increment ); @Override ModifyRequest setMessageId( int messageId ); @Override ModifyRequest addControl( Control control ); @Override ModifyRequest addAllControls( Control[] controls ); @Override ModifyRequest removeControl( Control control ); @Override MessageTypeEnum getResponseType(); @Override ModifyResponse getResultResponse(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testHashCodeSameObj() throws LdapException { ModifyRequestImpl req = getRequest(); assertTrue( req.hashCode() == req.hashCode() ); }
@Test public void testHashCodeExactCopy() throws LdapException { ModifyRequestImpl req0 = getRequest(); ModifyRequestImpl req1 = getRequest(); assertTrue( req0.hashCode() == req1.hashCode() ); } |
### Question:
OpaqueExtendedResponse extends AbstractExtendedResponse { @Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !super.equals( obj ) ) { return false; } if ( !( obj instanceof OpaqueExtendedResponse ) ) { return false; } OpaqueExtendedResponse extendedRequest = ( OpaqueExtendedResponse ) obj; if ( ( ( responseName != null ) && !responseName.equals( extendedRequest.responseName ) ) || ( ( responseName == null ) && ( extendedRequest.responseName != null ) ) ) { return false; } return Arrays.equals( responseValue, extendedRequest.responseValue ); } OpaqueExtendedResponse(); OpaqueExtendedResponse( int messageId ); OpaqueExtendedResponse( String responseName ); OpaqueExtendedResponse( int messageId, String responseName ); byte[] getResponseValue(); void setResponseValue( byte[] responseValue ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testEqualsSameObj() { ExtendedResponse resp = createStub(); assertTrue( resp.equals( resp ) ); }
@Test public void testEqualsExactCopy() { ExtendedResponse resp0 = createStub(); ExtendedResponse resp1 = createStub(); assertTrue( resp0.equals( resp1 ) ); assertTrue( resp1.equals( resp0 ) ); }
@Test public void testEqualsDiffImpl() throws LdapInvalidDnException { ExtendedResponse resp0 = createStub(); ExtendedResponse resp1 = new OpaqueExtendedResponse( 45, "1.1.1.1" ); resp1.getLdapResult().setMatchedDn( new Dn( "dc=example,dc=com" ) ); resp1.getLdapResult().setResultCode( ResultCodeEnum.SUCCESS ); ReferralImpl refs = new ReferralImpl(); refs.addLdapUrl( "ldap: refs.addLdapUrl( "ldap: refs.addLdapUrl( "ldap: resp1.getLdapResult().setReferral( refs ); assertTrue( resp0.equals( resp1 ) ); assertTrue( resp1.equals( resp0 ) ); }
@Test public void testNotEqualsDiffIds() { ExtendedResponse resp0 = new OpaqueExtendedResponse( 3 ); ExtendedResponse resp1 = new OpaqueExtendedResponse( 4 ); assertFalse( resp0.equals( resp1 ) ); assertFalse( resp1.equals( resp0 ) ); }
@Test public void testNotEqualsDiffNames() { ExtendedResponse resp0 = createStub(); resp0.setResponseName( "1.2.3.4" ); ExtendedResponse resp1 = createStub(); resp1.setResponseName( "1.2.3.4.5" ); assertFalse( resp0.equals( resp1 ) ); assertFalse( resp1.equals( resp0 ) ); } |
### Question:
OpaqueExtendedResponse extends AbstractExtendedResponse { @Override public int hashCode() { int hash = 37; hash = hash * 17 + super.hashCode(); if ( responseName != null ) { hash = hash * 17 + responseName.hashCode(); } if ( responseValue != null ) { for ( byte b : responseValue ) { hash = hash * 17 + b; } } return hash; } OpaqueExtendedResponse(); OpaqueExtendedResponse( int messageId ); OpaqueExtendedResponse( String responseName ); OpaqueExtendedResponse( int messageId, String responseName ); byte[] getResponseValue(); void setResponseValue( byte[] responseValue ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testHashCodeSameObj() { ExtendedResponse resp = createStub(); assertTrue( resp.hashCode() == resp.hashCode() ); }
@Test public void testHashCodeExactCopy() { ExtendedResponse resp0 = createStub(); ExtendedResponse resp1 = createStub(); assertTrue( resp0.hashCode() == resp1.hashCode() ); } |
### Question:
ReferralImpl implements Referral { @Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( obj instanceof Referral ) { Collection<String> refs = ( ( Referral ) obj ).getLdapUrls(); if ( refs.size() != urls.size() ) { return false; } Iterator<String> list = urls.iterator(); while ( list.hasNext() ) { if ( !refs.contains( list.next() ) ) { return false; } } return true; } return false; } @Override int getReferralLength(); @Override void setReferralLength( int referralLength ); @Override Collection<String> getLdapUrls(); @Override Collection<byte[]> getLdapUrlsBytes(); @Override void addLdapUrl( String url ); @Override void addLdapUrlBytes( byte[] urlBytes ); @Override void removeLdapUrl( String url ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testEqualsSameObject() { ReferralImpl refs = new ReferralImpl(); assertTrue( refs.equals( refs ), "equals method should work for the same object" ); }
@Test public void testEqualsDifferentImpls() { Referral refs0 = new Referral() { public Collection<String> getLdapUrls() { return Collections.emptyList(); } public void addLdapUrl( String url ) { } public void removeLdapUrl( String url ) { } public void addLdapUrlBytes( byte[] urlBytes ) { } public Collection<byte[]> getLdapUrlsBytes() { return null; } public int getReferralLength() { return 0; } public void setReferralLength( int referralLength ) { } }; ReferralImpl refs1 = new ReferralImpl(); assertFalse( refs0.equals( refs1 ), "Object.equals() in effect because we did not redefine equals for the new impl above" ); assertTrue( refs1.equals( refs0 ), "Empty Referrals should be equal even if they are different implementation classes" ); } |
### Question:
ReferralImpl implements Referral { @Override public int hashCode() { int hash = 37; hash = hash * 17 + urls.size(); for ( String url : urls ) { hash = hash + url.hashCode(); } return hash; } @Override int getReferralLength(); @Override void setReferralLength( int referralLength ); @Override Collection<String> getLdapUrls(); @Override Collection<byte[]> getLdapUrlsBytes(); @Override void addLdapUrl( String url ); @Override void addLdapUrlBytes( byte[] urlBytes ); @Override void removeLdapUrl( String url ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testHashCodeSameObject() { ReferralImpl refs = new ReferralImpl(); assertTrue( refs.hashCode() == refs.hashCode() ); } |
### Question:
BindResponseImpl extends AbstractResultResponse implements BindResponse { @Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !( obj instanceof BindResponse ) ) { return false; } if ( !super.equals( obj ) ) { return false; } BindResponse response = ( BindResponse ) obj; byte[] creds = response.getServerSaslCreds(); if ( serverSaslCreds == null ) { if ( creds != null ) { return false; } } else if ( creds == null ) { return false; } return Arrays.equals( serverSaslCreds, creds ); } BindResponseImpl(); BindResponseImpl( final int id ); @Override byte[] getServerSaslCreds(); @Override void setServerSaslCreds( byte[] serverSaslCreds ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testEqualsSameObj() { BindResponseImpl resp = new BindResponseImpl( 1 ); assertTrue( resp.equals( resp ), "same object should be equal" ); }
@Test public void testEqualsNewWithSameId() { BindResponseImpl resp0 = new BindResponseImpl( 1 ); BindResponseImpl resp1 = new BindResponseImpl( 1 ); assertTrue( resp0.equals( resp1 ), "default copy with same id should be equal" ); assertTrue( resp1.equals( resp0 ), "default copy with same id should be equal" ); }
@Test public void testNotEqualsNewWithDiffId() { BindResponseImpl resp0 = new BindResponseImpl( 1 ); BindResponseImpl resp1 = new BindResponseImpl( 2 ); assertFalse( resp0.equals( resp1 ), "different id objects should not be equal" ); assertFalse( resp1.equals( resp0 ), "different id objects should not be equal" ); } |
### Question:
BindResponseImpl extends AbstractResultResponse implements BindResponse { @Override public int hashCode() { int hash = 37; hash = hash * 17 + Arrays.hashCode( serverSaslCreds ); hash = hash * 17 + super.hashCode(); return hash; } BindResponseImpl(); BindResponseImpl( final int id ); @Override byte[] getServerSaslCreds(); @Override void setServerSaslCreds( byte[] serverSaslCreds ); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testHashCodeSameObj() { BindResponseImpl resp = new BindResponseImpl( 1 ); assertTrue( resp.hashCode() == resp.hashCode() ); }
@Test public void testHashCodeNewWithSameId() { BindResponseImpl resp0 = new BindResponseImpl( 1 ); BindResponseImpl resp1 = new BindResponseImpl( 1 ); assertTrue( resp1.hashCode() == resp0.hashCode() ); } |
### Question:
AbstractResultResponse extends AbstractResponse implements ResultResponse { @Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !super.equals( obj ) ) { return false; } if ( !( obj instanceof ResultResponse ) ) { return false; } ResultResponse resp = ( ResultResponse ) obj; return ( ( ldapResult != null ) && ldapResult.equals( resp.getLdapResult() ) ) || ( resp.getLdapResult() == null ); } protected AbstractResultResponse( final int id, final MessageTypeEnum type ); @Override LdapResult getLdapResult(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testEqualsSameObj() { AbstractResultResponse msg; msg = new AbstractResultResponse( 5, MessageTypeEnum.BIND_REQUEST ) { }; assertTrue( msg.equals( msg ) ); }
@Test public void testNotEqualsDiffId() { AbstractResultResponse msg0; AbstractResultResponse msg1; msg0 = new AbstractResultResponse( 5, MessageTypeEnum.BIND_REQUEST ) { }; msg1 = new AbstractResultResponse( 6, MessageTypeEnum.BIND_REQUEST ) { }; assertFalse( msg0.equals( msg1 ) ); assertFalse( msg1.equals( msg0 ) ); }
@Test public void testNotEqualsDiffType() { AbstractResultResponse msg0; AbstractResultResponse msg1; msg0 = new AbstractResultResponse( 5, MessageTypeEnum.BIND_REQUEST ) { }; msg1 = new AbstractResultResponse( 5, MessageTypeEnum.UNBIND_REQUEST ) { }; assertFalse( msg0.equals( msg1 ) ); assertFalse( msg1.equals( msg0 ) ); }
@Test public void testNotEqualsDiffControls() { AbstractResultResponse msg0; AbstractResultResponse msg1; msg0 = new AbstractResultResponse( 5, MessageTypeEnum.BIND_REQUEST ) { }; msg0.addControl( new Control() { public boolean isCritical() { return false; } public void setCritical( boolean isCritical ) { } public String getOid() { return "0.0"; } } ); msg1 = new AbstractResultResponse( 5, MessageTypeEnum.BIND_REQUEST ) { }; assertFalse( msg0.equals( msg1 ) ); assertFalse( msg1.equals( msg0 ) ); } |
### Question:
AbstractMessage implements Message { @Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !( obj instanceof Message ) ) { return false; } Message msg = ( Message ) obj; if ( msg.getMessageId() != id ) { return false; } if ( msg.getType() != type ) { return false; } Map<String, Control> controlMap = msg.getControls(); if ( controlMap.size() != controls.size() ) { return false; } for ( String key : controls.keySet() ) { if ( !controlMap.containsKey( key ) ) { return false; } } return true; } protected AbstractMessage( final int id, final MessageTypeEnum type ); @Override int getMessageId(); @Override Message setMessageId( int id ); @Override Map<String, Control> getControls(); @Override Control getControl( String oid ); @Override boolean hasControl( String oid ); @Override Message addControl( Control control ); @Override Message removeControl( Control control ); @Override MessageTypeEnum getType(); @Override Object get( Object key ); @Override Object put( Object key, Object value ); @Override boolean equals( Object obj ); @Override int hashCode(); @Override Message addAllControls( Control[] controls ); String toString( String message ); }### Answer:
@Test public void testEqualsSameObj() { AbstractMessage msg; msg = new AbstractMessage( 5, MessageTypeEnum.BIND_REQUEST ) { }; assertTrue( msg.equals( msg ) ); }
@Test public void testEqualsExactCopy() { AbstractMessage msg0; AbstractMessage msg1; msg0 = new AbstractMessage( 5, MessageTypeEnum.BIND_REQUEST ) { }; msg1 = new AbstractMessage( 5, MessageTypeEnum.BIND_REQUEST ) { }; assertTrue( msg0.equals( msg1 ) ); assertTrue( msg1.equals( msg0 ) ); }
@Test public void testNotEqualsDiffId() { AbstractMessage msg0; AbstractMessage msg1; msg0 = new AbstractMessage( 5, MessageTypeEnum.BIND_REQUEST ) { }; msg1 = new AbstractMessage( 6, MessageTypeEnum.BIND_REQUEST ) { }; assertFalse( msg0.equals( msg1 ) ); assertFalse( msg1.equals( msg0 ) ); }
@Test public void testNotEqualsDiffType() { AbstractMessage msg0; AbstractMessage msg1; msg0 = new AbstractMessage( 5, MessageTypeEnum.BIND_REQUEST ) { }; msg1 = new AbstractMessage( 5, MessageTypeEnum.UNBIND_REQUEST ) { }; assertFalse( msg0.equals( msg1 ) ); assertFalse( msg1.equals( msg0 ) ); } |
### Question:
LdapResultImpl implements LdapResult { @Override public boolean equals( Object obj ) { if ( obj == this ) { return true; } if ( !( obj instanceof LdapResult ) ) { return false; } LdapResult result = ( LdapResult ) obj; if ( referral == null && result.getReferral() != null ) { return false; } if ( result.getReferral() == null && referral != null ) { return false; } if ( referral != null && result.getReferral() != null && !referral.equals( result.getReferral() ) ) { return false; } if ( !resultCode.equals( result.getResultCode() ) ) { return false; } String errMsg0 = diagnosticMessage; String errMsg1 = result.getDiagnosticMessage(); if ( errMsg0 == null ) { errMsg0 = ""; } if ( errMsg1 == null ) { errMsg1 = ""; } if ( !errMsg0.equals( errMsg1 ) ) { return false; } if ( matchedDn != null ) { if ( !matchedDn.equals( result.getMatchedDn() ) ) { return false; } } else if ( result.getMatchedDn() != null ) { return false; } return true; } @Override String getDiagnosticMessage(); @Override void setDiagnosticMessage( String diagnosticMessage ); @Override Dn getMatchedDn(); @Override void setMatchedDn( Dn matchedDn ); @Override ResultCodeEnum getResultCode(); @Override void setResultCode( ResultCodeEnum resultCode ); @Override Referral getReferral(); @Override boolean isReferral(); @Override void setReferral( Referral referral ); @Override boolean isDefaultSuccess(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testEqualsSameObj() { LdapResultImpl r0 = new LdapResultImpl(); assertTrue( r0.equals( r0 ), "same object should be equal" ); }
@Test public void testEqualsDefaultCopy() { LdapResultImpl r0 = new LdapResultImpl(); LdapResultImpl r1 = new LdapResultImpl(); assertTrue( r0.equals( r1 ), "default copy should be equal" ); assertTrue( r1.equals( r0 ), "default copy should be equal" ); }
@Test public void testEqualsDiffLockableParent() { LdapResultImpl r0 = new LdapResultImpl(); LdapResultImpl r1 = new LdapResultImpl(); assertTrue( r0.equals( r1 ), "default copy with different lockable parents should be equal" ); assertTrue( r1.equals( r0 ), "default copy with different lockable parents should be equal" ); }
@Test public void testEqualsDiffImpl() { LdapResultImpl r0 = new LdapResultImpl(); LdapResult r1 = new LdapResult() { public ResultCodeEnum getResultCode() { return ResultCodeEnum.SUCCESS; } public void setResultCode( ResultCodeEnum a_resultCode ) { } public Dn getMatchedDn() { return null; } public void setMatchedDn( Dn dn ) { } public String getDiagnosticMessage() { return null; } public void setDiagnosticMessage( String diagnosticMessage ) { } public boolean isReferral() { return false; } public Referral getReferral() { return null; } public void setReferral( Referral referral ) { } public boolean isDefaultSuccess() { return false; } }; assertTrue( r0.equals( r1 ), "r0 equals should see other impl r1 as equal" ); assertFalse( r1.equals( r0 ), "r1 impl uses Object.equals() so it should not see r0 as the same object" ); } |
### Question:
LdapResultImpl implements LdapResult { @Override public int hashCode() { int hash = 37; if ( referral != null ) { hash = hash * 17 + referral.hashCode(); } hash = hash * 17 + resultCode.hashCode(); if ( diagnosticMessage != null ) { hash = hash * 17 + diagnosticMessage.hashCode(); } if ( matchedDn != null ) { hash = hash * 17 + matchedDn.hashCode(); } return hash; } @Override String getDiagnosticMessage(); @Override void setDiagnosticMessage( String diagnosticMessage ); @Override Dn getMatchedDn(); @Override void setMatchedDn( Dn matchedDn ); @Override ResultCodeEnum getResultCode(); @Override void setResultCode( ResultCodeEnum resultCode ); @Override Referral getReferral(); @Override boolean isReferral(); @Override void setReferral( Referral referral ); @Override boolean isDefaultSuccess(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testHashCodeSameObj() { LdapResultImpl r0 = new LdapResultImpl(); assertTrue( r0.hashCode() == r0.hashCode() ); }
@Test public void testHashCodeDefaultCopy() { LdapResultImpl r0 = new LdapResultImpl(); LdapResultImpl r1 = new LdapResultImpl(); assertTrue( r0.hashCode() == r1.hashCode() ); }
@Test public void testHashCodeDiffLockableParent() { LdapResultImpl r0 = new LdapResultImpl(); LdapResultImpl r1 = new LdapResultImpl(); assertTrue( r0.hashCode() == r1.hashCode() ); } |
### Question:
ModifyDnRequestImpl extends AbstractAbandonableRequest implements ModifyDnRequest { @Override public int hashCode() { int hash = 37; if ( name != null ) { hash = hash * 17 + name.hashCode(); } hash = hash * 17 + ( deleteOldRdn ? 0 : 1 ); if ( newRdn != null ) { hash = hash * 17 + newRdn.hashCode(); } if ( newSuperior != null ) { hash = hash * 17 + newSuperior.hashCode(); } hash = hash * 17 + super.hashCode(); return hash; } ModifyDnRequestImpl(); @Override boolean getDeleteOldRdn(); @Override ModifyDnRequest setDeleteOldRdn( boolean deleteOldRdn ); @Override boolean isMove(); @Override Dn getName(); @Override ModifyDnRequest setName( Dn name ); @Override Rdn getNewRdn(); @Override ModifyDnRequest setNewRdn( Rdn newRdn ); @Override Dn getNewSuperior(); @Override ModifyDnRequest setNewSuperior( Dn newSuperior ); @Override ModifyDnRequest setMessageId( int messageId ); @Override ModifyDnRequest addControl( Control control ); @Override ModifyDnRequest addAllControls( Control[] controls ); @Override ModifyDnRequest removeControl( Control control ); @Override MessageTypeEnum getResponseType(); @Override ModifyDnResponse getResultResponse(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override String toString(); }### Answer:
@Test public void testHashCodeExactCopy0() { ModifyDnRequestImpl req0 = getRequest(); ModifyDnRequestImpl req1 = getRequest(); assertTrue( req0.hashCode() == req1.hashCode() ); } |
### Question:
UndefinedNode extends AbstractExprNode { @Override public boolean isLeaf() { return false; } private UndefinedNode(); @Override boolean isLeaf(); @Override Object accept( FilterVisitor visitor ); @Override boolean isSchemaAware(); @Override String toString(); static final UndefinedNode UNDEFINED_NODE; }### Answer:
@Test public void testIsLeaf() throws Exception { assertFalse( undefinedNode.isLeaf() ); } |
### Question:
UndefinedNode extends AbstractExprNode { @Override public boolean isSchemaAware() { return false; } private UndefinedNode(); @Override boolean isLeaf(); @Override Object accept( FilterVisitor visitor ); @Override boolean isSchemaAware(); @Override String toString(); static final UndefinedNode UNDEFINED_NODE; }### Answer:
@Test public void testIsSchemaAware() throws Exception { assertFalse( undefinedNode.isSchemaAware() ); } |
### Question:
UndefinedNode extends AbstractExprNode { @Override public Object accept( FilterVisitor visitor ) { return null; } private UndefinedNode(); @Override boolean isLeaf(); @Override Object accept( FilterVisitor visitor ); @Override boolean isSchemaAware(); @Override String toString(); static final UndefinedNode UNDEFINED_NODE; }### Answer:
@Test public void testAccept() throws Exception { assertNull( undefinedNode.accept( new FilterVisitor() { public Object visit( ExprNode node ) { return null; } public boolean isPrefix() { return false; } public List<ExprNode> getOrder( BranchNode node, List<ExprNode> children ) { return null; } public boolean canVisit( ExprNode node ) { return false; } } ) ); } |
### Question:
BranchNormalizedVisitor implements FilterVisitor { @Override public Object visit( ExprNode node ) { if ( !( node instanceof BranchNode ) ) { return null; } BranchNode branch = ( BranchNode ) node; Comparator<ExprNode> nodeComparator = new NodeComparator(); Set<ExprNode> set = new TreeSet<>( nodeComparator ); List<ExprNode> children = branch.getChildren(); for ( ExprNode child : branch.getChildren() ) { if ( !child.isLeaf() ) { ExprNode newChild = ( ExprNode ) visit( child ); if ( newChild != null ) { set.add( newChild ); } } else { set.add( child ); } } children.clear(); children.addAll( set ); return branch; } @Override Object visit( ExprNode node ); @Override boolean canVisit( ExprNode node ); @Override boolean isPrefix(); @Override List<ExprNode> getOrder( BranchNode node, List<ExprNode> children ); static String getNormalizedFilter( SchemaManager schemaManager, String filter ); static String getNormalizedFilter( ExprNode filter ); }### Answer:
@Test public void testBranchNormalizedVisitor0() throws Exception { String filter = "(ou=Human Resources)"; ExprNode ori = FilterParser.parse( filter ); ExprNode altered = FilterParser.parse( filter ); BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); visitor.visit( altered ); assertEquals( ori.toString(), altered.toString() ); }
@Test public void testBranchNormalizedVisitor1() throws Exception { String filter = "(&(ou=Human Resources)(uid=akarasulu))"; ExprNode ori = FilterParser.parse( filter ); ExprNode altered = FilterParser.parse( filter ); BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); visitor.visit( altered ); assertEquals( ori.toString(), altered.toString() ); }
@Test public void testBranchNormalizedVisitor2() throws Exception { String filter = "(&(uid=akarasulu)(ou=Human Resources)"; filter += "(|(uid=akarasulu)(ou=Human Resources))) "; ExprNode ori = FilterParser.parse( filter ); ExprNode altered = FilterParser.parse( filter ); BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); visitor.visit( altered ); assertFalse( ori.toString().equals( altered.toString() ) ); }
@Test public void testBranchNormalizedVisitor3() throws Exception { String filter = "(&(ou=Human Resources)(uid=akarasulu)"; filter += "(|(ou=Human Resources)(uid=akarasulu)))"; ExprNode ori = FilterParser.parse( filter ); ExprNode altered = FilterParser.parse( filter ); BranchNormalizedVisitor visitor = new BranchNormalizedVisitor(); visitor.visit( altered ); assertTrue( ori.toString().equals( altered.toString() ) ); } |
### Question:
BranchNormalizedVisitor implements FilterVisitor { public static String getNormalizedFilter( SchemaManager schemaManager, String filter ) throws ParseException { ExprNode originalNode = FilterParser.parse( schemaManager, filter ); return getNormalizedFilter( originalNode ); } @Override Object visit( ExprNode node ); @Override boolean canVisit( ExprNode node ); @Override boolean isPrefix(); @Override List<ExprNode> getOrder( BranchNode node, List<ExprNode> children ); static String getNormalizedFilter( SchemaManager schemaManager, String filter ); static String getNormalizedFilter( ExprNode filter ); }### Answer:
@Test public void testBranchNormalizedComplex() throws Exception { String filter1 = "(&(a=A)(|(b=B)(c=C)))"; String filter2 = "(&(a=A)(|(c=C)(b=B)))"; String normalizedFilter1 = BranchNormalizedVisitor.getNormalizedFilter( null, filter1 ); String normalizedFilter2 = BranchNormalizedVisitor.getNormalizedFilter( null, filter2 ); assertEquals( normalizedFilter1, normalizedFilter2 ); } |
### Question:
SubstringNode extends LeafNode { public static Pattern getRegex( String initialPattern, String[] anyPattern, String finalPattern ) { StringBuilder buf = new StringBuilder(); if ( initialPattern != null ) { buf.append( '^' ).append( Pattern.quote( initialPattern ) ); } if ( anyPattern != null ) { for ( int i = 0; i < anyPattern.length; i++ ) { buf.append( ".*" ).append( Pattern.quote( anyPattern[i] ) ); } } if ( finalPattern != null ) { buf.append( ".*" ).append( Pattern.quote( finalPattern ) ); } else { buf.append( ".*" ); } return Pattern.compile( buf.toString() ); } SubstringNode( AttributeType attributeType, String initialPattern, String finalPattern ); SubstringNode( String attribute, String initialPattern, String finalPattern ); SubstringNode( AttributeType attribute ); SubstringNode( String attributeType ); SubstringNode( List<String> anyPattern, AttributeType attributeType, String initialPattern,
String finalPattern ); SubstringNode( List<String> anyPattern, String attribute, String initialPattern, String finalPattern ); static Pattern getRegex( String initialPattern, String[] anyPattern, String finalPattern ); @Override ExprNode clone(); final String getInitial(); void setInitial( String initialPattern ); final String getFinal(); void setFinal( String finalPattern ); final List<String> getAny(); void setAny( List<String> anyPattern ); void addAny( String anyPattern ); final Pattern getRegex( Normalizer normalizer ); @Override boolean equals( Object obj ); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testGetRegexpEmpty() throws Exception { Pattern pattern = SubstringNode.getRegex( "", new String[] { "" }, "" ); boolean b1 = pattern.matcher( "" ).matches(); assertTrue( b1 ); }
@Test public void testGetRegexpInitial() throws Exception { Pattern pattern = SubstringNode.getRegex( "Test", new String[] { "" }, "" ); boolean b1 = pattern.matcher( "Test just a test" ).matches(); assertTrue( b1 ); boolean b3 = pattern.matcher( "test just a test" ).matches(); assertFalse( b3 ); }
@Test public void testGetRegexpFinal() throws Exception { Pattern pattern = SubstringNode.getRegex( "", new String[] { "" }, "Test" ); boolean b1 = pattern.matcher( "test just a Test" ).matches(); assertTrue( b1 ); boolean b3 = pattern.matcher( "test just a test" ).matches(); assertFalse( b3 ); }
@Test public void testGetRegexpAny() throws Exception { Pattern pattern = SubstringNode.getRegex( "", new String[] { "just", "a" }, "" ); boolean b1 = pattern.matcher( "test just a Test" ).matches(); assertTrue( b1 ); boolean b3 = pattern.matcher( "test just A test" ).matches(); assertFalse( b3 ); }
@Test public void testGetRegexpFull() throws Exception { Pattern pattern = SubstringNode.getRegex( "Test", new String[] { "just", "a" }, "test" ); boolean b1 = pattern.matcher( "Test (this is) just (truly !) a (little) test" ).matches(); assertTrue( b1 ); boolean b3 = pattern.matcher( "Test (this is) just (truly !) A (little) test" ).matches(); assertFalse( b3 ); }
@Test public void testGetRegexpWithLdapFilterSpecialChars() throws Exception { Pattern[] patterns = new Pattern[] { SubstringNode.getRegex( null, new String[] { "(" }, null ), SubstringNode.getRegex( null, new String[] { ")" }, null ), SubstringNode.getRegex( null, new String[] { "*" }, null ), SubstringNode.getRegex( null, new String[] { "\\" }, null ), }; for ( Pattern pattern : patterns ) { boolean b1 = pattern.matcher( "a(b*c\\d)e" ).matches(); assertTrue( b1 ); boolean b3 = pattern.matcher( "Test test" ).matches(); assertFalse( b3 ); } } |
### Question:
FilterEncoder { public static String format( String filterTemplate, String... values ) { if ( values == null ) { values = Strings.EMPTY_STRING_ARRAY; } MessageFormat mf = new MessageFormat( filterTemplate, Locale.ROOT ); Format[] formats = mf.getFormatsByArgumentIndex(); if ( formats.length != values.length ) { throw new IllegalArgumentException( I18n.err( I18n.ERR_13300_BAD_PLACE_HOLDERS_NUMBER, filterTemplate, formats.length, values.length ) ); } for ( int i = 0; i < values.length; i++ ) { values[i] = encodeFilterValue( values[i] ); } return mf.format( values ); } private FilterEncoder(); static String format( String filterTemplate, String... values ); static String encodeFilterValue( String value ); }### Answer:
@Test public void testFormatWithNoPlaceholdersAndCorrectArgumentCount() { assertEquals( "(cn=foo)", FilterEncoder.format( "(cn=foo)", (String[])null ) ); assertEquals( "(cn=foo)", FilterEncoder.format( "(cn=foo)", ZERO ) ); }
@Test public void testFormatWithNoPlaceholdersAndTooManyArguments() { assertThrows( IllegalArgumentException.class, () -> { FilterEncoder.format( "(cn=foo)", ONE ); } ); }
@Test public void testFormatWithPlaceholdersAndTooFewArguments() { assertThrows( IllegalArgumentException.class, () -> { FilterEncoder.format( "(cn={0})", ZERO ); } ); }
@Test public void testFormatWithPlaceholdersAndCorrectArgumentCount() { assertEquals( "(cn=foo)", FilterEncoder.format( "(cn={0})", ONE ) ); assertEquals( "(&(cn=foo)(uid=bar))", FilterEncoder.format( "(&(cn={0})(uid={1}))", TWO ) ); }
@Test public void testFormatWithPlaceholdersAndTooManyArguments() { assertThrows( IllegalArgumentException.class, () -> { FilterEncoder.format( "(cn={0})", TWO ); } ); }
@Test public void testFormatWithPlaceholdersAndSpecialChars() { assertEquals( "(cn=\\28\\5C\\2A\\00\\29)", FilterEncoder.format( "(cn={0})", SPECIAL_CHARS ) ); }
@Test public void testExceptionMessage() { try { FilterEncoder.format( "(&(cn={0})(uid={1}))", ONE ); fail( "IllegalArgumentException expected" ); } catch ( IllegalArgumentException e ) { String message = e.getMessage(); assertTrue( message.contains( " (&(cn={0})(uid={1})) " ) ); assertTrue( message.contains( " 2 " ) ); assertTrue( message.contains( " 1 " ) ); } } |
### Question:
FilterEncoder { public static String encodeFilterValue( String value ) { StringBuilder sb = new StringBuilder( value.length() ); boolean escaped = false; boolean hexPair = false; char hex = '\0'; for ( int i = 0; i < value.length(); i++ ) { char ch = value.charAt( i ); switch ( ch ) { case '*': if ( escaped ) { sb.append( "\\5C" ); if ( hexPair ) { sb.append( hex ); hexPair = false; } escaped = false; } sb.append( "\\2A" ); break; case '(': if ( escaped ) { sb.append( "\\5C" ); if ( hexPair ) { sb.append( hex ); hexPair = false; } escaped = false; } sb.append( "\\28" ); break; case ')': if ( escaped ) { sb.append( "\\5C" ); if ( hexPair ) { sb.append( hex ); hexPair = false; } escaped = false; } sb.append( "\\29" ); break; case '\0': if ( escaped ) { sb.append( "\\5C" ); if ( hexPair ) { sb.append( hex ); hexPair = false; } escaped = false; } sb.append( "\\00" ); break; case '\\': if ( escaped ) { sb.append( "\\5C" ); escaped = false; } else { escaped = true; hexPair = false; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': if ( escaped ) { if ( hexPair ) { sb.append( '\\' ).append( hex ).append( ch ); escaped = false; hexPair = false; } else { hexPair = true; hex = ch; } } else { sb.append( ch ); } break; default: if ( escaped ) { sb.append( "\\5C" ); if ( hexPair ) { sb.append( hex ); hexPair = false; } escaped = false; } sb.append( ch ); } } if ( escaped ) { sb.append( "\\5C" ); } return sb.toString(); } private FilterEncoder(); static String format( String filterTemplate, String... values ); static String encodeFilterValue( String value ); }### Answer:
@Test public void testEncodeFilterValue() { assertEquals( "1234567890", FilterEncoder.encodeFilterValue( "1234567890" ) ); assertEquals( "\\28", FilterEncoder.encodeFilterValue( "(" ) ); assertEquals( "\\29", FilterEncoder.encodeFilterValue( ")" ) ); assertEquals( "\\2A", FilterEncoder.encodeFilterValue( "*" ) ); assertEquals( "\\5C", FilterEncoder.encodeFilterValue( "\\" ) ); assertEquals( "\\00", FilterEncoder.encodeFilterValue( "\0" ) ); assertEquals( "\\28\\2A\\29", FilterEncoder.encodeFilterValue( "(*)" ) ); assertEquals( "a test \\2A \\5Cend", FilterEncoder.encodeFilterValue( "a test \\2A \\end" ) ); } |
### Question:
PasswordUtil { public static boolean compareCredentials( byte[] receivedCredentials, byte[] storedCredentials ) { LdapSecurityConstants algorithm = findAlgorithm( storedCredentials ); if ( algorithm != null ) { PasswordDetails passwordDetails = PasswordUtil.splitCredentials( storedCredentials ); byte[] userPassword = PasswordUtil.encryptPassword( receivedCredentials, passwordDetails.getAlgorithm(), passwordDetails.getSalt() ); return compareBytes( userPassword, passwordDetails.getPassword() ); } else { return compareBytes( receivedCredentials, storedCredentials ); } } private PasswordUtil(); static LdapSecurityConstants findAlgorithm( byte[] credentials ); static byte[] createStoragePassword( String credentials, LdapSecurityConstants algorithm ); static byte[] createStoragePassword( byte[] credentials, LdapSecurityConstants algorithm ); static boolean compareCredentials( byte[] receivedCredentials, byte[] storedCredentials ); static PasswordDetails splitCredentials( byte[] credentials ); static boolean isPwdExpired( String pwdChangedZtime, int pwdMaxAgeSec, TimeProvider timeProvider ); static final int SHA1_LENGTH; static final int SHA256_LENGTH; static final int SHA384_LENGTH; static final int SHA512_LENGTH; static final int MD5_LENGTH; static final int PKCS5S2_LENGTH; static final int CRYPT_LENGTH; static final int CRYPT_MD5_LENGTH; static final int CRYPT_SHA256_LENGTH; static final int CRYPT_SHA512_LENGTH; static final int CRYPT_BCRYPT_LENGTH; }### Answer:
@Test public void compareCredentialTest() { assertTrue( PasswordUtil.compareCredentials( null, null ) ); assertTrue( PasswordUtil.compareCredentials( new byte[] {}, new byte[] {} ) ); assertTrue( PasswordUtil.compareCredentials( new byte[] { 0x01 }, new byte[] { 0x01 } ) ); assertFalse( PasswordUtil.compareCredentials( null, new byte[] { 0x01 } ) ); assertFalse( PasswordUtil.compareCredentials( new byte[] { 0x01 }, null ) ); assertFalse( PasswordUtil.compareCredentials( new byte[] { 0x01 }, new byte[] { 0x02 } ) ); assertFalse( PasswordUtil.compareCredentials( Strings.getBytesUtf8( "Password1" ), Strings.getBytesUtf8( "Password1 " ) ) ); assertFalse( PasswordUtil.compareCredentials( Strings.getBytesUtf8( "Password1" ), Strings.getBytesUtf8( "password1" ) ) ); assertTrue( PasswordUtil.compareCredentials( Strings.getBytesUtf8( "Password1" ), Strings.getBytesUtf8( "Password1" ) ) ); } |
Subsets and Splits