method2testcases
stringlengths
118
3.08k
### Question: Frequency { @Override public String toString() { return "Frequency{value=" + value + '}'; } private Frequency(int value); @CheckResult static Frequency of(@IntRange(from = LOWER, to = UPPER) int value); @CheckResult Frequency plus(@Nullable Frequency frequency); @CheckResult Frequency plus(int value); @C...
### Question: UriBuilder { public APIConnection build() throws APIKeyNotAssignedException { buildFinalURLWithCommandString(); buildFinalURLWithTheAPIKey(); buildFinalURLWithParametersToken(); return new APIConnection(finalURL); } UriBuilder(String baseURL); APIConnection build(); String getFinalURL(); UriBuilder setCom...
### Question: Utils { public static String readPropertyFrom(String propertyFilename, String propertyName) throws PropertyNotDefinedException { Properties prop = new Properties(); try { prop.load(new FileReader(new File(propertyFilename))); String propertyValue = prop.getProperty(propertyName); if(propertyValue != null)...
### Question: Utils { public static boolean isAValidJSONText(String resultAsString) { try { new JSONObject(resultAsString); return true; } catch (JSONException ex) { return false; } } private Utils(); static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator); static String urlEncode(String ...
### Question: Utils { public static String urlEncode(String token) { if (token == null) { throw new IllegalArgumentException(THE_TOKEN_CANNOT_BE_NULL_MSG); } String encodedToken = token; try { encodedToken = URLEncoder.encode(token, UTF_8); } catch (UnsupportedEncodingException uee) { logger.warn(INVALID_TOKEN_WARNING)...
### Question: Utils { public static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator) { return StringUtils.substringBeforeLast(urlParameterTokens, paramSeparator); } private Utils(); static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator); static String urlEnc...
### Question: TracingChannelInterceptor extends ChannelInterceptorAdapter implements ExecutorChannelInterceptor { @Override public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception arg3) { if ((handler instanceof WebSocketAnnotationMethodMessageHandler || handler...
### Question: CustomAsyncConfigurerAutoConfiguration implements BeanPostProcessor, PriorityOrdered, BeanFactoryAware { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AsyncConfigurer && !(bean instanceof TracedAsyncConfigurer)) { AsyncConf...
### Question: TracingMongoClientPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof MongoClient && !(bean instanceof TracingMongoClient)) { final MongoClient client = (MongoClient) bean; final Traci...
### Question: LargeMessageProxy extends AbstractLoggingActor { public static Props props() { return Props.create(LargeMessageProxy.class); } static Props props(); @Override Receive createReceive(); static final String DEFAULT_NAME; }### Answer: @Test public void testSmallMessageSending() { new TestKit(system) { { Acto...
### Question: Worker extends AbstractLoggingActor { public static Props props() { return Props.create(Worker.class); } static Props props(); @Override void preStart(); @Override void postStop(); @Override Receive createReceive(); }### Answer: @Test public void shouldFindCorrectPrimes() { new TestKit(this.actorSystem)...
### Question: UserRepository { public LiveData<User> getUser(String email) { MutableLiveData<User> liveData = new MutableLiveData<>(); userDao.loadUser(email) .compose(transformers.applySchedulersToFlowable()) .subscribe(liveData::setValue, Timber::d); userApi.getUser(email) .compose(transformers.applySchedulersToFlowa...
### Question: UserRepository { public LiveData<List<User>> getUsers() { MutableLiveData<List<User>> liveData = new MutableLiveData<>(); userDao.loadUsers() .compose(transformers.applySchedulersToFlowable()) .subscribe(liveData::setValue, Timber::d); userApi.getUsers() .compose(transformers.applySchedulersToFlowable()) ...
### Question: UserRepository { public LiveData<Boolean> saveUser(User user) { MutableLiveData<Boolean> liveData = new MutableLiveData<>(); Completable.fromAction(() -> userDao.saveUser(user)) .compose(transformers.applySchedulersToCompletable()) .subscribe(() -> liveData.setValue(true), throwable -> { Timber.d(throwabl...
### Question: UserMapper { public User toModel(com.jonathanpetitfrere.mvvm.repository.persistence.entity.User userEntity) { return new User(userEntity.getEmail(), userEntity.getFirstName(), userEntity.getLastName()); } @Inject UserMapper(); User toModel(com.jonathanpetitfrere.mvvm.repository.persistence.entity.User us...
### Question: UserMapper { public com.jonathanpetitfrere.mvvm.repository.persistence.entity.User toEntity(User userModel) { return new com.jonathanpetitfrere.mvvm.repository.persistence.entity.User(userModel.getEmail(), userModel.getFirstName(), userModel.getLastName()); } @Inject UserMapper(); User toModel(com.jonath...
### Question: RxIdler { @SuppressWarnings("ConstantConditions") @CheckResult @NonNull public static IdlingResourceScheduler wrap(@NonNull Scheduler scheduler, @NonNull String name) { if (scheduler == null) throw new NullPointerException("scheduler == null"); if (name == null) throw new NullPointerException("name == nul...
### Question: DelegatingIdlingResourceScheduler extends IdlingResourceScheduler { @Override public String getName() { return name; } DelegatingIdlingResourceScheduler(Scheduler delegate, String name); @Override String getName(); @Override boolean isIdleNow(); @Override void registerIdleTransitionCallback(ResourceCallba...
### Question: Rx2Idler { @SuppressWarnings("ConstantConditions") @CheckResult @NonNull public static Function<Callable<Scheduler>, Scheduler> create(@NonNull final String name) { if (name == null) throw new NullPointerException("name == null"); return new Function<Callable<Scheduler>, Scheduler>() { @Override public Sc...
### Question: Rx2Idler { @SuppressWarnings("ConstantConditions") @CheckResult @NonNull public static IdlingResourceScheduler wrap(@NonNull Scheduler scheduler, @NonNull String name) { if (scheduler == null) throw new NullPointerException("scheduler == null"); if (name == null) throw new NullPointerException("name == nu...
### Question: Rx3Idler { @SuppressWarnings("ConstantConditions") @CheckResult @NonNull public static Function<Supplier<Scheduler>, Scheduler> create(@NonNull final String name) { if (name == null) throw new NullPointerException("name == null"); return delegate -> { IdlingResourceScheduler scheduler = new DelegatingIdli...
### Question: Rx3Idler { @SuppressWarnings("ConstantConditions") @CheckResult @NonNull public static IdlingResourceScheduler wrap(@NonNull Scheduler scheduler, @NonNull String name) { if (scheduler == null) throw new NullPointerException("scheduler == null"); if (name == null) throw new NullPointerException("name == nu...
### Question: SupportUtils { public static String normalize(@NonNull String input) { String trimmedInput = input.trim(); Uri uri = Uri.parse(trimmedInput); for (final String s : SupportUtils.SUPPORTED_URLS) { if (s.equals(input)) { return input; } } if (TextUtils.isEmpty(uri.getScheme())) { uri = Uri.parse("http: } ret...
### Question: SupportUtils { public static String getSumoURLForTopic(final Context context, final String topic) { String escapedTopic; try { escapedTopic = URLEncoder.encode(topic, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("utf-8 should always be available", e); } final String...
### Question: SupportUtils { public static String getManifestoURL() { final String langTag = Locales.getLanguageTag(Locale.getDefault()); return "https: } static String normalize(@NonNull String input); static boolean isUrl(@Nullable String url); static boolean isTemplateSupportPages(String url); static String getSumo...
### Question: ColorUtils { public static int getReadableTextColor(final int backgroundColor) { final int greyValue = grayscaleFromRGB(backgroundColor); if (greyValue < 186) { return Color.WHITE; } else { return Color.BLACK; } } static int getReadableTextColor(final int backgroundColor); }### Answer: @Test public void...
### Question: MimeUtils { public static boolean isText(@Nullable String type) { return !TextUtils.isEmpty(type) && textPattern.matcher(type).find(); } private MimeUtils(); static boolean isText(@Nullable String type); static boolean isImage(@Nullable String type); static boolean isAudio(@Nullable String type); static ...
### Question: MimeUtils { public static boolean isImage(@Nullable String type) { return !TextUtils.isEmpty(type) && imgPattern.matcher(type).find(); } private MimeUtils(); static boolean isText(@Nullable String type); static boolean isImage(@Nullable String type); static boolean isAudio(@Nullable String type); static ...
### Question: MimeUtils { public static boolean isAudio(@Nullable String type) { return !TextUtils.isEmpty(type) && audioPattern.matcher(type).find(); } private MimeUtils(); static boolean isText(@Nullable String type); static boolean isImage(@Nullable String type); static boolean isAudio(@Nullable String type); stati...
### Question: MimeUtils { public static boolean isVideo(@Nullable String type) { return !TextUtils.isEmpty(type) && videoPattern.matcher(type).find(); } private MimeUtils(); static boolean isText(@Nullable String type); static boolean isImage(@Nullable String type); static boolean isAudio(@Nullable String type); stati...
### Question: UrlUtils { public static boolean isPermittedResourceProtocol(@NonNull final String scheme) { if (TextUtils.isEmpty(scheme)) { return false; } return scheme.startsWith("http") || scheme.startsWith("https") || scheme.startsWith("file") || scheme.startsWith("data"); } static boolean isHttpOrHttps(String url...
### Question: TabEntity { public boolean isValid() { final boolean hasId = !TextUtils.isEmpty(this.getId()); final boolean hasUrl = !TextUtils.isEmpty(this.getUrl()); return hasId && hasUrl; } @Ignore TabEntity(String id, String parentId); TabEntity(String id, String parentId, String title, String url); @NonNull Stri...
### Question: BrowsingSession { public static synchronized BrowsingSession getInstance() { if (instance == null) { instance = new BrowsingSession(); } return instance; } private BrowsingSession(); static synchronized BrowsingSession getInstance(); void countBlockedTracker(); void setBlockedTrackerCount(int count); voi...
### Question: SearchEngineParser { public static SearchEngine load(AssetManager assetManager, String identifier, String path) throws IOException { try (final InputStream stream = assetManager.open(path)) { return load(identifier, stream); } catch (XmlPullParserException e) { throw new AssertionError("Parser exception w...
### Question: Trie { public Trie findNode(final FocusString string) { if (terminator) { if (string.length() == 0 || string.charAt(0) == '.') { return this; } } else if (string.length() == 0) { return null; } final Trie next = children.get(string.charAt(0)); if (next == null) { return null; } return next.findNode(string...
### Question: TrackingProtectionWebViewClient extends WebViewClient { @Override public WebResourceResponse shouldInterceptRequest(final WebView view, final WebResourceRequest request) { if (!blockingEnabled) { return super.shouldInterceptRequest(view, request); } final Uri resourceUri = request.getUrl(); final String s...
### Question: DiskLruCache implements Closeable { public synchronized void close() throws IOException { if (journalWriter == null) { return; } for (Entry entry : new ArrayList<Entry>(lruEntries.values())) { if (entry.currentEditor != null) { entry.currentEditor.abort(); } } trimToSize(); journalWriter.close(); journalW...
### Question: UrlUtils { public static boolean isSupportedProtocol(@NonNull final String scheme) { if (TextUtils.isEmpty(scheme)) { return false; } return isPermittedResourceProtocol(scheme) || scheme.startsWith("error"); } static boolean isHttpOrHttps(String url); static boolean isSearchQuery(String text); static Str...
### Question: UrlUtils { public static boolean isSearchQuery(String text) { return text.contains(" "); } static boolean isHttpOrHttps(String url); static boolean isSearchQuery(String text); static String stripUserInfo(@Nullable String url); static boolean isPermittedResourceProtocol(@NonNull final String scheme); stat...
### Question: UrlUtils { public static String stripUserInfo(@Nullable String url) { if (TextUtils.isEmpty(url)) { return ""; } try { URI uri = new URI(url); final String userInfo = uri.getUserInfo(); if (userInfo == null) { return url; } uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), ...
### Question: UrlUtils { public static boolean isInternalErrorURL(final String url) { return "data:text/html;charset=utf-8;base64,".equals(url); } static boolean isHttpOrHttps(String url); static boolean isSearchQuery(String text); static String stripUserInfo(@Nullable String url); static boolean isPermittedResourcePr...
### Question: UrlUtils { public static boolean isHttpOrHttps(String url) { if (TextUtils.isEmpty(url)) { return false; } return url.startsWith("http:") || url.startsWith("https:"); } static boolean isHttpOrHttps(String url); static boolean isSearchQuery(String text); static String stripUserInfo(@Nullable String url); ...
### Question: UrlUtils { public static String stripCommonSubdomains(@Nullable String host) { return stripPrefix(host, COMMON_SUBDOMAINS_PREFIX_ARRAY); } static boolean isHttpOrHttps(String url); static boolean isSearchQuery(String text); static String stripUserInfo(@Nullable String url); static boolean isPermittedReso...
### Question: UrlUtils { public static String stripHttp(@Nullable String host) { return stripPrefix(host, HTTP_SCHEME_PREFIX_ARRAY); } static boolean isHttpOrHttps(String url); static boolean isSearchQuery(String text); static String stripUserInfo(@Nullable String url); static boolean isPermittedResourceProtocol(@NonN...
### Question: TabUtil { public static Bundle argument(@Nullable final String parentId, boolean fromExternal, boolean toFocus) { final Bundle bundle = new Bundle(); if (!TextUtils.isEmpty(parentId)) { bundle.putString(ARG_PARENT_ID, parentId); } bundle.putBoolean(ARG_EXTERNAL, fromExternal); bundle.putBoolean(ARG_FOCUS,...
### Question: PathUtil { public static Path getWindupUserDir() { String userHome = System.getProperty("user.home"); if (userHome == null) { Path path = new File("").toPath(); LOG.warning("$USER_HOME not set, using [" + path.toAbsolutePath().toString() + "] instead."); return path; } return Paths.get(userHome).resolve("...
### Question: PathUtil { public static Path getUserIgnoreDir() { return getUserSubdirectory(IGNORE_DIRECTORY_NAME); } static Path getWindupUserDir(); static Path getWindupHome(); static void setWindupHome(Path windupHome); static Path getUserCacheDir(); static Path getWindupCacheDir(); static Path getUserIgnoreDir(); ...
### Question: TickCounter { public TickCounter(TickHandler tickHandler, int maxTicks, int tickDuration) { this(tickHandler, maxTicks, tickDuration, 0); } TickCounter(TickHandler tickHandler, int maxTicks, int tickDuration); TickCounter(TickHandler tickHandler, int maxTicks, int tickDuration, int tickOffset); boo...
### Question: CollectionUtils { public static synchronized <T, E> T getKeyByValue(Map<T, E> map, E value) { Preconditions.checkNotNull(map, "The map cannot be null"); for (Entry<T, E> entry : map.entrySet()) { if (Objects.equals(value, entry.getValue())) { return entry.getKey(); } } return null; } private CollectionUt...
### Question: CollectionUtils { public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map) { Preconditions.checkNotNull(map, "The map cannot be null"); List<Entry<K, V>> list = new ArrayList<>(map.entrySet()); list.sort(Entry.comparingByValue()); Map<K, V> result = new LinkedHashMap<>(); f...
### Question: CollectionUtils { public static <T extends Comparable<T>> T findMostPopularElement( List<T> list) { Preconditions.checkNotNull(list, "The list cannot be null"); Collections.sort(list); T previous = list.get(0); T popular = list.get(0); int count = 1; int maxCount = 1; for (int i = 1; i < list.size(); i++)...
### Question: JwtUserFactory { public static JwtUser create(User user) { return new JwtUser( user.getId(), user.getUsername(), user.getFirstname(), user.getLastname(), user.getPassword(), user.getEmail(), user.getEnabled(), user.getLastPasswordResetDate().getTime(), mapUserRolesToGrantedAuthorities(user.getRoles()), us...
### Question: JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } @Override void ...
### Question: JwtUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { final User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException(String.format("No user found with use...
### Question: JwtUtils { public String getUsernameFromTokenClaims(Claims claims) { try { final String username = claims.getSubject(); if (username == null) { final String errorMsg = "Failed to extract username claim from token!"; LOG.error(errorMsg); throw new JwtAuthenticationException(errorMsg); } return username; } ...
### Question: OptionalConfig { public Map<String, String> getItems() { return items; } OptionalConfig(); Map<String, String> getItems(); void setItems(Map<String, String> items); @Override String toString(); }### Answer: @Test public void testAddingAndFetchingOptionalConfigItems() throws Exception { final OptionalConf...
### Question: JwtUtils { Date getIssuedAtDateFromTokenClaims(Claims claims) throws JwtAuthenticationException { try { return claims.getIssuedAt(); } catch (Exception e) { final String errorMsg = "Failed to extract iat claim from token!"; LOG.error(errorMsg, e); throw new JwtAuthenticationException(errorMsg, e); } } Cl...
### Question: JwtUtils { Date getExpirationDateFromTokenClaims(Claims claims) throws JwtAuthenticationException { try { return claims.getExpiration(); } catch (Exception e) { final String errorMsg = "Failed to extract expiration claim from token!"; LOG.error(errorMsg, e); throw new JwtAuthenticationException(errorMsg, ...
### Question: JwtUtils { public List<GrantedAuthority> getRolesFromTokenClaims(Claims claims) throws JwtAuthenticationException { final List<GrantedAuthority> roles = new ArrayList<>(); try { @SuppressWarnings("unchecked") final List<String> rolesFromClaim = (List<String>) claims.get(CLAIM_KEY_ROLES); for (final String...
### Question: JwtUtils { Date getLastPasswordResetDateFromTokenClaims(Claims claims) { Date lastPasswordResetDate; try { lastPasswordResetDate = new Date((Long) claims.get(CLAIM_KEY_LAST_PASSWORD_CHANGE_DATE)); } catch (Exception e) { LOG.error("Failed to extract lastPasswordResetDate claim from token!", e); lastPasswo...
### Question: JwtUtils { public Claims validateTokenAndGetClaims(String token) { try { final Claims claims = getClaimsFromToken(token); final Date created = getIssuedAtDateFromTokenClaims(claims); final Date lastPasswordResetDate = getLastPasswordResetDateFromTokenClaims(claims); if (isCreatedBeforeLastPasswordReset(cr...
### Question: Properlty { public Optional<BigDecimal> getBigDecimal(String key) { return get(key).map((val) -> new BigDecimal(val)); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue)...
### Question: Properlty { public Optional<BigInteger> getBigInteger(String key) { return get(key).map((val) -> new BigInteger(val)); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue)...
### Question: Properlty { public String[] getArray(String key) { return getArray(key, Default.LIST_SEPARATOR); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(Stri...
### Question: SystemPropertiesReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> properties = new HashMap<>(); final Properties systemProperties = System.getProperties(); for(final Entry<Object, Object> x : systemProperties.entrySet()) { properties.put((Stri...
### Question: EnvironmentVariablesReader implements Reader { @Override public Map<String, PropertyValue> read() { return envSupplier.get().entrySet().stream() .collect(Collectors.toMap( e -> getKey(e.getKey()), e -> PropertyValue.of(e.getValue()).resolvable(false) )); } EnvironmentVariablesReader(); EnvironmentVariabl...
### Question: PriorityQueueDecoratorReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> result = new LinkedHashMap<>(); readersMap.forEach((priority, readers) -> { readers.forEach(reader -> { final Map<String, PropertyValue> entries = reader.read(); result.pu...
### Question: AbstractMinikubeMojo extends AbstractMojo { @VisibleForTesting List<String> buildMinikubeCommand() { List<String> execString = new ArrayList<>(); execString.add(minikube); execString.add(getCommand()); if (flags != null) { execString.addAll(flags); } execString.addAll(getMoreFlags()); return execString; }...
### Question: AbstractMinikubeMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { List<String> minikubeCommand = buildMinikubeCommand(); try { commandExecutorSupplier.get().setLogger(mavenBuildLogger).run(minikubeCommand); } catch (InterruptedException | IOException ex) { throw n...
### Question: CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } CommandExecutor setLogger(BuildLogger logger); CommandExecutor setEnvironment(Map<String, String> environmentMap); List<String> run(String... command); List<String...
### Question: MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvid...
### Question: DefaultedURL { @Override public boolean equals(Object o) { if (o instanceof DefaultedURL) { return url.equals(((DefaultedURL) o).getUrl()); } return false; } DefaultedURL(); boolean isDefault(); void setUrl(URL url); String getDomain(); URL getUrl(); @Override String toString(); @Override boolean equals(O...
### Question: GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); }### Answer: @Test public void testGatewayManagerFromCurrentProvider_noProvider_...
### Question: GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); }### Answer: @Test @UseDataProvider("dataProviderTimezones") public void testSelect(int timezone, String expected) { when(ConfigHelper.getCurrent...
### Question: CeSymmMain { public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { s.nextLin...
### Question: DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<StringSecretEntry> getAllStringSecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.UTF8) .map(StringSecretEntry::of) .collect(Colle...
### Question: DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<ByteSecretEntry> getAllBinarySecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.BINARY) .map(ByteSecretEntry::of) .collect(Collect...
### Question: DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecrets...
### Question: IAMPolicyManager { public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyMa...
### Question: IAMPolicyManager { public void detachAllPrincipals(SecretsGroupIdentifier group) { try { List<Principal> admins = listAttachedAdmin(group); admins.forEach(p -> detachAdmin(group, p)); } catch (DoesNotExistException e) { } try { List<Principal> readonly = listAttachedReadOnly(group); readonly.forEach(p -> ...
### Question: IAMPolicyManager { public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentia...
### Question: IAMPolicyManager { public void deleteReadonlyPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCre...
### Question: RegionLocalResourceName { @Override public String toString() { return String.format("%s_%s_%s", PREFIX, group.region.getName(), AWSResourceNameSerialization.encodeSecretsGroupName(group.name)); } RegionLocalResourceName(SecretsGroupIdentifier group); @Override String toString(); static RegionLocalResource...
### Question: RegionLocalResourceName { public static RegionLocalResourceName fromString(String wrappedAWSResourceName) { String[] parts = wrappedAWSResourceName.split(AWSResourceNameSerialization.GLOBAL_STRING_DELIMITER); if (!parts[0].equals(PREFIX)) { throw new InvalidResourceName( wrappedAWSResourceName, "Regional ...
### Question: RegionLocalResourceName { @Override public boolean equals(final Object obj) { if(obj instanceof RegionLocalResourceName){ final RegionLocalResourceName other = (RegionLocalResourceName) obj; return Objects.equal(group, other.group); } else{ return false; } } RegionLocalResourceName(SecretsGroupIdentifier ...
### Question: SessionCache { String resolveFileName() { return String.format("%s--%s.json", profile.name, roleToAssume.toArn().replace(':', '_').replace('/', '-')); } SessionCache(final ProfileIdentifier profile, final RoleARN roleToAssume); Optional<BasicSessionCredentials> load(); void save(final AssumedRoleUser assu...
### Question: KMSEncryptor implements Encryptor, ManagedResource { @Override public String encrypt(String plaintext, EncryptionContext context) { return crypto.encryptString(getProvider(), plaintext, context.toMap()).getResult(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfigu...
### Question: KMSEncryptor implements Encryptor, ManagedResource { @Override public String create() { return kmsManager.create(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionS...
### Question: KMSEncryptor implements Encryptor, ManagedResource { @Override public void delete() { kmsManager.delete(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength e...
### Question: KMSEncryptor implements Encryptor, ManagedResource { @Override public Optional<String> awsAdminPolicy() { return kmsManager.awsAdminPolicy(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCry...
### Question: KMSEncryptor implements Encryptor, ManagedResource { @Override public Optional<String> awsReadOnlyPolicy() { return kmsManager.awsReadOnlyPolicy(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, ...
### Question: KMSEncryptor implements Encryptor, ManagedResource { @Override public String getArn() { return kmsManager.getArn(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionS...
### Question: KMSEncryptor implements Encryptor, ManagedResource { @Override public boolean exists() { return kmsManager.exists(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, Encryption...
### Question: IAMPolicyManager { public String getAdminPolicyArn(SecretsGroupIdentifier group) { return getArn(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCreden...
### Question: KMSManager implements ManagedResource { @Override public void delete() { deleteAndGetSchedule(); waitForKeyState(KMSKeyState.PENDING_DELETION); } KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); static KMSMan...
### Question: KMSManager implements ManagedResource { @Override public boolean exists() { return exists(false); } KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); static KMSManager fromCredentials(AWSCredentialsProvider aw...
### Question: EncryptionPayload implements BestEffortShred { public String toJsonBlob() { try { return objectMapper.writeValueAsString(this); } catch (JsonProcessingException e) { throw new SerializationException("Failed to serialize to JSON blob", e); } } @JsonCreator EncryptionPayload(@JsonProperty("value") SecretVa...
### Question: EncryptionPayload implements BestEffortShred { public static EncryptionPayload fromJsonBlob(String jsonBlob) { try { return objectMapper.readValue(jsonBlob, EncryptionPayload.class); } catch (IOException e) { throw new ParseException("Failed to deserialize JSON blob", e); } } @JsonCreator EncryptionPaylo...
### Question: EncryptionPayload implements BestEffortShred { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("value", value) .add("userdata", userData) .add("created", created) .add("modified", modified) .add("comment", comment) .toString(); } @JsonCreator EncryptionPayload(@JsonPrope...
### Question: EncryptionPayload implements BestEffortShred { public static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(state.asByte()); messageDigest.update(toByteArra...