method2testcases
stringlengths
118
3.08k
### Question: PgConfigurationProperties implements ApplicationListener<ApplicationReadyEvent> { public int getFetchSize() { return getQueueSize() / queueFetchRatio; } int getPageSizeForIds(); int getQueueSizeForIds(); int getFetchSizeForIds(); int getFetchSize(); @Override void onApplicationEvent(ApplicationReadyEvent event); }### Answer: @Test void testGetFetchSize() { assertEquals(250, uut.getFetchSize()); }
### Question: PgQueryBuilder { public PgQueryBuilder(@NonNull SubscriptionRequestTO request) { this.req = request; selectIdOnly = request.idOnly() && !request.hasAnyScriptFilters(); } PgQueryBuilder(@NonNull SubscriptionRequestTO request); PreparedStatementSetter createStatementSetter(@NonNull AtomicLong serial); String createSQL(); String catchupSQL(long clientId); }### Answer: @Test public void testPGQueryBuilder() throws Exception { assertThrows(NullPointerException.class, () -> { new PgQueryBuilder(null); }); PgQueryBuilder uut = new PgQueryBuilder(mock(SubscriptionRequestTO.class)); assertThrows(NullPointerException.class, () -> { uut.createStatementSetter(null); }); }
### Question: ProtocolVersion { public boolean isCompatibleTo(ProtocolVersion other) { return (major == other.major) && (minor <= other.minor); } boolean isCompatibleTo(ProtocolVersion other); @Override String toString(); }### Answer: @Test void testIsCompatibleTo() { assertTrue(ProtocolVersion.of(1, 0, 0).isCompatibleTo(ProtocolVersion.of(1, 0, 0))); assertTrue(ProtocolVersion.of(1, 0, 0).isCompatibleTo(ProtocolVersion.of(1, 0, 1))); assertTrue(ProtocolVersion.of(1, 0, 0).isCompatibleTo(ProtocolVersion.of(1, 1, 0))); assertFalse(ProtocolVersion.of(1, 1, 0).isCompatibleTo(ProtocolVersion.of(1, 0, 0))); assertFalse(ProtocolVersion.of(1, 1, 0).isCompatibleTo(ProtocolVersion.of(2, 0, 0))); }
### Question: ProtocolVersion { @Override public String toString() { StringJoiner joiner = new StringJoiner("."); joiner.add(String.valueOf(major)).add(String.valueOf(minor)).add(String.valueOf(patch)); return joiner.toString(); } boolean isCompatibleTo(ProtocolVersion other); @Override String toString(); }### Answer: @Test void testToString() { assertEquals("3.1.2", ProtocolVersion.of(3, 1, 2).toString()); }
### Question: PgSynchronizedQuery { @SuppressWarnings("SameReturnValue") public synchronized void run(boolean useIndex) { long latest = latestFetcher.retrieveLatestSer(); transactionTemplate.execute(status -> { if (!useIndex) jdbcTemplate.execute("SET LOCAL enable_bitmapscan=0;"); jdbcTemplate.query(sql, setter, rowHandler); return null; }); serialToContinueFrom.set(Math.max(latest, serialToContinueFrom.get())); } PgSynchronizedQuery(@NonNull JdbcTemplate jdbcTemplate, @NonNull String sql, @NonNull PreparedStatementSetter setter, @NonNull RowCallbackHandler rowHandler, AtomicLong serialToContinueFrom, PgLatestSerialFetcher fetcher); @SuppressWarnings("SameReturnValue") synchronized void run(boolean useIndex); }### Answer: @Test public void testRunWithIndex() throws Exception { uut = new PgSynchronizedQuery(jdbcTemplate, sql, setter, rowHandler, serialToContinueFrom, fetcher); uut.run(true); verify(jdbcTemplate, never()).execute(startsWith("SET LOCAL enable_bitmapscan")); } @Test public void testRunWithoutIndex() throws Exception { uut = new PgSynchronizedQuery(jdbcTemplate, sql, setter, rowHandler, serialToContinueFrom, fetcher); uut.run(false); verify(jdbcTemplate).execute(startsWith("SET LOCAL enable_bitmapscan")); }
### Question: SnappyGrpcClientCodec implements Codec { @Override public String getMessageEncoding() { return "snappy"; } @Override String getMessageEncoding(); @Override OutputStream compress(OutputStream os); @Override InputStream decompress(InputStream is); }### Answer: @Test void getMessageEncoding() { assertEquals("snappy", uut.getMessageEncoding()); }
### Question: Lz4GrpcClientCodec implements Codec { @Override public String getMessageEncoding() { return "lz4"; } @Override String getMessageEncoding(); @Override InputStream decompress(InputStream inputStream); @Override OutputStream compress(OutputStream outputStream); }### Answer: @Test void getMessageEncoding() { assertEquals("lz4", uut.getMessageEncoding()); }
### Question: ClientStreamObserver implements StreamObserver<FactStoreProto.MSG_Notification> { @Override public void onCompleted() { subscription.notifyComplete(); } @Override void onNext(MSG_Notification f); @Override void onError(Throwable t); @Override void onCompleted(); }### Answer: @Test void testOnTransportComplete() { uut.onCompleted(); verify(factObserver).onComplete(); }
### Question: ClientStreamObserver implements StreamObserver<FactStoreProto.MSG_Notification> { @Override public void onError(Throwable t) { subscription.notifyError(t); } @Override void onNext(MSG_Notification f); @Override void onError(Throwable t); @Override void onCompleted(); }### Answer: @Test void testOnError() { uut.onError(new IOException()); verify(factObserver).onError(any()); }
### Question: GrpcFactStore implements FactStore, SmartInitializingSingleton { @VisibleForTesting void configureCompression(String codecListFromServer) { codecs.selectFrom(codecListFromServer).ifPresent(c -> { log.info("configuring Codec " + c); this.blockingStub = blockingStub.withCompression(c); this.stub = stub.withCompression(c); }); } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Autowired @Generated GrpcFactStore(FactCastGrpcChannelFactory channelFactory, @Value("${grpc.client.factstore.credentials:#{null}}") Optional<String> credentials); @Generated @VisibleForTesting GrpcFactStore(Channel channel, Optional<String> credentials); private GrpcFactStore(RemoteFactStoreBlockingStub newBlockingStub, RemoteFactStoreStub newStub, Optional<String> credentials); @Override Optional<Fact> fetchById(UUID id); @Override void publish(@NonNull List<? extends Fact> factsToPublish); @Override Subscription subscribe(@NonNull SubscriptionRequestTO req, @NonNull FactObserver observer); @Override OptionalLong serialOf(@NonNull UUID l); synchronized void initialize(); @Override synchronized void afterSingletonsInstantiated(); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(String ns); @Override boolean publishIfUnchanged(@NonNull List<? extends Fact> factsToPublish, @NonNull Optional<StateToken> token); @Override void invalidate(@NonNull StateToken token); @Override StateToken stateFor(@NonNull Collection<UUID> forAggIds, @NonNull Optional<String> ns); @Override long currentTime(); }### Answer: @Test void configureCompressionChooseGzipIfAvail() { uut.configureCompression(" gzip,lz3,lz4, lz99"); verify(stub).withCompression("gzip"); } @Test void configureCompressionSkipCompression() { uut.configureCompression("zip,lz3,lz4, lz99"); verifyNoMoreInteractions(stub); }
### Question: PgFactStream { void connect(@NonNull SubscriptionRequestTO request) { this.request = request; log.debug("{} connecting subscription {}", request, request.dump()); postQueryMatcher = new PgPostQueryMatcher(request); PgQueryBuilder q = new PgQueryBuilder(request); initializeSerialToStartAfter(); String sql = q.createSQL(); PreparedStatementSetter setter = q.createStatementSetter(serial); RowCallbackHandler rsHandler = new FactRowCallbackHandler(subscription, postQueryMatcher); PgSynchronizedQuery query = new PgSynchronizedQuery(jdbcTemplate, sql, setter, rsHandler, serial, fetcher); catchupAndFollow(request, subscription, query); } synchronized void close(); }### Answer: @Test public void testConnectNullParameter() throws Exception { assertThrows(NullPointerException.class, () -> { uut.connect(null); }); }
### Question: PgPostQueryMatcher implements Predicate<Fact> { PgPostQueryMatcher(@NonNull SubscriptionRequest req) { canBeSkipped = req.specs().stream().noneMatch(s -> s.jsFilterScript() != null); if (canBeSkipped) { log.trace("{} post query filtering has been disabled", req); } else { this.matchers.addAll(req.specs() .stream() .map(FactSpecMatcher::new) .collect(Collectors.toList())); } } PgPostQueryMatcher(@NonNull SubscriptionRequest req); @Override boolean test(Fact input); }### Answer: @Test public void testPGPostQueryMatcher() throws Exception { assertThrows(NullPointerException.class, () -> { new PgPostQueryMatcher(null); }); }
### Question: GrpcFactStore implements FactStore, SmartInitializingSingleton { @VisibleForTesting static RuntimeException wrapRetryable(StatusRuntimeException e) { if (e.getStatus().getCode() == Code.UNAVAILABLE) { return new RetryableException(e); } else { return e; } } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @Autowired @Generated GrpcFactStore(FactCastGrpcChannelFactory channelFactory, @Value("${grpc.client.factstore.credentials:#{null}}") Optional<String> credentials); @Generated @VisibleForTesting GrpcFactStore(Channel channel, Optional<String> credentials); private GrpcFactStore(RemoteFactStoreBlockingStub newBlockingStub, RemoteFactStoreStub newStub, Optional<String> credentials); @Override Optional<Fact> fetchById(UUID id); @Override void publish(@NonNull List<? extends Fact> factsToPublish); @Override Subscription subscribe(@NonNull SubscriptionRequestTO req, @NonNull FactObserver observer); @Override OptionalLong serialOf(@NonNull UUID l); synchronized void initialize(); @Override synchronized void afterSingletonsInstantiated(); @Override Set<String> enumerateNamespaces(); @Override Set<String> enumerateTypes(String ns); @Override boolean publishIfUnchanged(@NonNull List<? extends Fact> factsToPublish, @NonNull Optional<StateToken> token); @Override void invalidate(@NonNull StateToken token); @Override StateToken stateFor(@NonNull Collection<UUID> forAggIds, @NonNull Optional<String> ns); @Override long currentTime(); }### Answer: @Test void testWrapRetryable_nonRetryable() throws Exception { StatusRuntimeException cause = new StatusRuntimeException(Status.DEADLINE_EXCEEDED); RuntimeException e = GrpcFactStore.wrapRetryable(cause); assertTrue(e instanceof StatusRuntimeException); assertSame(e, cause); } @Test void testWrapRetryable() throws Exception { StatusRuntimeException cause = new StatusRuntimeException(Status.UNAVAILABLE); RuntimeException e = GrpcFactStore.wrapRetryable(cause); assertTrue(e instanceof RetryableException); assertSame(e.getCause(), cause); }
### Question: JadxCLIArgs { public boolean isReplaceConsts() { return replaceConsts; } boolean processArgs(String[] args); boolean overrideProvided(String[] args); JadxArgs toJadxArgs(); List<String> getFiles(); String getOutDir(); String getOutDirSrc(); String getOutDirRes(); boolean isSkipResources(); boolean isSkipSources(); int getThreadsCount(); boolean isFallbackMode(); boolean isShowInconsistentCode(); boolean isUseImports(); boolean isDebugInfo(); boolean isInlineAnonymousClasses(); boolean isDeobfuscationOn(); int getDeobfuscationMinLength(); int getDeobfuscationMaxLength(); boolean isDeobfuscationForceSave(); boolean isDeobfuscationUseSourceNameAsAlias(); boolean isDeobfuscationParseKotlinMetadata(); boolean isEscapeUnicode(); boolean isCfgOutput(); boolean isRawCfgOutput(); boolean isReplaceConsts(); boolean isRespectBytecodeAccessModifiers(); boolean isExportAsGradleProject(); boolean isRenameCaseSensitive(); boolean isRenameValid(); boolean isRenamePrintable(); boolean isFsCaseSensitive(); static String enumValuesString(Enum<?>[] values); }### Answer: @Test public void testInvertedBooleanOption() { assertThat(parse("--no-replace-consts").isReplaceConsts(), is(false)); assertThat(parse("").isReplaceConsts(), is(true)); }
### Question: CertificateManager { public String generateSignature() { StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.serialSigType"), x509cert.getSigAlgName()); append(builder, NLS.str("certificate.serialSigOID"), x509cert.getSigAlgOID()); return builder.toString(); } CertificateManager(Certificate cert); static String decode(InputStream in); String generateHeader(); String generateSignature(); String generateFingerprint(); String generatePublicKey(); String generateTextForX509(); String generateText(); static String getThumbPrint(X509Certificate cert, String type); static String hexify(byte[] bytes); }### Answer: @Test public void decodeRSAKeySignature() { String string = certificateManagerRSA.generateSignature(); assertTrue(string.contains("SHA256withRSA")); assertTrue(string.contains("1.2.840.113549.1.1.11")); } @Test public void decodeDSAKeySignature() { String string = certificateManagerDSA.generateSignature(); assertTrue(string.contains("SHA1withDSA")); assertTrue(string.contains("1.2.840.10040.4.3")); }
### Question: StringRef implements CharSequence { public static StringRef subString(String str, int from, int to) { return new StringRef(str, from, to - from); } private StringRef(String str, int from, int length); static StringRef subString(String str, int from, int to); static StringRef subString(String str, int from); static StringRef fromStr(String str); @Override int length(); @Override char charAt(int index); @Override CharSequence subSequence(int start, int end); StringRef trim(); int indexOf(String str); int indexOf(String str, boolean caseInsensitive); int indexOf(String str, int from, boolean caseInsensitive); int indexOf(String str, int from); static List<StringRef> split(String str, String splitBy); int hashCode(); boolean equals(Object other); @NotNull @Override String toString(); }### Answer: @Test public void testSubstring() { checkStr(subString("a", 0), "a"); checkStr(subString("a", 1), ""); checkStr(subString("a", 0, 0), ""); checkStr(subString("a", 0, 1), "a"); checkStr(subString("abc", 1, 2), "b"); checkStr(subString("abc", 2), "c"); checkStr(subString("abc", 2, 3), "c"); }
### Question: StringRef implements CharSequence { public StringRef trim() { int start = offset; int end = start + length; String str = refStr; while ((start < end) && (str.charAt(start) <= ' ')) { start++; } while ((start < end) && (str.charAt(end - 1) <= ' ')) { end--; } if ((start > offset) || (end < offset + length)) { return subString(str, start, end); } return this; } private StringRef(String str, int from, int length); static StringRef subString(String str, int from, int to); static StringRef subString(String str, int from); static StringRef fromStr(String str); @Override int length(); @Override char charAt(int index); @Override CharSequence subSequence(int start, int end); StringRef trim(); int indexOf(String str); int indexOf(String str, boolean caseInsensitive); int indexOf(String str, int from, boolean caseInsensitive); int indexOf(String str, int from); static List<StringRef> split(String str, String splitBy); int hashCode(); boolean equals(Object other); @NotNull @Override String toString(); }### Answer: @Test public void testTrim() { checkTrim(fromStr("a"), "a"); checkTrim(fromStr(" a "), "a"); checkTrim(fromStr("\ta"), "a"); checkTrim(subString("a b c", 1), "b c"); checkTrim(subString("a b\tc", 1, 4), "b"); checkTrim(subString("a b\tc", 2, 3), "b"); }
### Question: StringRef implements CharSequence { public static List<StringRef> split(String str, String splitBy) { int len = str.length(); int targetLen = splitBy.length(); if (len == 0 || targetLen == 0) { return Collections.emptyList(); } int pos = -targetLen; List<StringRef> list = new ArrayList<>(); while (true) { int start = pos + targetLen; pos = indexOf(str, 0, len, splitBy, 0, targetLen, start, false); if (pos == -1) { if (start != len) { list.add(subString(str, start, len)); } break; } else { list.add(subString(str, start, pos)); } } return list; } private StringRef(String str, int from, int length); static StringRef subString(String str, int from, int to); static StringRef subString(String str, int from); static StringRef fromStr(String str); @Override int length(); @Override char charAt(int index); @Override CharSequence subSequence(int start, int end); StringRef trim(); int indexOf(String str); int indexOf(String str, boolean caseInsensitive); int indexOf(String str, int from, boolean caseInsensitive); int indexOf(String str, int from); static List<StringRef> split(String str, String splitBy); int hashCode(); boolean equals(Object other); @NotNull @Override String toString(); }### Answer: @Test public void testSplit() { checkSplit("abc", "b", "a", "c"); checkSplit("abc", "a", "", "bc"); checkSplit("abc", "c", "ab"); checkSplit("abc", "d", "abc"); checkSplit("abbbc", "b", "a", "", "", "c"); checkSplit("abbbc", "bb", "a", "bc"); checkSplit("abbbc", "bbb", "a", "c"); checkSplit("abbbc", "bbc", "ab"); checkSplit("abbbc", "bbbc", "a"); }
### Question: VersionComparator { public static int compare(String str1, String str2) { String[] s1 = str1.split("\\."); int l1 = s1.length; String[] s2 = str2.split("\\."); int l2 = s2.length; int i = 0; while (i < l1 && i < l2) { if (!s1[i].equals(s2[i])) { break; } i++; } if (i < l1 && i < l2) { return Integer.valueOf(s1[i]).compareTo(Integer.valueOf(s2[i])); } boolean checkFirst = l1 > l2; boolean zeroTail = isZeroTail(checkFirst ? s1 : s2, i); if (zeroTail) { return 0; } return checkFirst ? 1 : -1; } private VersionComparator(); static int checkAndCompare(String str1, String str2); static int compare(String str1, String str2); }### Answer: @Test public void testCompare() { checkCompare("", "", 0); checkCompare("1", "1", 0); checkCompare("1", "2", -1); checkCompare("1.1", "1.1", 0); checkCompare("0.5", "0.5", 0); checkCompare("0.5", "0.5.0", 0); checkCompare("0.5", "0.5.00", 0); checkCompare("0.5", "0.5.0.0", 0); checkCompare("0.5", "0.5.0.1", -1); checkCompare("0.5.0", "0.5.0", 0); checkCompare("0.5.0", "0.5.1", -1); checkCompare("0.5", "0.5.1", -1); checkCompare("0.4.8", "0.5", -1); checkCompare("0.4.8", "0.5.0", -1); checkCompare("0.4.8", "0.6", -1); }
### Question: JadxCLIArgs { public boolean isEscapeUnicode() { return escapeUnicode; } boolean processArgs(String[] args); boolean overrideProvided(String[] args); JadxArgs toJadxArgs(); List<String> getFiles(); String getOutDir(); String getOutDirSrc(); String getOutDirRes(); boolean isSkipResources(); boolean isSkipSources(); int getThreadsCount(); boolean isFallbackMode(); boolean isShowInconsistentCode(); boolean isUseImports(); boolean isDebugInfo(); boolean isInlineAnonymousClasses(); boolean isDeobfuscationOn(); int getDeobfuscationMinLength(); int getDeobfuscationMaxLength(); boolean isDeobfuscationForceSave(); boolean isDeobfuscationUseSourceNameAsAlias(); boolean isDeobfuscationParseKotlinMetadata(); boolean isEscapeUnicode(); boolean isCfgOutput(); boolean isRawCfgOutput(); boolean isReplaceConsts(); boolean isRespectBytecodeAccessModifiers(); boolean isExportAsGradleProject(); boolean isRenameCaseSensitive(); boolean isRenameValid(); boolean isRenamePrintable(); boolean isFsCaseSensitive(); static String enumValuesString(Enum<?>[] values); }### Answer: @Test public void testEscapeUnicodeOption() { assertThat(parse("--escape-unicode").isEscapeUnicode(), is(true)); assertThat(parse("").isEscapeUnicode(), is(false)); }
### Question: TypeCompare { public TypeCompareEnum compareTypes(ClassNode first, ClassNode second) { return compareObjects(first.getType(), second.getType()); } TypeCompare(RootNode root); TypeCompareEnum compareTypes(ClassNode first, ClassNode second); TypeCompareEnum compareTypes(ArgType first, ArgType second); Comparator<ArgType> getComparator(); Comparator<ArgType> getReversedComparator(); }### Answer: @Test public void compareTypes() { firstIsNarrow(INT, UNKNOWN); firstIsNarrow(array(UNKNOWN), UNKNOWN); firstIsNarrow(array(UNKNOWN), NARROW); }
### Question: AccessInfo { public AccessInfo changeVisibility(int flag) { int currentVisFlags = accFlags & VISIBILITY_FLAGS; if (currentVisFlags == flag) { return this; } int unsetAllVisFlags = accFlags & ~VISIBILITY_FLAGS; return new AccessInfo(unsetAllVisFlags | flag, type); } AccessInfo(int accessFlags, AFType type); boolean containsFlag(int flag); AccessInfo remove(int flag); AccessInfo add(int flag); AccessInfo changeVisibility(int flag); AccessInfo getVisibility(); boolean isPublic(); boolean isProtected(); boolean isPrivate(); boolean isPackagePrivate(); boolean isAbstract(); boolean isInterface(); boolean isAnnotation(); boolean isNative(); boolean isStatic(); boolean isFinal(); boolean isConstructor(); boolean isEnum(); boolean isSynthetic(); boolean isBridge(); boolean isVarArgs(); boolean isSynchronized(); boolean isTransient(); boolean isVolatile(); AFType getType(); String makeString(); String visibilityName(); int rawValue(); @Override String toString(); static final int VISIBILITY_FLAGS; }### Answer: @Test public void changeVisibility() { AccessInfo accessInfo = new AccessInfo(AccessFlags.PROTECTED | AccessFlags.STATIC, AFType.METHOD); AccessInfo result = accessInfo.changeVisibility(AccessFlags.PUBLIC); assertThat(result.isPublic(), is(true)); assertThat(result.isPrivate(), is(false)); assertThat(result.isProtected(), is(false)); assertThat(result.isStatic(), is(true)); } @Test public void changeVisibilityNoOp() { AccessInfo accessInfo = new AccessInfo(AccessFlags.PUBLIC, AFType.METHOD); AccessInfo result = accessInfo.changeVisibility(AccessFlags.PUBLIC); assertSame(accessInfo, result); }
### Question: NameMapper { public static boolean isValidIdentifier(String str) { return notEmpty(str) && !isReserved(str) && VALID_JAVA_IDENTIFIER.matcher(str).matches(); } private NameMapper(); static boolean isReserved(String str); static boolean isValidIdentifier(String str); static boolean isValidFullIdentifier(String str); static boolean isValidAndPrintable(String str); static boolean isValidIdentifierStart(int codePoint); static boolean isValidIdentifierPart(int codePoint); static boolean isPrintableChar(int c); static boolean isAllCharsPrintable(String str); static String removeInvalidCharsMiddle(String name); static String removeInvalidChars(String name, String prefix); }### Answer: @Test public void validIdentifiers() { assertThat(isValidIdentifier("ACls"), is(true)); } @Test public void notValidIdentifiers() { assertThat(isValidIdentifier("1cls"), is(false)); assertThat(isValidIdentifier("-cls"), is(false)); assertThat(isValidIdentifier("A-cls"), is(false)); }
### Question: NameMapper { public static String removeInvalidCharsMiddle(String name) { if (isValidIdentifier(name) && isAllCharsPrintable(name)) { return name; } int len = name.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { int codePoint = name.codePointAt(i); if (isPrintableChar(codePoint) && isValidIdentifierPart(codePoint)) { sb.append((char) codePoint); } } return sb.toString(); } private NameMapper(); static boolean isReserved(String str); static boolean isValidIdentifier(String str); static boolean isValidFullIdentifier(String str); static boolean isValidAndPrintable(String str); static boolean isValidIdentifierStart(int codePoint); static boolean isValidIdentifierPart(int codePoint); static boolean isPrintableChar(int c); static boolean isAllCharsPrintable(String str); static String removeInvalidCharsMiddle(String name); static String removeInvalidChars(String name, String prefix); }### Answer: @Test public void testRemoveInvalidCharsMiddle() { assertThat(removeInvalidCharsMiddle("1cls"), is("1cls")); assertThat(removeInvalidCharsMiddle("-cls"), is("cls")); assertThat(removeInvalidCharsMiddle("A-cls"), is("Acls")); }
### Question: NameMapper { public static String removeInvalidChars(String name, String prefix) { String result = removeInvalidCharsMiddle(name); if (!result.isEmpty()) { int codePoint = result.codePointAt(0); if (!isValidIdentifierStart(codePoint)) { return prefix + result; } } return result; } private NameMapper(); static boolean isReserved(String str); static boolean isValidIdentifier(String str); static boolean isValidFullIdentifier(String str); static boolean isValidAndPrintable(String str); static boolean isValidIdentifierStart(int codePoint); static boolean isValidIdentifierPart(int codePoint); static boolean isPrintableChar(int c); static boolean isAllCharsPrintable(String str); static String removeInvalidCharsMiddle(String name); static String removeInvalidChars(String name, String prefix); }### Answer: @Test public void testRemoveInvalidChars() { assertThat(removeInvalidChars("1cls", "C"), is("C1cls")); assertThat(removeInvalidChars("-cls", "C"), is("cls")); assertThat(removeInvalidChars("A-cls", "C"), is("Acls")); }
### Question: JadxCLIArgs { public boolean isSkipSources() { return skipSources; } boolean processArgs(String[] args); boolean overrideProvided(String[] args); JadxArgs toJadxArgs(); List<String> getFiles(); String getOutDir(); String getOutDirSrc(); String getOutDirRes(); boolean isSkipResources(); boolean isSkipSources(); int getThreadsCount(); boolean isFallbackMode(); boolean isShowInconsistentCode(); boolean isUseImports(); boolean isDebugInfo(); boolean isInlineAnonymousClasses(); boolean isDeobfuscationOn(); int getDeobfuscationMinLength(); int getDeobfuscationMaxLength(); boolean isDeobfuscationForceSave(); boolean isDeobfuscationUseSourceNameAsAlias(); boolean isDeobfuscationParseKotlinMetadata(); boolean isEscapeUnicode(); boolean isCfgOutput(); boolean isRawCfgOutput(); boolean isReplaceConsts(); boolean isRespectBytecodeAccessModifiers(); boolean isExportAsGradleProject(); boolean isRenameCaseSensitive(); boolean isRenameValid(); boolean isRenamePrintable(); boolean isFsCaseSensitive(); static String enumValuesString(Enum<?>[] values); }### Answer: @Test public void testSrcOption() { assertThat(parse("--no-src").isSkipSources(), is(true)); assertThat(parse("-s").isSkipSources(), is(true)); assertThat(parse("").isSkipSources(), is(false)); }
### Question: CertificateManager { public static String decode(InputStream in) { StringBuilder strBuild = new StringBuilder(); Collection<? extends Certificate> certificates = readCertificates(in); if (certificates != null) { for (Certificate cert : certificates) { CertificateManager certificateManager = new CertificateManager(cert); strBuild.append(certificateManager.generateText()); } } return strBuild.toString(); } CertificateManager(Certificate cert); static String decode(InputStream in); String generateHeader(); String generateSignature(); String generateFingerprint(); String generatePublicKey(); String generateTextForX509(); String generateText(); static String getThumbPrint(X509Certificate cert, String type); static String hexify(byte[] bytes); }### Answer: @Test public void decodeNotCertificateFile() throws IOException { try (InputStream in = new FileInputStream(emptyPath)) { String result = CertificateManager.decode(in); assertEquals("", result); } }
### Question: CertificateManager { public String generateHeader() { StringBuilder builder = new StringBuilder(); append(builder, NLS.str("certificate.cert_type"), x509cert.getType()); append(builder, NLS.str("certificate.serialSigVer"), ((Integer) x509cert.getVersion()).toString()); append(builder, NLS.str("certificate.serialNumber"), "0x" + x509cert.getSerialNumber().toString(16)); Principal subjectDN = x509cert.getSubjectDN(); append(builder, NLS.str("certificate.cert_subject"), subjectDN.getName()); append(builder, NLS.str("certificate.serialValidFrom"), x509cert.getNotBefore().toString()); append(builder, NLS.str("certificate.serialValidUntil"), x509cert.getNotAfter().toString()); return builder.toString(); } CertificateManager(Certificate cert); static String decode(InputStream in); String generateHeader(); String generateSignature(); String generateFingerprint(); String generatePublicKey(); String generateTextForX509(); String generateText(); static String getThumbPrint(X509Certificate cert, String type); static String hexify(byte[] bytes); }### Answer: @Test public void decodeRSAKeyHeader() { String string = certificateManagerRSA.generateHeader(); assertTrue(string.contains("X.509")); assertTrue(string.contains("0x4bd68052")); assertTrue(string.contains("CN=test cert, OU=test unit, O=OOO TestOrg, L=St.Peterburg, ST=Russia, C=123456")); } @Test public void decodeDSAKeyHeader() { String string = certificateManagerDSA.generateHeader(); assertTrue(string.contains("X.509")); assertTrue(string.contains("0x16420ba2")); assertTrue(string.contains("O=\"UJMRFVV CN=EDCVBGT C=TG\"")); }
### Question: CatalogService { public CompletableFuture<String> addProductToCatalog(AddProductToCatalogCommand command) { LOG.debug("Processing AddProductToCatalogCommand command: {}", command); return this.commandGateway.send(command); } CatalogService(CommandGateway commandGateway); CompletableFuture<String> addProductToCatalog(AddProductToCatalogCommand command); }### Answer: @Test public void testApi() throws Exception { when(commandGateway.send(any())) .thenAnswer(i -> { AddProductToCatalogCommand command = i.getArgumentAt(0, AddProductToCatalogCommand.class); assertEquals(id, command.getId()); CompletableFuture<String> response = new CompletableFuture<String>(); response.complete(command.getId()); return response; }); CompletableFuture<String> response = service.addProductToCatalog(command); verify(commandGateway, times(1)).send(any()); verifyNoMoreInteractions(commandGateway); assertEquals(id, response.get().toString()); }
### Question: CatalogApiController { @PostMapping("/add") public CompletableFuture<String> addProductToCatalog(@RequestBody Map<String, String> request) { AddProductToCatalogCommand command = new AddProductToCatalogCommand(request.get("id"), request.get("name")); LOG.info("Executing command: {}", command); return catalogService.addProductToCatalog(command); } CatalogApiController(CatalogService commandGateway); @PostMapping("/add") CompletableFuture<String> addProductToCatalog(@RequestBody Map<String, String> request); }### Answer: @Test public void checkControllerCallsServiceCorrectly() throws ExecutionException, InterruptedException { assertNotNull(request); assertNotNull(request.containsKey("id")); assertNotNull(request.containsKey("name")); when(commandGateway.addProductToCatalog(any(AddProductToCatalogCommand.class))) .thenAnswer(i -> { AddProductToCatalogCommand command = i.getArgumentAt(0, AddProductToCatalogCommand.class); CompletableFuture<String> response = new CompletableFuture<String>(); response.complete(command.getId()); return response; }); CompletableFuture<String> answer = controller.addProductToCatalog(request); verify(commandGateway, times(1)).addProductToCatalog(any(AddProductToCatalogCommand.class)); verifyNoMoreInteractions(commandGateway); assertEquals(id, answer.get().toString()); }
### Question: EventProcessor { @EventHandler public void on(ProductAddedEvent productAddedEvent) { repo.save(new Product(productAddedEvent.getId(), productAddedEvent.getName())); LOG.info("A product was added! Id={} Name={}", productAddedEvent.getId(), productAddedEvent.getName()); } EventProcessor(ProductRepository repository); @EventHandler // Mark this method as an Axon Event Handler void on(ProductAddedEvent productAddedEvent); }### Answer: @Test public void testOn(){ List<Product> products = new ArrayList<>(); when(repo.save(any(Product.class))) .thenAnswer(i -> { Product prod = i.getArgumentAt(0, Product.class); products.add(prod); return prod; }); processor.on(event); verify(repo, times(1)).save(any(Product.class)); verifyNoMoreInteractions(repo); Assert.assertEquals(products.get(0).getId(), uuid); Assert.assertEquals(products.get(0).getName(), name); }
### Question: DriftMethodInvocation extends AbstractFuture<Object> { static <A extends Address> DriftMethodInvocation<A> createDriftMethodInvocation( MethodInvoker invoker, MethodMetadata metadata, Map<String, String> headers, List<Object> parameters, RetryPolicy retryPolicy, AddressSelector<A> addressSelector, Optional<String> addressSelectionContext, MethodInvocationStat stat, Ticker ticker) { DriftMethodInvocation<A> invocation = new DriftMethodInvocation<>( invoker, metadata, headers, parameters, retryPolicy, addressSelector, addressSelectionContext, stat, ticker); invocation.nextAttempt(true); return invocation; } private DriftMethodInvocation( MethodInvoker invoker, MethodMetadata metadata, Map<String, String> headers, List<Object> parameters, RetryPolicy retryPolicy, AddressSelector<A> addressSelector, Optional<String> addressSelectionContext, MethodInvocationStat stat, Ticker ticker); }### Answer: @Test(timeOut = 60000) public void testFirstTrySuccess() throws Exception { TestingMethodInvocationStat stat = new TestingMethodInvocationStat(); DriftMethodInvocation<?> methodInvocation = createDriftMethodInvocation(RetryPolicy.NO_RETRY_POLICY, stat, () -> immediateFuture(SUCCESS)); assertEquals(methodInvocation.get(), SUCCESS); stat.assertSuccess(0); }
### Question: ThriftUnionMetadataBuilder extends AbstractThriftMetadataBuilder { @Override public ThriftStructMetadata build() { metadataErrors.throwIfHasErrors(); ThriftMethodInjection builderMethodInjection = buildBuilderConstructorInjections(); ThriftConstructorInjection constructorInjection = buildConstructorInjection(); Iterable<ThriftFieldMetadata> fieldsMetadata = buildFieldInjections(); List<ThriftMethodInjection> methodInjections = buildMethodInjections(); return new ThriftStructMetadata( structName, extractStructIdlAnnotations(), structType, builderType, MetadataType.UNION, Optional.ofNullable(builderMethodInjection), ImmutableList.copyOf(documentation), ImmutableList.copyOf(fieldsMetadata), Optional.ofNullable(constructorInjection), methodInjections); } ThriftUnionMetadataBuilder(ThriftCatalog catalog, Type structType); @Override ThriftStructMetadata build(); }### Answer: @Test public void testNonFinalUnionOk() { ThriftUnionMetadataBuilder builder = new ThriftUnionMetadataBuilder(new ThriftCatalog(), NotFinalUnion.class); builder.build(); }
### Question: ThriftStructMetadataBuilder extends AbstractThriftMetadataBuilder { @Override public ThriftStructMetadata build() { metadataErrors.throwIfHasErrors(); ThriftMethodInjection builderMethodInjection = buildBuilderConstructorInjections(); ThriftConstructorInjection constructorInjections = buildConstructorInjection(); Iterable<ThriftFieldMetadata> fieldsMetadata = buildFieldInjections(); List<ThriftMethodInjection> methodInjections = buildMethodInjections(); return new ThriftStructMetadata( structName, extractStructIdlAnnotations(), structType, builderType, MetadataType.STRUCT, Optional.ofNullable(builderMethodInjection), ImmutableList.copyOf(documentation), ImmutableList.copyOf(fieldsMetadata), Optional.of(constructorInjections), methodInjections); } ThriftStructMetadataBuilder(ThriftCatalog catalog, Type structType); @Override ThriftStructMetadata build(); }### Answer: @Test public void testGenericBuilder() { Type structType = new TypeToken<GenericStruct<String>>() {}.getType(); ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), structType); builder.build(); } @Test(expectedExceptions = MetadataErrorException.class) public void testGenericBuilderForNonGenericStruct() { Type structType = new TypeToken<NonGenericStruct>() {}.getType(); ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), structType); builder.build(); } @Test public void testMergeableRequiredness() { ThriftStructMetadata metadata = new ThriftStructMetadataBuilder(new ThriftCatalog(), MergeableRequiredness.class).build(); assertThat(metadata.getField(1).getRequiredness()) .as("requiredness of field 'foo'") .isEqualTo(Requiredness.OPTIONAL); } @Test public void testNonFinalStructsOk() { ThriftStructMetadataBuilder builder = new ThriftStructMetadataBuilder(new ThriftCatalog(), NotFinalStruct.class); builder.build(); }
### Question: ThriftMethodMetadata { public Method getMethod() { return method; } ThriftMethodMetadata(Method method, ThriftCatalog catalog); String getName(); ThriftType getReturnType(); List<ThriftFieldMetadata> getParameters(); Set<ThriftHeaderParameter> getHeaderParameters(); Map<Short, ExceptionInfo> getExceptions(); Method getMethod(); boolean getOneway(); boolean isIdempotent(); List<String> getDocumentation(); boolean isAsync(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ThriftMethod .* parameter 1 must not be annotated with both @ThriftField and @ThriftHeader") public void invalidHeaderAndFieldParameter() { Method validHeaderWithInferredFieldIds = getMethod("invalidHeaderAndFieldParameter", boolean.class, String.class); new ThriftMethodMetadata(validHeaderWithInferredFieldIds, THRIFT_CATALOG); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "ThriftMethod .* parameter 1 annotated with @ThriftHeader must be a String") public void invalidHeaderType() { Method validHeaderWithInferredFieldIds = getMethod("invalidHeaderType", boolean.class, int.class); new ThriftMethodMetadata(validHeaderWithInferredFieldIds, THRIFT_CATALOG); }
### Question: ConnectionPool implements ConnectionManager { @Override public Future<Channel> getConnection(ConnectionParameters connectionParameters, HostAndPort address) { ConnectionKey key = new ConnectionKey(connectionParameters, address); while (true) { synchronized (this) { if (closed) { return group.next().newFailedFuture(new TTransportException("Connection pool is closed")); } Future<Channel> future; try { future = cachedConnections.get(key, () -> createConnection(key)); } catch (ExecutionException e) { throw new RuntimeException(e); } if (!future.isDone()) { return future; } Channel channel = future.getNow(); if (channel != null && channel.isOpen()) { return future; } cachedConnections.asMap().remove(key, future); } } } ConnectionPool(ConnectionManager connectionFactory, EventLoopGroup group, int maxSize, Duration idleTimeout); @Override Future<Channel> getConnection(ConnectionParameters connectionParameters, HostAndPort address); @Override void returnConnection(Channel connection); @Override synchronized void close(); }### Answer: @Test public void testPooling() { try (ConnectionPool pool = new ConnectionPool(new TestingConnectionManager(), new DefaultEventLoopGroup(), 10, new Duration(1, MINUTES))) { HostAndPort address1 = HostAndPort.fromParts("localhost", 1234); HostAndPort address2 = HostAndPort.fromParts("localhost", 4567); Channel channel1 = futureGet(pool.getConnection(PARAMETERS, address1)); Channel channel2 = futureGet(pool.getConnection(PARAMETERS, address1)); assertSame(channel1, channel2); Channel channel3 = futureGet(pool.getConnection(PARAMETERS, address2)); assertNotSame(channel1, channel3); Channel channel4 = futureGet(pool.getConnection(PARAMETERS, address1)); assertSame(channel1, channel4); } }
### Question: DriftServerConfig { @Config("thrift.server.stats.enabled") public DriftServerConfig setStatsEnabled(boolean statsEnabled) { this.statsEnabled = statsEnabled; return this; } boolean isStatsEnabled(); @Config("thrift.server.stats.enabled") DriftServerConfig setStatsEnabled(boolean statsEnabled); }### Answer: @Test public void testDefaults() { assertRecordedDefaults(recordDefaults(DriftServerConfig.class) .setStatsEnabled(true)); } @Test public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("thrift.server.stats.enabled", "false") .build(); DriftServerConfig expected = new DriftServerConfig() .setStatsEnabled(false); assertFullMapping(properties, expected); }
### Question: GenericJDBCConfigurationStore extends AbstractJDBCConfigurationStore implements MessageStoreProvider { @Override public void onDelete(final ConfiguredObject<?> parent) { assertState(CLOSED); ConnectionProvider connectionProvider = JdbcUtils.createConnectionProvider(parent, LOGGER); try { try (Connection conn = connectionProvider.getConnection()) { conn.setAutoCommit(true); onDelete(conn); } catch (SQLException e) { getLogger().error("Exception while deleting store tables", e); } } finally { try { connectionProvider.close(); } catch (SQLException e) { LOGGER.warn("Unable to close connection provider ", e); } } } GenericJDBCConfigurationStore(final Class<? extends ConfiguredObject> rootClass); @Override void init(ConfiguredObject<?> parent); @Override void upgradeStoreStructure(); @Override Connection getConnection(); @Override void closeConfigurationStore(); @Override void onDelete(final ConfiguredObject<?> parent); @Override String getSqlBigIntType(); @Override MessageStore getMessageStore(); PreferenceStore getPreferenceStore(); }### Answer: @Test public void testOnDelete() throws Exception { try (Connection connection = openConnection()) { GenericJDBCConfigurationStore store = (GenericJDBCConfigurationStore) getConfigurationStore(); Collection<String> expectedTables = Arrays.asList(store.getConfiguredObjectHierarchyTableName(), store.getConfiguredObjectsTableName()); assertTablesExistence(expectedTables, getTableNames(connection), true); store.closeConfigurationStore(); assertTablesExistence(expectedTables, getTableNames(connection), true); store.onDelete(getVirtualHostNode()); assertTablesExistence(expectedTables, getTableNames(connection), false); } }
### Question: EnvHomeRegistry { public synchronized void registerHome(final File home) throws StoreException { if (home == null) { throw new IllegalArgumentException("home parameter cannot be null"); } String canonicalForm = getCanonicalForm(home); if (_canonicalNames.contains(canonicalForm)) { throw new IllegalArgumentException("JE Home " + home + " is already in use"); } _canonicalNames.add(canonicalForm); } EnvHomeRegistry(); static final EnvHomeRegistry getInstance(); synchronized void registerHome(final File home); synchronized void deregisterHome(final File home); }### Answer: @Test public void testDuplicateEnvHomeRejected() throws Exception { File home = new File(UnitTestBase.TMP_FOLDER, getTestName()); _ehr.registerHome(home); try { _ehr.registerHome(home); fail("Exception not thrown"); } catch (IllegalArgumentException iae) { } } @Test public void testUniqueEnvHomesAllowed() throws Exception { File home1 = new File(UnitTestBase.TMP_FOLDER, getTestName() + "1"); File home2 = new File(UnitTestBase.TMP_FOLDER, getTestName() + "2"); _ehr.registerHome(home1); _ehr.registerHome(home2); }
### Question: StandardEnvironmentFacade implements EnvironmentFacade { @Override public void close() { try { _committer.stop(); closeSequences(); closeDatabases(); } finally { try { closeEnvironment(); } finally { EnvHomeRegistry.getInstance().deregisterHome(_environmentPath); } } } StandardEnvironmentFacade(StandardEnvironmentConfiguration configuration); @Override Transaction beginTransaction(TransactionConfig transactionConfig); @Override void commit(com.sleepycat.je.Transaction tx, boolean syncCommit); @Override ListenableFuture<X> commitAsync(final Transaction tx, final X val); @Override void close(); @Override long getTotalLogSize(); @Override void reduceSizeOnDisk(); @Override void flushLog(); @Override void setCacheSize(long cacheSize); @Override void flushLogFailed(final RuntimeException e); @Override void updateMutableConfig(final ConfiguredObject<?> object); @Override int cleanLog(); @Override void checkpoint(final boolean force); @Override Map<String,Map<String,Object>> getEnvironmentStatistics(boolean reset); @Override Map<String,Object> getDatabaseStatistics(String database, boolean reset); @Override void deleteDatabase(final String databaseName); @Override Map<String, Object> getTransactionStatistics(boolean reset); @Override void upgradeIfNecessary(ConfiguredObject<?> parent); @Override RuntimeException handleDatabaseException(String contextMessage, RuntimeException e); @Override Database openDatabase(String name, DatabaseConfig databaseConfig); @Override Database clearDatabase(Transaction txn, String databaseName, DatabaseConfig databaseConfig); @Override Sequence openSequence(final Database database, final DatabaseEntry sequenceKey, final SequenceConfig sequenceConfig); @Override void closeDatabase(final String name); }### Answer: @Test public void testSecondEnvironmentFacadeUsingSamePathRejected() throws Exception { EnvironmentFacade ef = createEnvironmentFacade(); assertNotNull("Environment should not be null", ef); try { createEnvironmentFacade(); fail("Exception not thrown"); } catch (IllegalArgumentException iae) { } ef.close(); EnvironmentFacade ef2 = createEnvironmentFacade(); assertNotNull("Environment should not be null", ef2); } @Test public void testClose() throws Exception { EnvironmentFacade ef = createEnvironmentFacade(); ef.close(); }
### Question: CompositeFilter extends Filter<ILoggingEvent> { public void addLogInclusionRule(LogBackLogInclusionRule logInclusionRule) { Filter<ILoggingEvent> f = logInclusionRule.asFilter(); f.setName(logInclusionRule.getName()); _filterList.add(f); } void addLogInclusionRule(LogBackLogInclusionRule logInclusionRule); void removeLogInclusionRule(LogBackLogInclusionRule logInclusionRule); @Override FilterReply decide(ILoggingEvent event); long getErrorCount(); long getWarnCount(); }### Answer: @Test public void testAddLogInclusionRule() { CompositeFilter compositeFilter = new CompositeFilter(); LogBackLogInclusionRule rule = createRule(FilterReply.ACCEPT, "accept"); compositeFilter.addLogInclusionRule(rule); verify(rule.asFilter()).setName("accept"); }
### Question: BDBMessageStore extends AbstractBDBMessageStore { @Override public void onDelete(ConfiguredObject<?> parent) { if (isMessageStoreOpen()) { throw new IllegalStateException("Cannot delete the store as store is still open"); } FileBasedSettings fileBasedSettings = (FileBasedSettings)parent; String storePath = fileBasedSettings.getStorePath(); if (storePath != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Deleting store : {}", storePath); } File configFile = new File(storePath); if (!FileUtils.delete(configFile, true)) { LOGGER.info("Failed to delete the store at location : {} ", storePath); } } } BDBMessageStore(); BDBMessageStore(EnvironmentFacadeFactory environmentFacadeFactory); @Override void onDelete(ConfiguredObject<?> parent); @Override EnvironmentFacade getEnvironmentFacade(); @Override String getStoreLocation(); @Override File getStoreLocationAsFile(); }### Answer: @Test public void testOnDelete() throws Exception { String storeLocation = getStore().getStoreLocation(); File location = new File(storeLocation); assertTrue("Store does not exist at " + storeLocation, location.exists()); getStore().closeMessageStore(); assertTrue("Store does not exist at " + storeLocation, location.exists()); BDBVirtualHost mockVH = mock(BDBVirtualHost.class); String testLocation = getStore().getStoreLocation(); when(mockVH.getStorePath()).thenReturn(testLocation); getStore().onDelete(mockVH); assertFalse("Store exists at " + storeLocation, location.exists()); }
### Question: StandardEnvironmentFacadeFactory implements EnvironmentFacadeFactory { @SuppressWarnings("unchecked") @Override public EnvironmentFacade createEnvironmentFacade(final ConfiguredObject<?> parent) { final FileBasedSettings settings = (FileBasedSettings)parent; final String storeLocation = settings.getStorePath(); StandardEnvironmentConfiguration sec = new StandardEnvironmentConfiguration() { @Override public String getName() { return parent.getName(); } @Override public String getStorePath() { return storeLocation; } @Override public CacheMode getCacheMode() { return BDBUtils.getCacheMode(parent); } @Override public Map<String, String> getParameters() { return BDBUtils.getEnvironmentConfigurationParameters(parent); } @Override public <T> T getFacadeParameter(final Class<T> clazz, final String parameterName, final T defaultValue) { return BDBUtils.getContextValue(parent, clazz, parameterName, defaultValue); } @Override public <T> T getFacadeParameter(final Class<T> paremeterClass, final Type type, final String parameterName, final T defaultValue) { return BDBUtils.getContextValue(parent, paremeterClass, type, parameterName, defaultValue); } }; return new StandardEnvironmentFacade(sec); } @SuppressWarnings("unchecked") @Override EnvironmentFacade createEnvironmentFacade(final ConfiguredObject<?> parent); }### Answer: @Test public void testCreateEnvironmentFacade() { when(_parent.getName()).thenReturn(getTestName()); when(_parent.getContextKeys(any(boolean.class))).thenReturn(Collections.singleton(EnvironmentConfig.ENV_IS_TRANSACTIONAL)); when(_parent.getContextValue(String.class, EnvironmentConfig.ENV_IS_TRANSACTIONAL)).thenReturn("false"); StandardEnvironmentFacadeFactory factory = new StandardEnvironmentFacadeFactory(); EnvironmentFacade facade = factory.createEnvironmentFacade(_parent); try { facade.beginTransaction(null); fail("Context variables were not picked up on environment creation"); } catch(UnsupportedOperationException e) { } }
### Question: AMQShortString implements Comparable<AMQShortString> { @Override public boolean equals(Object o) { if (o == this) { return true; } if(o instanceof AMQShortString) { return equals((AMQShortString) o); } return false; } private AMQShortString(byte[] data); static String readAMQShortStringAsString(QpidByteBuffer buffer); static AMQShortString readAMQShortString(QpidByteBuffer buffer); static AMQShortString createAMQShortString(byte[] data); static AMQShortString createAMQShortString(String string); int length(); char charAt(int index); byte[] getBytes(); void writeToBuffer(QpidByteBuffer buffer); static void writeShortString(final QpidByteBuffer buffer, final String data); @Override boolean equals(Object o); boolean equals(final AMQShortString otherString); @Override int hashCode(); @Override String toString(); @Override int compareTo(AMQShortString name); boolean contains(final byte b); static AMQShortString validValueOf(Object obj); static AMQShortString valueOf(Object obj); static AMQShortString valueOf(String obj); static String toString(AMQShortString amqShortString); static final int MAX_LENGTH; static final AMQShortString EMPTY_STRING; }### Answer: @Test public void testEquals() { assertEquals(GOODBYE, AMQShortString.createAMQShortString("Goodbye")); assertEquals(AMQShortString.createAMQShortString("A"), AMQShortString.createAMQShortString("A")); assertFalse(AMQShortString.createAMQShortString("A").equals(AMQShortString.createAMQShortString("a"))); }
### Question: AMQShortString implements Comparable<AMQShortString> { public static AMQShortString createAMQShortString(byte[] data) { if (data == null) { throw new NullPointerException("Cannot create AMQShortString with null data[]"); } final AMQShortString cached = getShortStringCache().getIfPresent(ByteBuffer.wrap(data)); return cached != null ? cached : new AMQShortString(data); } private AMQShortString(byte[] data); static String readAMQShortStringAsString(QpidByteBuffer buffer); static AMQShortString readAMQShortString(QpidByteBuffer buffer); static AMQShortString createAMQShortString(byte[] data); static AMQShortString createAMQShortString(String string); int length(); char charAt(int index); byte[] getBytes(); void writeToBuffer(QpidByteBuffer buffer); static void writeShortString(final QpidByteBuffer buffer, final String data); @Override boolean equals(Object o); boolean equals(final AMQShortString otherString); @Override int hashCode(); @Override String toString(); @Override int compareTo(AMQShortString name); boolean contains(final byte b); static AMQShortString validValueOf(Object obj); static AMQShortString valueOf(Object obj); static AMQShortString valueOf(String obj); static String toString(AMQShortString amqShortString); static final int MAX_LENGTH; static final AMQShortString EMPTY_STRING; }### Answer: @Test public void testCreateAMQShortStringStringOver255() { String test = buildString('a', 256); try { AMQShortString.createAMQShortString(test); fail("It should not be possible to create AMQShortString with length over 255"); } catch (IllegalArgumentException e) { assertEquals("Exception message differs from expected", "Cannot create AMQShortString with number of octets over 255!", e.getMessage()); } }
### Question: AMQMessageMutator implements ServerMessageMutator<AMQMessage> { @Override public void setPriority(final byte priority) { _basicContentHeaderProperties.setPriority(priority); } AMQMessageMutator(final AMQMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override AMQMessage create(); }### Answer: @Test public void setPriority() { _messageMutator.setPriority((byte) (TEST_PRIORITY + 1)); assertThat(_messageMutator.getPriority(), is(equalTo((byte) (TEST_PRIORITY + 1)))); }
### Question: AMQMessageMutator implements ServerMessageMutator<AMQMessage> { @Override public byte getPriority() { return _basicContentHeaderProperties.getPriority(); } AMQMessageMutator(final AMQMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override AMQMessage create(); }### Answer: @Test public void getPriority() { assertThat((int) _messageMutator.getPriority(), is(equalTo((int) TEST_PRIORITY))); }
### Question: AMQMessageMutator implements ServerMessageMutator<AMQMessage> { @Override public AMQMessage create() { final long contentSize = _message.getSize(); final QpidByteBuffer content = _message.getContent(); final ContentHeaderBody contentHeader = new ContentHeaderBody(_basicContentHeaderProperties, contentSize); final MessageMetaData messageMetaData = new MessageMetaData(_message.getMessagePublishInfo(), contentHeader, _message.getArrivalTime()); final MessageHandle<MessageMetaData> handle = _messageStore.addMessage(messageMetaData); if (content != null) { handle.addContent(content); } return new AMQMessage(handle.allContentAdded(), _message.getConnectionReference()); } AMQMessageMutator(final AMQMessage message, final MessageStore messageStore); @Override void setPriority(final byte priority); @Override byte getPriority(); @Override AMQMessage create(); }### Answer: @Test public void create() { _messageMutator.setPriority((byte) (TEST_PRIORITY + 1)); AMQMessage newMessage = _messageMutator.create(); assertThat(newMessage.getMessageHeader().getPriority(), is(equalTo((byte) (TEST_PRIORITY + 1)))); assertThat(newMessage.getMessageHeader().getMimeType(), is(equalTo(TEST_CONTENT_TYPE))); assertThat(newMessage.getMessageHeader().getHeader(TEST_HEADER_NAME), is(equalTo(TEST_HEADER_VALUE))); QpidByteBuffer content = newMessage.getContent(); final byte[] bytes = new byte[content.remaining()]; content.copyTo(bytes); assertThat(new String(bytes, UTF_8), is(equalTo(TEST_CONTENT))); }
### Question: FieldTable { @Override public String toString() { return _fieldTableSupport.toString(); } FieldTable(QpidByteBuffer input, int len); FieldTable(QpidByteBuffer buffer); FieldTable(Map<String, Object> properties); FieldTable(FieldTableSupport fieldTableSupport); @Override String toString(); void writeToBuffer(QpidByteBuffer buffer); byte[] getDataAsBytes(); long getEncodedSize(); static Map<String, Object> convertToMap(final FieldTable fieldTable); void dispose(); int size(); boolean isEmpty(); boolean containsKey(String key); Set<String> keys(); Object get(String key); @Override boolean equals(final Object o); @Override int hashCode(); static FieldTable convertToFieldTable(Map<String, Object> map); static FieldTable convertToDecodedFieldTable(final FieldTable fieldTable); void validate(); }### Answer: @Test public void testCheckPropertyNameHasMaxLength() { StringBuilder longPropertyName = new StringBuilder(129); for (int i = 0; i < 129; i++) { longPropertyName.append("x"); } boolean strictAMQP = FieldTable._strictAMQP; try { FieldTable._strictAMQP = true; new FieldTable(Collections.singletonMap(longPropertyName.toString(), "String")); fail("property name must be < 128 characters"); } catch (IllegalArgumentException iae) { } finally { FieldTable._strictAMQP = strictAMQP; } }
### Question: FieldTable { public void validate() { _fieldTableSupport.validate(); } FieldTable(QpidByteBuffer input, int len); FieldTable(QpidByteBuffer buffer); FieldTable(Map<String, Object> properties); FieldTable(FieldTableSupport fieldTableSupport); @Override String toString(); void writeToBuffer(QpidByteBuffer buffer); byte[] getDataAsBytes(); long getEncodedSize(); static Map<String, Object> convertToMap(final FieldTable fieldTable); void dispose(); int size(); boolean isEmpty(); boolean containsKey(String key); Set<String> keys(); Object get(String key); @Override boolean equals(final Object o); @Override int hashCode(); static FieldTable convertToFieldTable(Map<String, Object> map); static FieldTable convertToDecodedFieldTable(final FieldTable fieldTable); void validate(); }### Answer: @Test public void testValidateMalformedFieldTable() { final FieldTable fieldTable = buildMalformedFieldTable(); try { fieldTable.validate(); fail("Exception is expected"); } catch (RuntimeException e) { } }
### Question: QpidException extends Exception { @Override public String toString() { return getClass().getName() + ": " + getMessage(); } QpidException(String msg); QpidException(String msg, Throwable cause); @Override String toString(); QpidException cloneForCurrentThread(); @Override QpidException clone(); }### Answer: @Test public void testGetMessageAsString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 25; i++) { sb.append("message [" + i + "]"); } AMQException e = new AMQException(ErrorCodes.INTERNAL_ERROR, sb.toString(), null); AMQShortString message = AMQShortString.validValueOf(e.getMessage()); assertEquals(sb.substring(0, AMQShortString.MAX_LENGTH - 3) + "...", message.toString()); }
### Question: HttpManagement extends AbstractPluginAdapter<HttpManagement> implements HttpManagementConfiguration<HttpManagement>, PortManager { @Override public int getSessionTimeout() { return _sessionTimeout; } @ManagedObjectFactoryConstructor HttpManagement(Map<String, Object> attributes, Broker broker); @Override int getSessionTimeout(); @Override String getCorsAllowOrigins(); @Override Set<String> getCorsAllowMethods(); @Override String getCorsAllowHeaders(); @Override boolean getCorsAllowCredentials(); @Override int getBoundPort(final HttpPort httpPort); @Override int getNumberOfAcceptors(HttpPort httpPort); @Override int getNumberOfSelectors(HttpPort httpPort); @Override SSLContext getSSLContext(final HttpPort httpPort); @Override boolean updateSSLContext(final HttpPort httpPort); @Override boolean isHttpsSaslAuthenticationEnabled(); @Override boolean isHttpSaslAuthenticationEnabled(); @Override boolean isHttpsBasicAuthenticationEnabled(); @Override boolean isHttpBasicAuthenticationEnabled(); @Override boolean isCompressResponses(); @Override AuthenticationProvider getAuthenticationProvider(HttpServletRequest request); @SuppressWarnings("unused") static Set<String> getAllAvailableCorsMethodCombinations(); @Override HttpPort<?> getPort(final HttpServletRequest request); @Override long getSaslExchangeExpiry(); static final int DEFAULT_TIMEOUT_IN_SECONDS; static final String TIME_OUT; static final String HTTP_BASIC_AUTHENTICATION_ENABLED; static final String HTTPS_BASIC_AUTHENTICATION_ENABLED; static final String HTTP_SASL_AUTHENTICATION_ENABLED; static final String HTTPS_SASL_AUTHENTICATION_ENABLED; static final String PLUGIN_TYPE; static final String DEFAULT_LOGOUT_URL; static final String DEFAULT_LOGIN_URL; @ManagedAttributeField public String _corsAllowOrigins; @ManagedAttributeField public Set<String> _corsAllowMethods; @ManagedAttributeField public String _corsAllowHeaders; @ManagedAttributeField public boolean _corsAllowCredentials; }### Answer: @Test public void testGetSessionTimeout() { assertEquals("Unexpected session timeout", 10000l, (long) _management.getSessionTimeout()); }
### Question: HttpManagement extends AbstractPluginAdapter<HttpManagement> implements HttpManagementConfiguration<HttpManagement>, PortManager { @Override public boolean isHttpBasicAuthenticationEnabled() { return _httpBasicAuthenticationEnabled; } @ManagedObjectFactoryConstructor HttpManagement(Map<String, Object> attributes, Broker broker); @Override int getSessionTimeout(); @Override String getCorsAllowOrigins(); @Override Set<String> getCorsAllowMethods(); @Override String getCorsAllowHeaders(); @Override boolean getCorsAllowCredentials(); @Override int getBoundPort(final HttpPort httpPort); @Override int getNumberOfAcceptors(HttpPort httpPort); @Override int getNumberOfSelectors(HttpPort httpPort); @Override SSLContext getSSLContext(final HttpPort httpPort); @Override boolean updateSSLContext(final HttpPort httpPort); @Override boolean isHttpsSaslAuthenticationEnabled(); @Override boolean isHttpSaslAuthenticationEnabled(); @Override boolean isHttpsBasicAuthenticationEnabled(); @Override boolean isHttpBasicAuthenticationEnabled(); @Override boolean isCompressResponses(); @Override AuthenticationProvider getAuthenticationProvider(HttpServletRequest request); @SuppressWarnings("unused") static Set<String> getAllAvailableCorsMethodCombinations(); @Override HttpPort<?> getPort(final HttpServletRequest request); @Override long getSaslExchangeExpiry(); static final int DEFAULT_TIMEOUT_IN_SECONDS; static final String TIME_OUT; static final String HTTP_BASIC_AUTHENTICATION_ENABLED; static final String HTTPS_BASIC_AUTHENTICATION_ENABLED; static final String HTTP_SASL_AUTHENTICATION_ENABLED; static final String HTTPS_SASL_AUTHENTICATION_ENABLED; static final String PLUGIN_TYPE; static final String DEFAULT_LOGOUT_URL; static final String DEFAULT_LOGIN_URL; @ManagedAttributeField public String _corsAllowOrigins; @ManagedAttributeField public Set<String> _corsAllowMethods; @ManagedAttributeField public String _corsAllowHeaders; @ManagedAttributeField public boolean _corsAllowCredentials; }### Answer: @Test public void testIsHttpBasicAuthenticationEnabled() { assertEquals("Unexpected value for the http basic authentication enabled attribute", false, _management.isHttpBasicAuthenticationEnabled()); }
### Question: LoginLogoutReporter implements HttpSessionBindingListener { @Override public void valueBound(HttpSessionBindingEvent arg0) { reportLogin(); } LoginLogoutReporter(Subject subject, EventLoggerProvider eventLoggerProvider); @Override void valueBound(HttpSessionBindingEvent arg0); @Override void valueUnbound(HttpSessionBindingEvent arg0); EventLogger getEventLogger(); }### Answer: @Test public void testLoginLogged() { _loginLogoutReport.valueBound(null); verify(_logger).message(isLogMessageWithMessage("MNG-1007 : Open : User mockusername")); }
### Question: LoginLogoutReporter implements HttpSessionBindingListener { @Override public void valueUnbound(HttpSessionBindingEvent arg0) { reportLogout(); } LoginLogoutReporter(Subject subject, EventLoggerProvider eventLoggerProvider); @Override void valueBound(HttpSessionBindingEvent arg0); @Override void valueUnbound(HttpSessionBindingEvent arg0); EventLogger getEventLogger(); }### Answer: @Test public void testLogoutLogged() { _loginLogoutReport.valueUnbound(null); verify(_logger).message(isLogMessageWithMessage("MNG-1008 : Close : User mockusername")); }
### Question: CSVFormat { public <T extends Collection<?>> void printRecord(final Appendable out, final T record) throws IOException { boolean newRecord = true; for (Object item : record) { print(out, item, newRecord); newRecord = false; } println(out); } CSVFormat(); private CSVFormat(final char delimiter, final Character quoteCharacter, final String recordSeparator); void printRecord(final Appendable out, final T record); void printRecords(final Appendable out, final C records); void println(final Appendable out); void print(final Appendable out, final Object value, final boolean newRecord); void printComments(final Appendable out, final String... comments); }### Answer: @Test public void testPrintRecord() throws Exception { CSVFormat csvFormat = new CSVFormat(); final StringWriter out = new StringWriter(); csvFormat.printRecord(out, Arrays.asList("test", 1, true, "\"quoted\" test")); assertEquals("Unexpected format", String.format("%s,%d,%b,%s%s", "test", 1, true, "\"\"\"quoted\"\" test\"", "\r\n"), out.toString()); }
### Question: CSVFormat { public <C extends Collection<? extends Collection<?>>> void printRecords(final Appendable out, final C records) throws IOException { for (Collection<?> record : records) { printRecord(out, record); } } CSVFormat(); private CSVFormat(final char delimiter, final Character quoteCharacter, final String recordSeparator); void printRecord(final Appendable out, final T record); void printRecords(final Appendable out, final C records); void println(final Appendable out); void print(final Appendable out, final Object value, final boolean newRecord); void printComments(final Appendable out, final String... comments); }### Answer: @Test public void testPrintRecords() throws Exception { CSVFormat csvFormat = new CSVFormat(); final StringWriter out = new StringWriter(); csvFormat.printRecords(out, Arrays.asList(Arrays.asList("test", 1, true, "\"quoted\" test"), Arrays.asList("delimeter,test", 1.0f, false, "quote\" in the middle"))); assertEquals("Unexpected format", String.format("%s,%d,%b,%s%s%s,%s,%b,%s%s", "test", 1, true, "\"\"\"quoted\"\" test\"", "\r\n", "\"delimeter,test\"", "1.0", false, "\"quote\"\" in the middle\"", "\r\n"), out.toString()); }
### Question: CSVFormat { public void println(final Appendable out) throws IOException { if (_recordSeparator != null) { out.append(_recordSeparator); } } CSVFormat(); private CSVFormat(final char delimiter, final Character quoteCharacter, final String recordSeparator); void printRecord(final Appendable out, final T record); void printRecords(final Appendable out, final C records); void println(final Appendable out); void print(final Appendable out, final Object value, final boolean newRecord); void printComments(final Appendable out, final String... comments); }### Answer: @Test public void testPrintln() throws Exception { CSVFormat csvFormat = new CSVFormat(); final StringWriter out = new StringWriter(); csvFormat.println(out); assertEquals("Unexpected new line", "\r\n", out.toString()); }
### Question: CSVFormat { public void print(final Appendable out, final Object value, final boolean newRecord) throws IOException { CharSequence charSequence; if (value == null) { charSequence = EMPTY; } else if (value instanceof CharSequence) { charSequence = (CharSequence) value; } else if (value instanceof Date || value instanceof Calendar) { final Date time = value instanceof Calendar ? ((Calendar) value).getTime() : (Date) value; charSequence = DATE_TIME_FORMATTER.format(time.toInstant().atZone(ZoneId.systemDefault())); } else { charSequence = value.toString(); } this.print(out, value, charSequence, 0, charSequence.length(), newRecord); } CSVFormat(); private CSVFormat(final char delimiter, final Character quoteCharacter, final String recordSeparator); void printRecord(final Appendable out, final T record); void printRecords(final Appendable out, final C records); void println(final Appendable out); void print(final Appendable out, final Object value, final boolean newRecord); void printComments(final Appendable out, final String... comments); }### Answer: @Test public void testPrint() throws Exception { CSVFormat csvFormat = new CSVFormat(); final StringWriter out = new StringWriter(); csvFormat.print(out, "test", true); csvFormat.print(out, 1, false); csvFormat.print(out, true, false); csvFormat.print(out, "\"quoted\" test", false); assertEquals("Unexpected format ", String.format("%s,%d,%b,%s", "test", 1, true, "\"\"\"quoted\"\" test\""), out.toString()); } @Test public void testDate() throws Exception { Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); CSVFormat csvFormat = new CSVFormat(); final StringWriter out = new StringWriter(); csvFormat.print(out, date, true); assertEquals("Unexpected format ", simpleDateFormat.format(date), out.toString()); }
### Question: CSVFormat { public void printComments(final Appendable out, final String... comments) throws IOException { for (String comment: comments) { out.append(COMMENT).append(SP).append(comment); println(out); } } CSVFormat(); private CSVFormat(final char delimiter, final Character quoteCharacter, final String recordSeparator); void printRecord(final Appendable out, final T record); void printRecords(final Appendable out, final C records); void println(final Appendable out); void print(final Appendable out, final Object value, final boolean newRecord); void printComments(final Appendable out, final String... comments); }### Answer: @Test public void testPrintComments() throws Exception { CSVFormat csvFormat = new CSVFormat(); final StringWriter out = new StringWriter(); csvFormat.printComments(out, "comment1", "comment2"); assertEquals("Unexpected format of comments", String.format("# %s%s# %s%s", "comment1", "\r\n", "comment2", "\r\n"), out.toString()); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public Collection<String> getAttributeNames() { return _nextVersionLegacyConfiguredObject.getAttributeNames(); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getAttributeNames() { final Collection<String> attributeNames = Arrays.asList("foo", "bar", "test"); when(_nextVersionLegacyConfiguredObject.getAttributeNames()).thenReturn(attributeNames); Collection<String> names = _object.getAttributeNames(); assertThat(names, is(equalTo(attributeNames))); verify(_nextVersionLegacyConfiguredObject).getAttributeNames(); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public Object getAttribute(final String name) { return convertLegacyConfiguredObjectIfRequired(_nextVersionLegacyConfiguredObject.getAttribute(name)); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getAttribute() { final String attributeName = "name"; final String attributeValue = "test"; when(_nextVersionLegacyConfiguredObject.getAttribute(attributeName)).thenReturn(attributeValue); final Object value = _object.getAttribute(attributeName); assertThat(value, is(equalTo(attributeValue))); verify(_nextVersionLegacyConfiguredObject).getAttribute(attributeName); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public Object getActualAttribute(final String name) { return _nextVersionLegacyConfiguredObject.getActualAttribute(name); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getActualAttribute() { final String attributeName = "name"; final String attributeValue = "test"; when(_nextVersionLegacyConfiguredObject.getActualAttribute(attributeName)).thenReturn(attributeValue); final Object value = _object.getActualAttribute(attributeName); assertThat(value, is(equalTo(attributeValue))); verify(_nextVersionLegacyConfiguredObject).getActualAttribute(attributeName); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public String getCategory() { return _category; } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getCategory() { assertThat(_object.getCategory(), is(equalTo(CATEGORY))); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure) { ManagementResponse result = _nextVersionLegacyConfiguredObject.invoke(operation, parameters, isSecure); return convertLegacyConfiguredObjectIfRequired(result); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void invoke() { final String operationName = "testOperation"; final Map<String, Object> operationArguments = Collections.singletonMap("arg", "argValue"); final String operationResult = "testOperationResult"; final ControllerManagementResponse managementResponse = new ControllerManagementResponse( ResponseType.DATA, operationResult); when(_nextVersionLegacyConfiguredObject.invoke(operationName, operationArguments, true)).thenReturn(managementResponse); final ManagementResponse result = _object.invoke(operationName, operationArguments, true); assertThat(result, is(notNullValue())); assertThat(result.getResponseCode(), is(equalTo(200))); assertThat(result.getBody(), is(equalTo(operationResult))); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public LegacyConfiguredObject getNextVersionConfiguredObject() { return _nextVersionLegacyConfiguredObject; } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getNextVersionConfiguredObject() { assertThat(_object.getNextVersionConfiguredObject(), is(equalTo(_nextVersionLegacyConfiguredObject))); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public LegacyConfiguredObject getParent(final String category) { LegacyConfiguredObject parent = _nextVersionLegacyConfiguredObject.getParent(category); return _managementController.convertFromNextVersion(parent); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getParent() { final String parentCategory = "testParentCategory"; final LegacyConfiguredObject nextVersionParent = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject nextVersionParentConverted = mock(LegacyConfiguredObject.class); when(_nextVersionLegacyConfiguredObject.getParent(parentCategory)).thenReturn(nextVersionParent); when(_managementController.convertFromNextVersion(nextVersionParent)).thenReturn( nextVersionParentConverted); final LegacyConfiguredObject parent = _object.getParent(parentCategory); assertThat(parent, is(equalTo(nextVersionParentConverted))); verify(_nextVersionLegacyConfiguredObject).getParent(parentCategory); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public boolean isSecureAttribute(final String name) { return _nextVersionLegacyConfiguredObject.isSecureAttribute(name); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void isSecureAttribute() { final String attributeName = "testAttribute"; when(_nextVersionLegacyConfiguredObject.isSecureAttribute(attributeName)).thenReturn(true); assertThat(_object.isSecureAttribute(attributeName), is(equalTo(true))); verify(_nextVersionLegacyConfiguredObject).isSecureAttribute(attributeName); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public boolean isOversizedAttribute(final String name) { return _nextVersionLegacyConfiguredObject.isOversizedAttribute(name); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void isOversizedAttribute() { final String attributeName = "testAttribute"; when(_nextVersionLegacyConfiguredObject.isOversizedAttribute(attributeName)).thenReturn(true); assertThat(_object.isOversizedAttribute(attributeName), is(equalTo(true))); verify(_nextVersionLegacyConfiguredObject).isOversizedAttribute(attributeName); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public String getContextValue(final String contextKey) { return _nextVersionLegacyConfiguredObject.getContextValue(contextKey); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getContextValue() { final String contextName = "testContext"; final String contextValue = "testValue"; when(_nextVersionLegacyConfiguredObject.getContextValue(contextName)).thenReturn(contextValue); assertThat(_object.getContextValue(contextName), is(equalTo(contextValue))); verify(_nextVersionLegacyConfiguredObject).getContextValue(contextName); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { @Override public Map<String, Object> getStatistics() { return _nextVersionLegacyConfiguredObject.getStatistics(); } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getStatistics() { Map<String, Object> stats = Collections.singletonMap("testStat", "statValue"); when(_nextVersionLegacyConfiguredObject.getStatistics()).thenReturn(stats); assertThat(_object.getStatistics(), is(equalTo(stats))); verify(_nextVersionLegacyConfiguredObject).getStatistics(); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { public LegacyManagementController getManagementController() { return _managementController; } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getManagementController() { assertThat(_object.getManagementController(), is(equalTo(_managementController))); }
### Question: GenericLegacyConfiguredObject implements LegacyConfiguredObject { protected LegacyConfiguredObject getNextVersionLegacyConfiguredObject() { return _nextVersionLegacyConfiguredObject; } GenericLegacyConfiguredObject(final LegacyManagementController managementController, final LegacyConfiguredObject nextVersionLegacyConfiguredObject, final String category); @Override Collection<String> getAttributeNames(); @Override Object getAttribute(final String name); @Override Object getActualAttribute(final String name); @Override Collection<LegacyConfiguredObject> getChildren(final String category); @Override String getCategory(); @Override ManagementResponse invoke(final String operation, final Map<String, Object> parameters, final boolean isSecure); @Override LegacyConfiguredObject getNextVersionConfiguredObject(); @Override LegacyConfiguredObject getParent(final String category); @Override boolean isSecureAttribute(final String name); @Override boolean isOversizedAttribute(final String name); @Override String getContextValue(final String contextKey); @Override Map<String, Object> getStatistics(); @Override boolean equals(final Object o); @Override int hashCode(); LegacyManagementController getManagementController(); }### Answer: @Test public void getNextVersionLegacyConfiguredObject() { assertThat(_object.getNextVersionConfiguredObject(), is(equalTo(_nextVersionLegacyConfiguredObject))); }
### Question: LegacyManagementController extends AbstractLegacyConfiguredObjectController { @Override public Map<String, List<String>> convertQueryParameters(final Map<String, List<String>> requestParameters) { Map<String, List<String>> params = requestParameters .entrySet() .stream() .filter(e -> !INCLUDE_SYS_CONTEXT_PARAM.equals(e.getKey()) && !INHERITED_ACTUALS_PARAM.equals(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<String, List<String>> parameters = new HashMap<>(params); boolean excludeInheritedContext = isInheritedContextExcluded(params); parameters.put(EXCLUDE_INHERITED_CONTEXT_PARAM, Collections.singletonList(String.valueOf(excludeInheritedContext))); if (!parameters.containsKey(DEPTH_PARAM)) { parameters.put(DEPTH_PARAM, Collections.singletonList("1")); } return parameters; } LegacyManagementController(final ManagementController nextVersionManagementController); @Override Object get(final ConfiguredObject<?> root, final String category, final List<String> path, final Map<String, List<String>> parameters); @Override Map<String, List<String>> convertQueryParameters(final Map<String, List<String>> requestParameters); @Override Object formatConfiguredObject(final Object content, final Map<String, List<String>> parameters, final boolean isSecureOrAllowedOnInsecureChannel); }### Answer: @Test public void convertQueryParameters() { final Map<String, List<String>> parameters = Collections.singletonMap("actuals", Collections.singletonList("true")); final Map<String, List<String>> converted = _controller.convertQueryParameters(parameters); assertThat(converted, is(notNullValue())); assertThat(converted.get("excludeInheritedContext"), is(equalTo(Collections.singletonList("true")))); }
### Question: LegacyManagementController extends AbstractLegacyConfiguredObjectController { @Override public Object get(final ConfiguredObject<?> root, final String category, final List<String> path, final Map<String, List<String>> parameters) throws ManagementException { Object result = super.get(root, category, path, convertQueryParameters(parameters)); if (result instanceof LegacyConfiguredObject) { return Collections.singletonList(result); } return result; } LegacyManagementController(final ManagementController nextVersionManagementController); @Override Object get(final ConfiguredObject<?> root, final String category, final List<String> path, final Map<String, List<String>> parameters); @Override Map<String, List<String>> convertQueryParameters(final Map<String, List<String>> requestParameters); @Override Object formatConfiguredObject(final Object content, final Map<String, List<String>> parameters, final boolean isSecureOrAllowedOnInsecureChannel); }### Answer: @Test public void get() { final List<String> path = Collections.emptyList(); final LegacyConfiguredObject object = mock(LegacyConfiguredObject.class); final Map<String, List<String>> parameters = Collections.emptyMap(); final ConfiguredObject<?> root = mock(ConfiguredObject.class); when(_nextVersionManagementController.get(eq(root), eq(BrokerController.TYPE), eq(path), any())).thenReturn(object); final Object result = _controller.get(root, BrokerController.TYPE, path, parameters); assertThat(result, is(instanceOf(Collection.class))); Collection data = (Collection) result; assertThat(data.size(), is(equalTo(1))); Object obj = data.iterator().next(); assertThat(obj, is(instanceOf(LegacyConfiguredObject.class))); assertThat(((LegacyConfiguredObject)obj).getCategory(), is(equalTo(BrokerController.TYPE))); }
### Question: PortController extends LegacyCategoryController { @Override protected LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new LegacyPort(getManagementController(), object); } PortController(final LegacyManagementController legacyManagementController, final Set<TypeController> typeControllers); @Override Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes); static final String TYPE; }### Answer: @Test public void convertNextVersionLegacyConfiguredObject() { final LegacyConfiguredObject nextVersionPort = mock(LegacyConfiguredObject.class); when(nextVersionPort.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("test"); when(nextVersionPort.getAttribute(LegacyConfiguredObject.TYPE)).thenReturn("HTTP"); Map<String, String> context = new HashMap<>(); context.put("qpid.port.http.acceptBacklog", "2000"); when(nextVersionPort.getAttribute(LegacyConfiguredObject.CONTEXT)).thenReturn(context); final LegacyConfiguredObject converted = _portController.convertNextVersionLegacyConfiguredObject(nextVersionPort); assertThat(converted, is(notNullValue())); assertThat(converted.getCategory(), is(equalTo(PortController.TYPE))); assertThat(converted.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("test"))); assertThat(converted.getAttribute(LegacyConfiguredObject.TYPE), is(equalTo("HTTP"))); Object contextObject = converted.getAttribute(LegacyConfiguredObject.CONTEXT); assertThat(contextObject, is(instanceOf(Map.class))); Map<?,?> convertedContext = (Map<?,?>)contextObject; assertThat(convertedContext.get("port.http.maximumQueuedRequests"), is(equalTo("2000"))); }
### Question: SessionController extends LegacyCategoryController { @Override protected LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new LegacySession(getManagementController(), object); } SessionController(final LegacyManagementController legacyManagementController, final Set<TypeController> typeControllers); static final String TYPE; }### Answer: @Test public void convertNextVersionLegacyConfiguredObject() { final UUID sessionID = UUID.randomUUID(); final LegacyConfiguredObject nextVersionSession = mock(LegacyConfiguredObject.class); final LegacyConfiguredObject nextVersionConsumer = mock(LegacyConfiguredObject.class); when(nextVersionSession.getCategory()).thenReturn(SessionController.TYPE); when(nextVersionSession.getAttribute(LegacyConfiguredObject.ID)).thenReturn(sessionID); final ManagementResponse operationResult = new ControllerManagementResponse(ResponseType.MODEL_OBJECT, Collections.singletonList( nextVersionConsumer)); when(nextVersionSession.invoke(eq("getConsumers"), eq(Collections.emptyMap()), eq(true))).thenReturn( operationResult); final LegacyConfiguredObject convertedConsumer = mock(LegacyConfiguredObject.class); when(_legacyManagementController.convertFromNextVersion(nextVersionConsumer)).thenReturn(convertedConsumer); final LegacyConfiguredObject convertedSession = _sessionController.convertNextVersionLegacyConfiguredObject(nextVersionSession); assertThat(convertedSession.getAttribute(LegacyConfiguredObject.ID), is(equalTo(sessionID))); final Collection<LegacyConfiguredObject> consumers = convertedSession.getChildren(ConsumerController.TYPE); assertThat(consumers, is(notNullValue())); assertThat(consumers.size(), is(equalTo(1))); assertThat(consumers.iterator().next(), is(equalTo(convertedConsumer))); }
### Question: LegacyCategoryControllerFactory implements CategoryControllerFactory { @Override public Set<String> getSupportedCategories() { return SUPPORTED_CATEGORIES; } @Override CategoryController createController(final String type, final LegacyManagementController legacyManagementController); @Override Set<String> getSupportedCategories(); @Override String getModelVersion(); @Override String getType(); }### Answer: @Test public void getSupportedCategories() { assertThat(_factory.getSupportedCategories(), is(equalTo(LegacyCategoryControllerFactory.SUPPORTED_CATEGORIES))); }
### Question: VirtualHostController extends LegacyCategoryController { @Override public LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new VirtualHostController.LegacyVirtualHost(getManagementController(), object); } VirtualHostController(final LegacyManagementController legacyManagementController, final Set<TypeController> typeControllers); @Override LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object); @Override @SuppressWarnings("unchecked") Map<String, Object> convertAttributesToNextVersion(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes); static final String TYPE; }### Answer: @Test public void convertNextVersionLegacyConfiguredObject() { final LegacyConfiguredObject nextVersionVirtualHost = mock(LegacyConfiguredObject.class); when(nextVersionVirtualHost.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("test"); final LegacyConfiguredObject converted = _virtualHostController.convertNextVersionLegacyConfiguredObject(nextVersionVirtualHost); assertThat(converted, is(notNullValue())); assertThat(converted.getCategory(), is(equalTo(VirtualHostController.TYPE))); assertThat(converted.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("test"))); assertThat(converted.getAttribute("modelVersion"), is(equalTo("6.1"))); assertThat(converted.getAttribute("queue_deadLetterQueueEnabled"), is(equalTo(false))); }
### Question: BrokerController extends LegacyCategoryController { @Override public LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new LegacyBroker(getManagementController(), object); } BrokerController(final LegacyManagementController legacyManagementController, final Set<TypeController> typeControllers); @Override LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object); static final String TYPE; }### Answer: @Test public void convertNextVersionLegacyConfiguredObject() { final LegacyConfiguredObject object = mock(LegacyConfiguredObject.class); when(object.getAttribute("modelVersion")).thenReturn("foo"); final Map<String, String> context = new HashMap<>(); context.put("qpid.port.sessionCountLimit", "512"); context.put("qpid.port.heartbeatDelay", "10000"); context.put("qpid.port.closeWhenNoRoute", "true"); when(object.getAttribute("context")).thenReturn(context); final BrokerController controller = new BrokerController(_legacyVersionManagementController, Collections.emptySet()); assertThat(controller.getCategory(), is(equalTo("Broker"))); final LegacyConfiguredObject converted = controller.convertFromNextVersion(object); assertThat(converted.getAttribute("modelVersion"), is(equalTo(MODEL_VERSION))); assertThat(converted.getAttribute("connection.sessionCountLimit"), is(equalTo(512))); assertThat(converted.getAttribute("connection.heartBeatDelay"), is(equalTo(10000L))); assertThat(converted.getAttribute("connection.closeWhenNoRoute"), is(equalTo(true))); }
### Question: LegacyCategoryController extends GenericCategoryController { @Override public String[] getParentCategories() { return _parentCategories; } LegacyCategoryController(final LegacyManagementController managementController, final String name, final String[] parentCategories, final String defaultType, final Set<TypeController> typeControllers); @Override String[] getParentCategories(); }### Answer: @Test public void getParentCategories() { assertThat(_controller.getParentCategories(), is(equalTo(new String[]{BrokerController.TYPE}))); }
### Question: LegacyCategoryController extends GenericCategoryController { @Override protected LegacyConfiguredObject convertNextVersionLegacyConfiguredObject(final LegacyConfiguredObject object) { return new GenericLegacyConfiguredObject(getManagementController(), object, getCategory()); } LegacyCategoryController(final LegacyManagementController managementController, final String name, final String[] parentCategories, final String defaultType, final Set<TypeController> typeControllers); @Override String[] getParentCategories(); }### Answer: @Test public void convertNextVersionLegacyConfiguredObject() { final LegacyConfiguredObject node = mock(LegacyConfiguredObject.class); when(node.getAttribute(LegacyConfiguredObject.NAME)).thenReturn("test"); final LegacyConfiguredObject converted = _controller.convertNextVersionLegacyConfiguredObject(node); assertThat(converted, is(notNullValue())); assertThat(converted.getCategory(), is(equalTo(VirtualHostNode.TYPE))); assertThat(converted.getAttribute(LegacyConfiguredObject.NAME), is(equalTo("test"))); }
### Question: ConsumerController implements CategoryController { @Override public String getCategory() { return TYPE; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getCategory() { assertThat(_controller.getCategory(), is(equalTo("Consumer"))); }
### Question: ConsumerController implements CategoryController { @Override public String getNextVersionCategory() { return TYPE; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getNextVersionCategory() { assertThat(_controller.getNextVersionCategory(), is(equalTo("Consumer"))); }
### Question: ConsumerController implements CategoryController { @Override public String getDefaultType() { return null; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getDefaultType() { assertThat(_controller.getDefaultType(), is(equalTo(null))); }
### Question: ConsumerController implements CategoryController { @Override public String[] getParentCategories() { return new String[]{SessionController.TYPE, QueueController.TYPE}; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getParentCategories() { assertThat(_controller.getParentCategories(), is(equalTo(new String[]{"Session", "Queue"}))); }
### Question: ConsumerController implements CategoryController { @Override public LegacyManagementController getManagementController() { return _managementController; } ConsumerController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override int delete(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getManagementController() { assertThat(_controller.getManagementController(), is(equalTo(_managementController))); }
### Question: BindingController implements CategoryController { @Override public String getCategory() { return TYPE; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes, final boolean isPost); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getCategory() { assertThat(_controller.getCategory(), is(equalTo("Binding"))); }
### Question: BindingController implements CategoryController { @Override public String getNextVersionCategory() { return null; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes, final boolean isPost); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getNextVersionCategory() { assertThat(_controller.getNextVersionCategory(), is(equalTo(null))); }
### Question: BindingController implements CategoryController { @Override public String getDefaultType() { return null; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes, final boolean isPost); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getDefaultType() { assertThat(_controller.getDefaultType(), is(equalTo(null))); }
### Question: BindingController implements CategoryController { @Override public String[] getParentCategories() { return new String[]{ExchangeController.TYPE, QueueController.TYPE}; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes, final boolean isPost); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getParentCategories() { assertThat(_controller.getParentCategories(), is(equalTo(new String[]{"Exchange", "Queue"}))); }
### Question: BindingController implements CategoryController { @Override public LegacyManagementController getManagementController() { return _managementController; } BindingController(final LegacyManagementController managementController); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override String[] getParentCategories(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(final ConfiguredObject<?> root, final List<String> path, final Map<String, Object> attributes, final boolean isPost); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(ConfiguredObject<?> root, List<String> path, String operation, Map<String, Object> parameters, boolean isPost, final boolean isSecure); @Override Object getPreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override void setPreferences(ConfiguredObject<?> root, List<String> path, Object preferences, Map<String, List<String>> parameters, boolean isPost); @Override int deletePreferences(ConfiguredObject<?> root, List<String> path, Map<String, List<String>> parameters); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject nextVersionObject); static final String TYPE; }### Answer: @Test public void getManagementController() { assertThat(_controller.getManagementController(), is(equalTo(_managementController))); }
### Question: LegacyManagementController extends AbstractLegacyConfiguredObjectController { @Override protected Map<String, List<String>> convertQueryParameters(final Map<String, List<String>> parameters) { return parameters; } LegacyManagementController(final ManagementController nextVersionManagementController, final String modelVersion); @Override Object formatConfiguredObject(final Object content, final Map<String, List<String>> parameters, final boolean isSecureOrAllowedOnInsecureChannel); }### Answer: @Test public void convertQueryParameters() { final Map<String, List<String>> parameters = Collections.singletonMap("depth", Collections.singletonList("1")); final Map<String, List<String>> converted = _controller.convertQueryParameters(parameters); assertThat(converted, is(equalTo(parameters))); }
### Question: LegacyCategoryControllerFactory implements CategoryControllerFactory { @Override public CategoryController createController(final String type, final LegacyManagementController legacyManagementController) { if (SUPPORTED_CATEGORIES.containsKey(type)) { return new LegacyCategoryController(legacyManagementController, type, SUPPORTED_CATEGORIES.get(type), DEFAULT_TYPES.get(type), legacyManagementController.getTypeControllersByCategory(type)); } else { throw new IllegalArgumentException(String.format("Unsupported type '%s'", type)); } } @Override CategoryController createController(final String type, final LegacyManagementController legacyManagementController); @Override Set<String> getSupportedCategories(); @Override String getModelVersion(); @Override String getType(); static final String CATEGORY_BROKER; static final String CATEGORY_AUTHENTICATION_PROVIDER; static final String CATEGORY_PORT; static final String CATEGORY_VIRTUAL_HOST; static final Map<String, String> SUPPORTED_CATEGORIES; static final Map<String, String> DEFAULT_TYPES; }### Answer: @Test public void createController() { SUPPORTED_CATEGORIES.keySet().forEach(category-> { final CategoryController controller = _factory.createController(category, _nextVersionManagementController); assertThat(controller.getCategory(), is(equalTo(category))); }); }
### Question: GenericCategoryController implements CategoryController { @Override public String getCategory() { return _name; } protected GenericCategoryController(final LegacyManagementController managementController, final ManagementController nextVersionManagementController, final String name, final String defaultType, final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root, final List<String> path, final String operation, final Map<String, Object> parameters, final boolean isPost, final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root, final List<String> path, final Object preferences, final Map<String, List<String>> parameters, final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); }### Answer: @Test public void getCategory() { assertThat(_controller.getCategory(), is(equalTo(TEST_CATEGORY))); }
### Question: GenericCategoryController implements CategoryController { @Override public String getDefaultType() { return _defaultType; } protected GenericCategoryController(final LegacyManagementController managementController, final ManagementController nextVersionManagementController, final String name, final String defaultType, final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root, final List<String> path, final String operation, final Map<String, Object> parameters, final boolean isPost, final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root, final List<String> path, final Object preferences, final Map<String, List<String>> parameters, final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); }### Answer: @Test public void getDefaultType() { assertThat(_controller.getDefaultType(), is(equalTo(DEFAULT_TYPE))); }
### Question: GenericCategoryController implements CategoryController { @Override public LegacyManagementController getManagementController() { return _managementController; } protected GenericCategoryController(final LegacyManagementController managementController, final ManagementController nextVersionManagementController, final String name, final String defaultType, final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root, final List<String> path, final String operation, final Map<String, Object> parameters, final boolean isPost, final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root, final List<String> path, final Object preferences, final Map<String, List<String>> parameters, final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); }### Answer: @Test public void getManagementController() { assertThat(_controller.getManagementController(), is(equalTo(_managementController))); }
### Question: GenericCategoryController implements CategoryController { protected ManagementController getNextVersionManagementController() { return _nextVersionManagementController; } protected GenericCategoryController(final LegacyManagementController managementController, final ManagementController nextVersionManagementController, final String name, final String defaultType, final Set<TypeController> typeControllers); @Override String getCategory(); @Override String getNextVersionCategory(); @Override String getDefaultType(); @Override LegacyManagementController getManagementController(); @Override Object get(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override LegacyConfiguredObject createOrUpdate(ConfiguredObject<?> root, List<String> path, Map<String, Object> attributes, boolean isPost); @Override LegacyConfiguredObject convertFromNextVersion(final LegacyConfiguredObject object); @Override int delete(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override ManagementResponse invoke(final ConfiguredObject<?> root, final List<String> path, final String operation, final Map<String, Object> parameters, final boolean isPost, final boolean isSecure); @Override Object getPreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); @Override @SuppressWarnings("unchecked") void setPreferences(final ConfiguredObject<?> root, final List<String> path, final Object preferences, final Map<String, List<String>> parameters, final boolean isPost); @Override int deletePreferences(final ConfiguredObject<?> root, final List<String> path, final Map<String, List<String>> parameters); }### Answer: @Test public void getNextVersionManagementController() { assertThat(_controller.getNextVersionManagementController(), is(equalTo(_nextVersionManagementController))); }
### Question: StringTypeConstructor extends VariableWidthTypeConstructor<String> { @Override public String construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException { int size; if (!in.hasRemaining(getSize())) { throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct string: insufficient input data"); } if (getSize() == 1) { size = in.getUnsignedByte(); } else { size = in.getInt(); } if (!in.hasRemaining(size)) { throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct string: insufficient input data"); } byte[] data = new byte[size]; in.get(data); ByteBuffer buffer = ByteBuffer.wrap(data); String cached = getCache().getIfPresent(buffer); if (cached == null) { cached = new String(data, UTF_8); getCache().put(buffer, cached); } return cached; } private StringTypeConstructor(int size); static StringTypeConstructor getInstance(int i); @Override String construct(final QpidByteBuffer in, final ValueHandler handler); }### Answer: @Test public void construct() throws Exception { StringTypeConstructor constructor = StringTypeConstructor.getInstance(1); Cache<ByteBuffer, String> original = StringTypeConstructor.getCache(); Cache<ByteBuffer, String> cache = CacheBuilder.newBuilder().maximumSize(2).build(); StringTypeConstructor.setCache(cache); try { String string1 = constructor.construct(QpidByteBuffer.wrap(new byte[]{4, 't', 'e', 's', 't'}), null); String string2 = constructor.construct(QpidByteBuffer.wrap(new byte[]{4, 't', 'e', 's', 't'}), null); assertEquals(string1, string2); assertSame(string1, string2); } finally { cache.cleanUp(); StringTypeConstructor.setCache(original); } }
### Question: ReportRunner { public static ReportRunner<?> createRunner(final String reportName, final Map<String, String[]> parameterMap) { QueueReport<?> report = getReport(reportName); setReportParameters(report, parameterMap); return new ReportRunner<>(report); } private ReportRunner(final QueueReport<T> report); boolean isBinaryReport(); static ReportRunner<?> createRunner(final String reportName, final Map<String, String[]> parameterMap); String getContentType(); final T runReport(Queue<?> queue); }### Answer: @Test public void testInvalidReportName() { try { ReportRunner.createRunner("unknown", Collections.<String, String[]>emptyMap()); fail("Unknown report name should throw exception"); } catch(IllegalArgumentException e) { assertEquals("Unknown report: unknown", e.getMessage()); } }