method2testcases
stringlengths
118
3.08k
### Question: NetworkUtil { public static boolean mapTcpPort(int port) { try { GatewayDiscover discover = new GatewayDiscover(); discover.discover(); GatewayDevice device = discover.getValidGateway(); if (device != null) { PortMappingEntry portMapping = new PortMappingEntry(); if (device.getSpecificPortMappingEntry(por...
### Question: ResourceUtil { public static Map<Object, Object> loadPropertiesFromUrl(URL url) throws RuntimeException { InputStream is = null; try { is = url.openStream(); Properties properties = new Properties(); properties.load(is); return properties; } catch (IOException e) { throw new RuntimeException("Cannot load ...
### Question: HeapUnit { public static HeapImage captureHeap() throws IOException { String path = "target/heapunit/" + System.currentTimeMillis() + ".hprof"; return new SimpleHeapImage(HeapDumpProcuder.makeHeapDump(path, TimeUnit.SECONDS.toMillis(60))); } static HeapImage captureHeap(); }### Answer: @Test public void...
### Question: InMemoryRoutingTable implements RoutingTable<R> { @Override public Optional<R> removeRoute(final InterledgerAddressPrefix addressPrefix) { Objects.requireNonNull(addressPrefix); return this.interledgerAddressPrefixMap.removeEntry(addressPrefix); } InMemoryRoutingTable(); InMemoryRoutingTable(final Interl...
### Question: InMemoryRoutingTable implements RoutingTable<R> { @Override public Optional<R> getRouteByPrefix(final InterledgerAddressPrefix addressPrefix) { Objects.requireNonNull(addressPrefix); return this.interledgerAddressPrefixMap.getEntry(addressPrefix); } InMemoryRoutingTable(); InMemoryRoutingTable(final Inte...
### Question: InMemoryRoutingTable implements RoutingTable<R> { @Override public void forEach(final BiConsumer<InterledgerAddressPrefix, R> action) { Objects.requireNonNull(action); this.interledgerAddressPrefixMap.forEach(action); } InMemoryRoutingTable(); InMemoryRoutingTable(final InterledgerAddressPrefixMap interl...
### Question: InMemoryRoutingTable implements RoutingTable<R> { @Override public Optional<R> findNextHopRoute(final InterledgerAddress interledgerAddress) { Objects.requireNonNull(interledgerAddress, "finalDestinationAddress must not be null!"); return this.interledgerAddressPrefixMap.findNextHop(interledgerAddress); }...
### Question: ConnectorServer extends Server { @Override public void start() { super.start(); if (SpringProfileUtils.isProfileActive(getContext().getEnvironment(), "MIGRATE-ONLY")) { System.out.println("###################################################################"); System.out.println("!!! Container started with...
### Question: InDatabaseStreamPaymentManager implements StreamPaymentManager { @Override public Optional<StreamPayment> findByAccountIdAndStreamPaymentId(AccountId accountId, String streamPaymentId) { return streamPaymentsRepository.findByAccountIdAndStreamPaymentId(accountId, streamPaymentId) .map(streamPaymentFromEnt...
### Question: InDatabaseStreamPaymentManager implements StreamPaymentManager { @Override public List<StreamPayment> findByAccountId(AccountId accountId, PageRequest pageRequest) { return streamPaymentsRepository.findByAccountIdOrderByCreatedDateDesc(accountId, pageRequest) .stream() .map(streamPaymentFromEntityConverte...
### Question: AccountSettingsLoadingCache implements AccountSettingsCache { @Subscribe @SuppressWarnings("PMD.UnusedPublicMethod") public void _handleAccountUpdated(AccountUpdatedEvent event) { this.accountSettingsCache.invalidate(event.accountId()); } @VisibleForTesting AccountSettingsLoadingCache(final AccountSettin...
### Question: PrometheusMetricsService implements MetricsService { @Override public void trackNumRateLimitedPackets(final AccountSettings accountSettings) { Objects.requireNonNull(accountSettings); PrometheusCollectors.rateLimitedPackets.labels( accountSettings.accountId().value(), accountSettings.assetCode(), stringif...
### Question: DefaultAccessTokenManager implements AccessTokenManager { @Override public AccessToken createToken(AccountId accountId) { String newRandomToken = Base64.getEncoder().encodeToString(UUID.randomUUID().toString().getBytes()); AccessTokenEntity newEntity = new AccessTokenEntity(); newEntity.setAccountId(accou...
### Question: ApplicationContextProvider implements ApplicationContextAware { public static Set<ApplicationContext> getAllApplicationContexts() { return findActiveContexts(ctx); } static Set<ApplicationContext> getAllApplicationContexts(); void setApplicationContext(ApplicationContext ctx); }### Answer: @Test public ...
### Question: StreamPacketUtils { public static Optional<Denomination> getDenomination(StreamPacket streamPacket) { return streamPacket.frames().stream() .filter(frame -> frame.streamFrameType().equals(StreamFrameType.ConnectionAssetDetails)) .map(frame -> ((ConnectionAssetDetailsFrame) frame)) .map(ConnectionAssetDeta...
### Question: StreamPacketUtils { public static boolean hasCloseFrame(StreamPacket streamPacket) { return streamPacket.frames().stream() .map(StreamFrame::streamFrameType) .anyMatch(CLOSING_FRAMES::contains); } static Optional<Denomination> getDenomination(StreamPacket streamPacket); static boolean hasCloseFrame(Strea...
### Question: StreamPacketUtils { public static Optional<InterledgerAddress> getSourceAddress(StreamPacket streamPacket) { return streamPacket.frames().stream() .filter(frame -> frame.streamFrameType().equals(StreamFrameType.ConnectionNewAddress)) .map(frame -> ((ConnectionNewAddressFrame) frame).sourceAddress()) .filt...
### Question: AccountBalanceService { public AccountBalanceResponse getAccountBalance(final AccountId accountId) { Objects.requireNonNull(accountId); return accountSettingsRepository.findByAccountIdWithConversion(accountId) .map(settings -> AccountBalanceResponse.builder() .accountBalance(balanceTracker.balance(account...
### Question: ApplicationContextProvider implements ApplicationContextAware { @VisibleForTesting static Set<ApplicationContext> findActiveContexts(Set<ApplicationContext> contexts) { return contexts.stream() .filter(ctx -> ctx instanceof ConfigurableApplicationContext) .map(ctx -> (ConfigurableApplicationContext) ctx) ...
### Question: DefaultPacketEventPublisher implements PacketEventPublisher { @Override public void publishRejectionByNextHop(AccountSettings sourceAccountSettings, AccountSettings nextHopAccountSettings, InterledgerPreparePacket preparePacket, InterledgerPreparePacket nextHopPacket, BigDecimal fxRate, InterledgerRejectP...
### Question: DefaultPacketEventPublisher implements PacketEventPublisher { @Override public void publishRejectionByConnector(AccountSettings sourceAccountSettings, InterledgerPreparePacket preparePacket, InterledgerRejectPacket rejectPacket) { eventBus.post(PacketRejectionEvent.builder() .accountSettings(sourceAccount...
### Question: DefaultPacketEventPublisher implements PacketEventPublisher { @Override public void publishFulfillment(AccountSettings sourceAccountSettings, AccountSettings nextHopAccountSettings, InterledgerPreparePacket preparePacket, InterledgerPreparePacket nextHopPacket, BigDecimal fxRate, InterledgerFulfillment fu...
### Question: DefaultPacketSwitchFilterChain implements PacketSwitchFilterChain { @VisibleForTesting Link computeLink(final AccountSettings nextHopAccountSettings, final InterledgerAddress destinationAddress) { if (localDestinationAddressUtils.isLocalSpspDestinationAddress(destinationAddress)) { return this.linkManager...
### Question: EthCurrencyProvider implements CurrencyProviderSpi { @Override public Set<CurrencyUnit> getCurrencies(CurrencyQuery query) { if (query.isEmpty() || query.getCurrencyCodes().contains(ETH)) { return currencyUnits; } return Collections.emptySet(); } EthCurrencyProvider(); @Override Set<CurrencyUnit> getCurre...
### Question: DropRoundingProvider implements RoundingProviderSpi { public Set<String> getRoundingNames() { return roundingNames; } DropRoundingProvider(); MonetaryRounding getRounding(RoundingQuery query); Set<String> getRoundingNames(); }### Answer: @Test public void getRoundingNames() { assertThat(dropRoundingProvi...
### Question: CryptoCompareRateProvider extends AbstractRateProvider { @Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { Objects.requireNonNull(conversionQuery); try { return this.exchangeRateCache.get(conversionQuery, fxLoader()); } catch (Exception e) { throw new MonetaryException("Fail...
### Question: XrpCurrencyProvider implements CurrencyProviderSpi { @Override public Set<CurrencyUnit> getCurrencies(CurrencyQuery query) { if (query.isEmpty() || query.getCurrencyCodes().contains(XRP)) { return currencyUnits; } return Collections.emptySet(); } XrpCurrencyProvider(); @Override Set<CurrencyUnit> getCurre...
### Question: SpringProfileUtils { public static boolean isProfileActive(Environment environment, String profile) { return Arrays.asList(environment.getActiveProfiles()) .stream() .anyMatch(active -> active.trim().equalsIgnoreCase(profile.trim())); } static boolean isProfileActive(Environment environment, String profi...
### Question: DefaultNextHopPacketMapper implements NextHopPacketMapper { @VisibleForTesting protected Instant lesser(final Instant first, final Instant second) { if (first.isBefore(second)) { return first; } else { return second; } } DefaultNextHopPacketMapper( final Supplier<ConnectorSettings> connectorSettingsSu...
### Question: SettlementEngineIdempotencyKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { if (target != null && SettlementController.class.isAssignableFrom(target.getClass())) { Preconditions.checkArgument(params.length > 0, "params is expected to...
### Question: ByteArrayUtils { public static byte[] generate32RandomBytes() { final byte[] rndBytes = new byte[32]; secureRandom.nextBytes(rndBytes); return rndBytes; } static boolean isEqualUsingConstantTime(byte[] val1, byte[] val2); static byte[] generate32RandomBytes(); }### Answer: @Test public void generateRand...
### Question: CoordinationEventBusBridge { @Subscribe public void onCoordinatedEvent(AbstractCoordinatedEvent event) { publish(event); } CoordinationEventBusBridge(CoordinationMessagePublisher coordinationMessagePublisher, EventBus eventBus); @Subscribe void onCoordinatedEvent(AbstractCoordinatedEvent event); }### Ans...
### Question: RuntimeUtils { public static boolean gcpProfileEnabled(final Environment environment) { Objects.requireNonNull(environment); return Arrays.stream(environment.getActiveProfiles()) .anyMatch(Runtimes.GCP::equalsIgnoreCase); } static boolean gcpProfileEnabled(final Environment environment); static Optional<...
### Question: RuntimeUtils { public static Optional<String> getGoogleCloudProjectId() { return Optional.ofNullable(System.getenv().get(GOOGLE_CLOUD_PROJECT)) .filter(projectId -> !projectId.isEmpty()); } static boolean gcpProfileEnabled(final Environment environment); static Optional<String> getGoogleCloudProjectId();...
### Question: OerPreparePacketHttpMessageConverter extends AbstractGenericHttpMessageConverter<InterledgerPacket> implements HttpMessageConverter<InterledgerPacket> { @Override public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) { if (contextClass != null && IlpHttpController.class.isAssignabl...
### Question: MetaDataController { @RequestMapping( path = PathConstants.SLASH, method = RequestMethod.GET, produces = {APPLICATION_JSON_VALUE, MediaTypes.PROBLEM_VALUE} ) public ResponseEntity<ConnectorSettingsResponse> getConnectorMetaData() { return new ResponseEntity<>(ConnectorSettingsResponse.builder() .operatorA...
### Question: DelegatingEncryptionService implements EncryptionService { @Override public KeyStoreType keyStoreType() { return serviceMap.values().stream().map(EncryptionService::keyStoreType).findFirst().get(); } DelegatingEncryptionService(final Set<EncryptionService> encryptionServices); @Override KeyStoreType keySt...
### Question: JwksUtils { public static HttpUrl getJwksUrl(HttpUrl issuerUrl) { HttpUrl.Builder builder = new HttpUrl.Builder() .scheme(issuerUrl.scheme()) .host(issuerUrl.host()) .port(issuerUrl.port()); issuerUrl.pathSegments().forEach(builder::addPathSegment); return builder.addPathSegment(".well-known") .addPathSeg...
### Question: BearerTokenSecurityContextRepository implements SecurityContextRepository { @Override public boolean containsContext(HttpServletRequest request) { return parseToken(request).isPresent() && parseAccountId(request).isPresent(); } BearerTokenSecurityContextRepository(byte[] ephemeralBytes); @Override Securit...
### Question: BearerTokenSecurityContextRepository implements SecurityContextRepository { @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { SecurityContext context = SecurityContextHolder.createEmptyContext(); parseToken(requestResponseHolder.getRequest()).ifPresent(token -...
### Question: AsnUuidCodec extends AsnOctetStringBasedObjectCodec<UUID> { @VisibleForTesting protected final static byte[] getBytesFromUUID(final UUID uuid) { final ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return bb.array(); } ...
### Question: DelegatingEncryptionService implements EncryptionService { @Override public byte[] decrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] cipherMessage) { return getDelegate(keyMetadata).decrypt(keyMetadata, encryptionAlgorithm, cipherMessage); } DelegatingEncryptionService(final...
### Question: CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public LinkId getLinkId() { return this.linkDelegate.getLinkId(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, final CircuitB...
### Question: CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public Supplier<InterledgerAddress> getOperatorAddressSupplier() { return this.linkDelegate.getOperatorAddressSupplier(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreaking...
### Question: CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public LinkSettings getLinkSettings() { return this.linkDelegate.getLinkSettings(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, ...
### Question: CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public void registerLinkHandler(LinkHandler dataHandler) throws LinkHandlerAlreadyRegisteredException { this.linkDelegate.registerLinkHandler(dataHandler); } @VisibleForTesting CircuitBreakingLink(final Link<...
### Question: CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public Optional<LinkHandler> getLinkHandler() { return this.linkDelegate.getLinkHandler(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDel...
### Question: CircuitBreakingLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public void unregisterLinkHandler() { this.linkDelegate.unregisterLinkHandler(); } @VisibleForTesting CircuitBreakingLink(final Link<?> linkDelegate); CircuitBreakingLink( final Link<?> linkDelegate, ...
### Question: StaticRouteEntityConverter implements Converter<StaticRouteEntity, StaticRoute> { @Override public StaticRoute convert(StaticRouteEntity staticRouteEntity) { Objects.requireNonNull(staticRouteEntity); return StaticRoute.builder() .nextHopAccountId(staticRouteEntity.getBoxedAccountId()) .routePrefix(static...
### Question: AccountBalanceSettingsEntityConverter implements Converter<AccountBalanceSettingsEntity, AccountBalanceSettings> { @Override public AccountBalanceSettings convert(final AccountBalanceSettingsEntity accountSettingsEntity) { Objects.requireNonNull(accountSettingsEntity); return AccountBalanceSettings.buil...
### Question: RateLimitSettingsEntityConverter implements Converter<AccountRateLimitSettingsEntity, AccountRateLimitSettings> { @Override public AccountRateLimitSettings convert(final AccountRateLimitSettingsEntity entity) { return AccountRateLimitSettings.builder() .maxPacketsPerSecond(entity.getMaxPacketsPerSecond())...
### Question: FxRateOverridesEntityConverter implements Converter<FxRateOverrideEntity, FxRateOverride> { @Override public FxRateOverride convert(FxRateOverrideEntity rateOverrideEntity) { Objects.requireNonNull(rateOverrideEntity); return FxRateOverride.builder() .id(rateOverrideEntity.getId()) .assetCodeFrom(rateOver...
### Question: SettlementEngineDetailsEntityConverter implements Converter<SettlementEngineDetailsEntity, SettlementEngineDetails> { @Override public SettlementEngineDetails convert(final SettlementEngineDetailsEntity settlementEngineDetailsEntity) { Objects.requireNonNull(settlementEngineDetailsEntity); return Settle...
### Question: InMemoryForwardingRoutingTable extends InMemoryRoutingTable<RouteUpdate> implements ForwardingRoutingTable<RouteUpdate> { @Override public void clearRouteInLogAtEpoch(final int epoch) { this.routeUpdateLog.put(epoch, null); } InMemoryForwardingRoutingTable(); @Override RoutingTableId getRoutingTableId()...
### Question: InMemoryForwardingRoutingTable extends InMemoryRoutingTable<RouteUpdate> implements ForwardingRoutingTable<RouteUpdate> { @Override public void setEpochValue(final int epoch, final RouteUpdate routeUpdate) { Objects.requireNonNull(routeUpdate); this.routeUpdateLog.put(epoch, routeUpdate); if (epoch != g...
### Question: DelegatingEncryptionService implements EncryptionService { @Override public EncryptedSecret encrypt(KeyMetadata keyMetadata, EncryptionAlgorithm encryptionAlgorithm, byte[] plainText) { return getDelegate(keyMetadata).encrypt(keyMetadata, encryptionAlgorithm, plainText); } DelegatingEncryptionService(fina...
### Question: InMemoryForwardingRoutingTable extends InMemoryRoutingTable<RouteUpdate> implements ForwardingRoutingTable<RouteUpdate> { @Override public Iterable<RouteUpdate> getPartialRouteLog(final int numberToSkip, final int limit) { return Iterables.limit(Iterables.skip(this.routeUpdateLog.values(), numberToSkip)...
### Question: DefaultRouteBroadcaster implements RouteBroadcaster { @Override public Optional<RoutableAccount> getCcpEnabledAccount(final AccountId accountId) { Objects.requireNonNull(accountId); return Optional.ofNullable(this.ccpEnabledAccounts.get(accountId)); } DefaultRouteBroadcaster( final Supplier<ConnectorS...
### Question: DefaultRouteBroadcaster implements RouteBroadcaster { @Override public Stream<RoutableAccount> getAllCcpEnabledAccounts() { return this.ccpEnabledAccounts.values().stream(); } DefaultRouteBroadcaster( final Supplier<ConnectorSettings> connectorSettingsSupplier, final CodecContext ccpCodecContext, ...
### Question: InterledgerAddressPrefixMap { public R putEntry(final InterledgerAddressPrefix addressPrefix, final R entry) { Objects.requireNonNull(entry); synchronized (prefixMap) { return prefixMap.put(toTrieKey(addressPrefix), entry); } } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerA...
### Question: DelegatingEncryptionService implements EncryptionService { @Override public <T> T withDecrypted(EncryptedSecret encryptedSecret, Function<byte[], T> callable) { return getDelegate(encryptedSecret.keyMetadata()).withDecrypted(encryptedSecret, callable); } DelegatingEncryptionService(final Set<EncryptionSer...
### Question: InterledgerAddressPrefixMap { public Optional<R> getEntry(final InterledgerAddressPrefix addressPrefix) { Objects.requireNonNull(addressPrefix, "addressPrefix must not be null!"); return Optional.ofNullable(this.prefixMap.get(toTrieKey(addressPrefix))); } InterledgerAddressPrefixMap(); int getNumKeys(); R...
### Question: InterledgerAddressPrefixMap { public void forEach(final BiConsumer<? super InterledgerAddressPrefix, R> action) { Objects.requireNonNull(action); final BiConsumer<String, R> translatedAction = (ilpPrefixAsString, entry) -> { final String strippedPrefix; if (ilpPrefixAsString.endsWith(".")) { strippedPrefi...
### Question: InterledgerAddressPrefixMap { public Set<InterledgerAddressPrefix> getKeys() { return this.prefixMap.keySet().stream() .map(this::stripTrailingDot) .map(InterledgerAddressPrefix::of) .collect(Collectors.toSet()); } InterledgerAddressPrefixMap(); int getNumKeys(); R putEntry(final InterledgerAddressPrefix ...
### Question: InMemoryRoutingTable implements RoutingTable<R> { @Override public R addRoute(final R route) { Objects.requireNonNull(route); return this.interledgerAddressPrefixMap.putEntry(route.routePrefix(), route); } InMemoryRoutingTable(); InMemoryRoutingTable(final InterledgerAddressPrefixMap interledgerAddressPr...
### Question: AttractionCollection { public int getHeaderTitle() { return headerTitle; } AttractionCollection(int headerTextResId, List<Attraction> listOfAttractions); int getHeaderTitle(); List<Attraction> getAttractions(); }### Answer: @Test public void saveResIdAsHeaderTitle() { assertThat(subject.getHeaderTitle(),...
### Question: AttractionCollection { public List<Attraction> getAttractions() { return listOfAttractions; } AttractionCollection(int headerTextResId, List<Attraction> listOfAttractions); int getHeaderTitle(); List<Attraction> getAttractions(); }### Answer: @Test public void savesAttractionType_getAttractions() { asser...
### Question: Attraction implements Parcelable { public int getImageResourceId() { return imageResourceId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @O...
### Question: Attraction implements Parcelable { public int getTitle() { return titleTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Override voi...
### Question: Attraction implements Parcelable { public int getShortDesc() { return shortDescTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Over...
### Question: Attraction implements Parcelable { public int getLongDesc() { return longDescTextResId; } Attraction(int imageResourceId, int titleTextResId, int shortDescTextResId, int longDescTextResId, int mapQueryStrId); protected Attraction(Parcel in); @Override int describeContents(); @Overri...
### Question: AttractionRepository { @VisibleForTesting static AttractionCollection buildBreweriesCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.new_belgium, R.string.new_belgium_title, R.string.new_belgium_free_tours, R.string.new_belgium_detailed_desc,...
### Question: ToDoController { @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html") public String dashboard() { return "dashboard"; } @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html") String dashboard(); @RequestMapping(value = "/todo/listdata", method = Reque...
### Question: ProfileController { @RequestMapping(value = "/profile", method = RequestMethod.GET, produces = "text/html") public String showProfile() { return "profile"; } @RequestMapping(value = "/profile", method = RequestMethod.GET, produces = "text/html") String showProfile(); }### Answer: @Test public void testS...
### Question: TracingKafkaUtils { public static void inject(SpanContext spanContext, Headers headers, Tracer tracer) { tracer.inject(spanContext, Format.Builtin.TEXT_MAP, new HeadersMapInjectAdapter(headers)); } static SpanContext extractSpanContext(Headers headers, Tracer tracer); static void inject(SpanContext spanC...
### Question: TracingKafkaUtils { public static SpanContext extractSpanContext(Headers headers, Tracer tracer) { return tracer .extract(Format.Builtin.TEXT_MAP, new HeadersMapExtractAdapter(headers)); } static SpanContext extractSpanContext(Headers headers, Tracer tracer); static void inject(SpanContext spanContext, H...
### Question: HeadersMapExtractAdapter implements TextMap { @Override public Iterator<Entry<String, String>> iterator() { return map.entrySet().iterator(); } HeadersMapExtractAdapter(Headers headers); @Override Iterator<Entry<String, String>> iterator(); @Override void put(String key, String value); }### Answer: @Test...
### Question: RateThisApp { @Deprecated public static void onStart(Context context) { onCreate(context); } static void init(Config config); static void setCallback(Callback callback); static void onCreate(Context context); @Deprecated static void onStart(Context context); static boolean showRateDialogIfNeeded(final Co...
### Question: RateThisApp { public static void stopRateDialog(final Context context){ setOptOut(context, true); } static void init(Config config); static void setCallback(Callback callback); static void onCreate(Context context); @Deprecated static void onStart(Context context); static boolean showRateDialogIfNeeded(f...
### Question: DateTrigger implements Trigger { @Override public Date nextExecutionTime(TriggerContext triggerContext) { Date result = null; if (nextFireDates.size() > 0) { try { result = nextFireDates.remove(0); } catch (IndexOutOfBoundsException e) { logger.debug(e.getMessage()); } } return result; } DateTrigger(Date....
### Question: ShellWordsParser { List<String> parse(String s) { List<String> words = new ArrayList<>(); String field = ""; Matcher matcher = SHELLWORDS.matcher(s); while (matcher.find()) { String word = matcher.group(1); String sq = matcher.group(2); String dq = matcher.group(3); String esc = matcher.group(4); String g...
### Question: MappedAnalytic implements Analytic<I, O> { @Override @SuppressWarnings("unchecked") public O evaluate(I input) { Assert.notNull(input, "input"); MI modelInput = inputMapper.mapInput((A) this, input); MO modelOutput = evaluateInternal(modelInput); O output = outputMapper.mapOutput((A) this, input, modelOut...
### Question: CommonUtils { public static boolean isValidEmail(String emailAddress) { return emailAddress.matches(EMAIL_VALIDATION_REGEX); } private CommonUtils(); static String padRight(String inputString, int size, char paddingChar); static String padRight(String string, int size); static String collectionToCommaDel...
### Question: CommonUtils { public static String padRight(String inputString, int size, char paddingChar) { final String stringToPad; if (inputString == null) { stringToPad = ""; } else { stringToPad = inputString; } StringBuilder padded = new StringBuilder(stringToPad); while (padded.length() < size) { padded.append(p...
### Question: CommonUtils { public static String maskPassword(String password) { int lengthOfPassword = password.length(); StringBuilder stringBuilder = new StringBuilder(lengthOfPassword); for (int i = 0; i < lengthOfPassword; i++) { stringBuilder.append('*'); } return stringBuilder.toString(); } private CommonUtils(...
### Question: LibreOfficeLauncherHelper { public static String getOperatingSystem(String operatingSystemIndentifier) { if ("linux".equalsIgnoreCase(operatingSystemIndentifier)) { return OS_LINUX; } if (operatingSystemIndentifier != null && operatingSystemIndentifier.toLowerCase().contains("windows")) { return OS_WINDOW...
### Question: LibreOfficeLauncherHelper { public static String generateLibreOfficeOpenUrl(String cmisUrl, String repositoryId, String filePath) throws UnsupportedEncodingException { StringBuilder openUrlSb = new StringBuilder(); openUrlSb.append(LibreOfficeLauncherHelper.LIBREOFFICE_HANDLER); openUrlSb.append(": String...
### Question: NotificationMessage implements Serializable { public String getPayloadString(String name) { return payload.get(name) == null ? null : String.valueOf(payload.get(name)); } static String buildSubjectPrefix(String nsPath); Map<String, Object> getPayload(); String getPayloadString(String name); void putPaylo...
### Question: CmsCryptoDES implements CmsCrypto { public void init() throws IOException, GeneralSecurityException { Security.addProvider(new BouncyCastleProvider()); this.secretKeyFile = System.getenv("CMS_DES_PEM"); if (this.secretKeyFile == null) { this.secretKeyFile = System.getProperty("com.kloopz.crypto.cms_des_pe...
### Question: CmsCryptoDES implements CmsCrypto { @Override public String decrypt(String instr) throws GeneralSecurityException { if (instr.startsWith(ENC_PREFIX)) { instr = instr.substring(ENC_PREFIX.length()); } return decryptStr(instr); } @Override String encrypt(String instr); @Override String decrypt(String instr...
### Question: ListUtils { public <V> Map<K, V> toMap(List<V> list, String keyField) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String accessor = convertFieldToAccessor(keyField); Map<K, V> map = new HashMap<K, V>(); for(V obj : list) { Method method = obj.getClass().getMethod(acce...
### Question: CapacityProcessor { public boolean isCapacityManagementEnabled(String nsPath) { CmsVar softQuotaEnabled = cmProcessor.getCmSimpleVar(CAPACITY_MANAGEMENT_VAR_NAME); if (softQuotaEnabled != null) { String value = softQuotaEnabled.getValue(); if (Boolean.TRUE.toString().equalsIgnoreCase(value)) return true; ...
### Question: SubscriberService { public List<BasicSubscriber> getSubscribersForNs(String nsPath) { try { return sinkCache.instance().get(new SinkKey(nsPath)); } catch (Exception e) { logger.error("Can't retrieve subscribers for nspath " + nsPath + " from sink cache", e); return Collections.singletonList(defaultSystemS...
### Question: EmailService implements NotificationSender { @Override public boolean postMessage(NotificationMessage msg, BasicSubscriber subscriber) { EmailSubscriber esub; if (subscriber instanceof EmailSubscriber) { esub = (EmailSubscriber) subscriber; } else { throw new ClassCastException("invalid subscriber " + sub...
### Question: AntennaListener implements MessageListener { public void onMessage(Message msg) { msgs.mark(); Context tc = msgTime.time(); try { NotificationMessage notify = null; if (msg instanceof TextMessage) { try { notify = parseMsg((TextMessage) msg); } catch (JsonParseException e) { logger.error("Got the bad mess...
### Question: InductorPublisher { protected String getCtxtId(CmsWorkOrderSimpleBase wo) { String ctxtId = ""; if (wo instanceof CmsWorkOrderSimple) { CmsWorkOrderSimple woSimple = CmsWorkOrderSimple.class.cast(wo); ctxtId = "d-" + woSimple.getDeploymentId() + "-" + woSimple.rfcCi.getRfcId() + "-" + woSimple.rfcCi.getEx...
### Question: InductorPublisher { public void cleanup() { logger.info("Closing AMQ connection"); closeConnection(); } void setConnFactory(ActiveMQConnectionFactory connFactory); void init(); void publishMessage(DelegateExecution exec, String waitTaskName, String woType); void publishMessage(String processId, String ex...
### Question: InductorListener implements MessageListener { public void onMessage(Message message) { try { if (message instanceof TextMessage) { if (logger.isDebugEnabled()) { logger.debug("got message: " + ((TextMessage) message).getText()); } try { processResponseMessage((TextMessage) message); } catch (ActivitiExcep...
### Question: WorkflowController { public String startReleaseProcess(String processKey, Map<String,Object> params){ logger.info("starting process for " + processKey + " with params: " + params.toString()); ProcessInstance pi = runtimeService.startProcessInstanceByKey(processKey, params); logger.info("started process wi...
### Question: WorkflowController { public String startOpsProcess(String processKey, Map<String,Object> params){ logger.info("starting process for " + processKey + " with params: " + params.toString()); ProcessInstance pi = runtimeService.startProcessInstanceByKey(processKey, params); logger.info("started process with i...