method2testcases
stringlengths
118
3.08k
### Question: Person { public void addFriend(String friend) { if (!friends.contains(friend)) friends.add(friend); } Person(); Person(String name); List<String> getFriends(); void addFriend(String friend); @Override String toString(); }### Answer: @Test public void testAddFriend() throws Exception { Person p = new Per...
### Question: RESTService { public void precomputeGraphs(ServletContext context){ logger.info("Precomputing graphs..."); DatasetBasedGraphGenerator graphGenerator = new CachedDatasetBasedGraphGenerator(qef, cacheDirectory); Map<String, List<String>> entities = getEntities(null); for (String cls : entities.keySet()) { t...
### Question: DBpediaPropertyBlackList implements BlackList { @Override public boolean contains(Resource resource){ return contains(resource.getURI()); } DBpediaPropertyBlackList(); @Override boolean contains(Resource resource); @Override boolean contains(String uri); static boolean onlyOntologyNamespace; }### Answer: ...
### Question: Integers { public static long any(long l) { l = l | (l << 32) | (l >>> 32); l = l | (l << 16) | (l >>> 16); l = l | (l << 8) | (l >>> 8); l = l | (l << 4) | (l >>> 4); l = l | (l << 2) | (l >>> 2); l = l | (l << 1) | (l >>> 1); return l; } private Integers(); static long negative(long l); static int nega...
### Question: Integers { public static long all(long l) { long c = Long.bitCount(l); return ~any(c ^ 64); } private Integers(); static long negative(long l); static int negative(int i); static short netative(short s); static long min(long lhs, long rhs); static int min(int lhs, int rhs); static short min(short lhs, sh...
### Question: ByteArrayDiffs { public static byte[] diff(byte[] orig, byte[] target) { MemoryDiff md = new MemoryDiff(); md.store(Diffs.improved(Diffs.queue(orig, target))); return Serials.serialize(DefaultSerialization.newInstance(), MemoryDiff.class, md); } private ByteArrayDiffs(); static byte[] diff(byte[] orig, b...
### Question: ByteArrayDiffs { public static byte[] undo(byte[] target, byte[] diff) { MemoryDiff md = Serials.deserialize(DefaultSerialization.newInstance(), MemoryDiff.class, diff); return Diffs.apply(new UndoOpQueue(md.queue()), target); } private ByteArrayDiffs(); static byte[] diff(byte[] orig, byte[] target); st...
### Question: Document { @Loggable public String name() throws Exception { TimeUnit.SECONDS.sleep(1); return this.name; } Document(@NotNull String txt); @Loggable String name(); @Loggable void exception(); }### Answer: @Test public void instantiates() throws Exception { final Document doc = new Document("test"); doc.n...
### Question: Document { @Loggable public void exception() { throw new IllegalStateException(); } Document(@NotNull String txt); @Loggable String name(); @Loggable void exception(); }### Answer: @Test(expected = IllegalStateException.class) public void throwsAndLogs() throws Exception { new Document("foo").exception()...
### Question: Page { @Cacheable(lifetime = 0) public String downloadWithoutCache(final String text) { ++this.cnt; return "done without cache"; } @Cacheable String downloadWithCache(final String text); @Cacheable(lifetime = 0) String downloadWithoutCache(final String text); int counted(); }### Answer: @Test public voi...
### Question: LoggableThreading { @Loggable(Loggable.DEBUG) public int foo() { return 1; } @Loggable(Loggable.DEBUG) int foo(); }### Answer: @Test public void loggableThreadTerminates() throws Exception { new LoggableThreading().foo(); Thread thread = null; final Set<Thread> keys = Thread.getAllStackTraces().keySet()...
### Question: Sample { public String notNull(@NotNull final String value) { return value; } String notNull(@NotNull final String value); }### Answer: @Test(expected = javax.validation.ConstraintViolationException.class) public void aspectjAnnotationsWork() throws Exception { new Sample().notNull(null); }
### Question: HttpClientController { public Author getAuthorByURL(String link, Author a) throws IOException, SamlibParseException, SamlibInterruptException { a.setUrl(link); String str = getURL(mSamLibConfig.getAuthorIndexDate(a), new StringReader()); parseAuthorIndexDateData(a, str); return a; } HttpClientController(A...
### Question: HttpClientController { public Author addAuthor(String link, Author a1) throws IOException, SamlibParseException, SamlibInterruptException { Author a = getAuthorByURL(link, a1); a.extractName(); return a; } HttpClientController(AbstractSettings context); void cancelAll(); Author getAuthorByURL(String link,...
### Question: SamlibOperation { public void makeAuthorAdd(final ArrayList<String> urls, final AuthorGuiState state) { mThread = new Thread() { @Override public void run() { super.run(); runAuthorAdd(urls, state); } }; mThread.start(); } SamlibOperation(AuthorController sql, AbstractSettings settingsHelper, HttpClientCo...
### Question: CPLC { public static CPLC read(byte[] buf) { return read(buf, 0, buf.length); } CPLC(); CPLC(Map<Field, byte[]> values); List<Field> getFields(); byte[] getFieldValue(Field field); String getFieldHex(Field field); String getLifetimeIdentifier(); String toString(); static CPLC read(byte[] buf); static CPL...
### Question: GPCardData { public static GPCardData fromBytes(byte[] data) throws TLVException { GPCardData result = new GPCardData(); TLVConstructed cd = TLV.readRecursive(data).asConstructed(TAG_CARD_DATA); TLVConstructed crd = cd.getChild(0).asConstructed(TAG_CARD_RECOGNITION_DATA); parseCRD(result, crd.getChildren(...
### Question: GPKeyInfoTemplate { public static GPKeyInfoTemplate fromBytes(byte[] buf) throws TLVException { ArrayList<GPKeyInfo> infos = new ArrayList<>(); TLVConstructed kitTlv = TLVConstructed.readConstructed(buf).asConstructed(TAG_KEY_INFO_TEMPLATE); for (TLV kiTlv : kitTlv.getChildren()) { infos.add(GPKeyInfo.fro...
### Question: GPKeyInfo { public static GPKeyInfo fromBytes(byte[] data) throws TLVException { return fromTLV(TLVPrimitive.readPrimitive(data)); } GPKeyInfo(int keyId, int keyVersion, int keyType, int keySize); GPKeyInfo(int keyId, int keyVersion, int[] keyTypes, int[] keySizes); int getKeyId(); int getKeyVersion(); i...
### Question: GPKey { public byte[] getCheckValue(GPKeyCipher cipher) { if(!isCompatible(cipher)) { throw new UnsupportedOperationException("Cannot use " + mCipher + " key with cipher " + cipher); } switch(cipher) { case DES3: return GPCrypto.kcv_3des(this); case AES: return GPCrypto.kcv_aes(this); default: throw new U...
### Question: Util { public static Calendar getCalendarForLocale(Calendar oldCalendar, Locale locale) { if (locale == null) throw new IllegalArgumentException("You must specify the Locate value"); if (oldCalendar == null) return Calendar.getInstance(locale); long currentTimeMillis = oldCalendar.getTimeInMillis(); Calen...
### Question: Util { public static boolean isNumericMonths(String[] value) { return Character.isDigit(value[Calendar.JANUARY].charAt(0)); } static Calendar getCalendarForLocale(Calendar oldCalendar, Locale locale); static boolean isNumericMonths(String[] value); }### Answer: @Test public void isNotNumericMonths() { S...
### Question: ClientRunner { public void read(String serverId) throws Throwable { Optional<Connecter> connecter = Optional.of(connecterMap.get(serverId)); Server server = connecter.get().getServer().get(); ConnectInfo serverInfo = this.getServerInfo(serverId); String topic = serverInfo.getTopic(); Browser.readAsyn(serv...
### Question: Connecter { public Server connect() throws Throwable { server.connect(); long connectTime = 10; while (connectTime-- >0){ if(server!=null && server.getServerState()!=null && server.getServerState().getServerState()!=null){ server.addStateListener(listener); return server; }else{ TimeUnit.SECONDS.sleep(2);...
### Question: Browser { public static void readAsyn(Server server, Collection<String> itemIds, ScheduledExecutorService threadPool, long heartBeat,DataCallback dataCallback) throws Throwable { Group group = server.addGroup(); Map<String, Item> items = group.addItems(itemIds.toArray(new String[0])); Runnable runnable = ...
### Question: Browser { public static void subscibe(Server server){ } private Browser(); static List<DataItem> readSync(Server server, Collection<String> itemIds); static List<DataItem> readSync(Server server); static void readAsyn(Server server, Collection<String> itemIds, ScheduledExecutorService threadPool, long he...
### Question: Browser { public static Collection<String> browseItemIds(Server server) throws Throwable{ Collection<String> nodeIds = server.getFlatBrowser().browse(); return nodeIds; } private Browser(); static List<DataItem> readSync(Server server, Collection<String> itemIds); static List<DataItem> readSync(Server se...
### Question: Browser { public static List<ServerInfo> listServer(String host, String domain, String userName, String password) throws Throwable { ServerList serverList = new ServerList(host, userName, password, domain); Collection<ClassDetails> classDetails = serverList.listServersWithDetails(new Category[]{Categories...
### Question: Browser { public static void browserServer(){ } private Browser(); static List<DataItem> readSync(Server server, Collection<String> itemIds); static List<DataItem> readSync(Server server); static void readAsyn(Server server, Collection<String> itemIds, ScheduledExecutorService threadPool, long heartBeat,...
### Question: BlobModule extends ReactContextBaseJavaModule { public void remove(String blobId) { mBlobs.remove(blobId); } BlobModule(ReactApplicationContext reactContext); @Override String getName(); @Override @Nullable Map<String, Object> getConstants(); String store(byte[] data); void store(byte[] data, String blobI...
### Question: BlobModule extends ReactContextBaseJavaModule { @ReactMethod public void release(String blobId) { remove(blobId); } BlobModule(ReactApplicationContext reactContext); @Override String getName(); @Override @Nullable Map<String, Object> getConstants(); String store(byte[] data); void store(byte[] data, Strin...
### Question: SQLLookupService extends AbstractSQLLookupService<String> { @Override public Class<?> getValueType() { return String.class; } SQLLookupService(); @Override Class<?> getValueType(); @OnEnabled void onEnabled(final ConfigurationContext context); static final PropertyDescriptor LOOKUP_VALUE_COLUMN; }### Answ...
### Question: SQLRecordLookupService extends AbstractSQLLookupService<Record> { @Override public Set<String> getRequiredKeys() { return Collections.emptySet(); } SQLRecordLookupService(); @Override Set<String> getRequiredKeys(); @Override Class<?> getValueType(); @OnEnabled void onEnabled(final ConfigurationContext con...
### Question: SQLRecordLookupService extends AbstractSQLLookupService<Record> { @Override public Class<?> getValueType() { return Record.class; } SQLRecordLookupService(); @Override Set<String> getRequiredKeys(); @Override Class<?> getValueType(); @OnEnabled void onEnabled(final ConfigurationContext context); }### Ans...
### Question: UpgradeServerDefaultsStep extends AbstractUpgradeStep { @VisibleForTesting protected Map<String, String> calculateAddedServerDefaults(Map<String, String> newDefaults, Map<String, String> existingDefaults) { Map<String, String> addedValues = new HashMap<String, String>(); for (Map.Entry<String, String> new...
### Question: IPAddressValidator implements ServiceAttributeValidator { public boolean validate(Set<String> values) { for (String value : values) { if (!validate(value)) { return false; } } return true; } boolean validate(Set<String> values); boolean validate(String value); }### Answer: @Test(dataProvider = "addresse...
### Question: RequiredValueValidator implements ServiceAttributeValidator { public boolean validate(Set<String> values) { if (values.size() > 0) { for (String value : values) { if (!StringUtils.isNotEmpty(value)) { return false; } } return true; } return false; } boolean validate(Set<String> values); }### Answer: @Te...
### Question: EmailValidator implements ServiceAttributeValidator { public boolean validate(Set<String> values) { for (String value : values) { if (!validate(value)) { return false; } } return true; } boolean validate(Set<String> values); boolean validate(String value); }### Answer: @Test(dataProvider = "data") publi...
### Question: DelegationUtils { static String swapRealmTag(String realm, String value) { return value.replace(REALM_NAME_TAG, realm); } static void createRealmPrivileges(SSOToken token, String realmName); static void copyRealmPrivilegesFromParent(SSOToken token, OrganizationConfigManager parent, Organizati...
### Question: DynamicSessionIDExtensions implements SessionIDExtensions { @Override public String getPrimaryID() { SessionIDCorrector corrector = query.getSessionIDCorrector(); if (corrector == null) { return delegate.getPrimaryID(); } return corrector.translatePrimaryID(delegate.getPrimaryID(), delegate.getSiteID()); ...
### Question: DynamicSessionIDExtensions implements SessionIDExtensions { @Override public String getSiteID() { SessionIDCorrector corrector = query.getSessionIDCorrector(); if (corrector == null) { return delegate.getSiteID(); } return corrector.translateSiteID(delegate.getPrimaryID(), delegate.getSiteID()); } @Visibl...
### Question: RemoteOperations implements SessionOperations { public void logout(Session session) throws SessionException { if (debug.messageEnabled()) { debug.message(MessageFormat.format( "Remote logout {0}", session.getID().toString())); } SessionRequest sreq = new SessionRequest(SessionRequest.Logout, session.getID...
### Question: RemoteOperations implements SessionOperations { public void destroy(Session requester, Session session) throws SessionException { if (debug.messageEnabled()) { debug.message(MessageFormat.format( "Remote destroy {0}", session)); } SessionRequest sreq = new SessionRequest(SessionRequest.DestroySession, req...
### Question: RemoteOperations implements SessionOperations { public void setProperty(Session session, String name, String value) throws SessionException { if (debug.messageEnabled()) { debug.message(MessageFormat.format( "Remote setProperty {0} {1}={2}", session, name, value)); } SessionID sessionID = session.getID();...
### Question: StatelessOperations implements SessionOperations { @Override public SessionInfo refresh(final Session session, final boolean reset) throws SessionException { final SessionInfo sessionInfo = statelessSessionFactory.getSessionInfo(session.getID()); if (sessionInfo.getExpiryTime() < currentTimeMillis()) { th...
### Question: StatelessOperations implements SessionOperations { @Override public void logout(final Session session) throws SessionException { if (session instanceof StatelessSession) { SessionInfo sessionInfo = statelessSessionFactory.getSessionInfo(session.getID()); sessionLogging.logEvent(sessionInfo, SessionEvent.L...
### Question: LocalOperations implements SessionOperations { public SessionInfo refresh(Session session, boolean reset) throws SessionException { SessionID sessionID = session.getID(); if (debug.messageEnabled()) { debug.message(MessageFormat.format( "Local fetch SessionInfo for {0}\n" + "Reset: {1}", sessionID.toStrin...
### Question: ResourceSetRegistrationEndpoint extends ServerResource { @Delete public Representation deleteResourceSet() throws NotFoundException, ServerException { if (!isConditionalRequest()) { throw new ResourceException(512, "precondition_failed", "Require If-Match header to delete Resource Set", null); } ResourceS...
### Question: PropertiesFileLicenseLog implements LicenseLog { public void logLicenseAccepted(License license, String user, Date acceptedDate) { Properties log = loadLogFile(license, true); String acceptedDateStr = DateUtils.toUTCDateFormat(acceptedDate); log.setProperty(user, acceptedDateStr); saveLogFile(license, log...
### Question: AccessTokenService { public AccessToken requestAccessToken(OAuth2Request request) throws RedirectUriMismatchException, InvalidClientException, InvalidRequestException, InvalidCodeException, InvalidGrantException, ServerException, UnauthorizedClientException, InvalidScopeException, NotFoundException, Autho...
### Question: StatefulAccessToken extends StatefulToken implements AccessToken { @Override public String getClientId() { final Set<String> value = getParameter(CLIENT_ID); if (value != null && !value.isEmpty()) { return value.iterator().next(); } return null; } StatefulAccessToken(JsonValue token); StatefulAccessToken...
### Question: DuplicateRequestParameterValidator implements AuthorizeRequestValidator { public void validateRequest(OAuth2Request request) throws InvalidClientException, InvalidRequestException, RedirectUriMismatchException, UnsupportedResponseTypeException, ServerException, BadRequestException, InvalidScopeException, ...
### Question: RESTEndpoint { public String getPath() { return path + paramsToString(); } private RESTEndpoint(RESTEndpointBuilder builder); RESTResponse call(); @Override String toString(); String getPath(); static final String AUTHENTICATION_URI; static final String AUTHENTICATION_URI_API_VERSION; static final String...
### Question: ApplicationV1Filter implements Filter { @Override public Promise<ResourceResponse, ResourceException> filterDelete(Context context, DeleteRequest request, RequestHandler next) { return next.handleDelete(context, request); } @Inject ApplicationV1Filter(final ResourceTypeService resourceTypeService, ...
### Question: AMIdentityMembershipCondition extends EntitlementConditionAdaptor { @Override public ConditionDecision evaluate(String realm, Subject subject, String resourceName, Map<String, Set<String>> env) throws EntitlementException { String subjectPrincipal = SubjectUtils.getPrincipalId(subject); if (debug.messageE...
### Question: IOFactory { void writeContent(BufferedWriter writer, File content, ContentConverter contentConverter) throws IOException { BufferedReader contentReader = null; try { contentReader = newReader(content); String line; while ((line = contentReader.readLine()) != null) { writeLine(writer, contentConverter.conv...
### Question: PrivilegeValidator { public void validateReferralPrivilege(ReferralPrivilege referralPrivilege) throws EntitlementException { Set<String> referralPrivilegeRealms = referralPrivilege.getRealms(); realmValidator.validateRealms(referralPrivilegeRealms); } @Inject PrivilegeValidator(RealmValidator realmValid...
### Question: AuditEventPublisherImpl implements AuditEventPublisher { @Override public void tryPublish(String topic, AuditEvent auditEvent) { try { String realm = getValue(auditEvent.getValue(), EVENT_REALM, null); if (isBlank(realm)) { publishToDefault(topic, auditEvent); } else { publishForRealm(realm, topic, auditE...
### Question: AuditServiceProviderImpl implements AuditServiceProvider { @Override public AMAuditService getAuditService(String realm) { AMAuditService auditService = auditServices.get(realm.toLowerCase()); if (auditService == null) { return defaultAuditService; } else { return auditService; } } @Inject AuditServicePr...
### Question: PositiveIntegerValidator implements ServiceAttributeValidator { @Override public boolean validate(Set<String> values) { if (values.isEmpty()) { return false; } for (String value : values) { int intValue; try { intValue = Integer.parseInt(value); } catch (NumberFormatException nfe) { return false; } if (in...
### Question: ElasticsearchAuditEventHandlerFactory implements AuditEventHandlerFactory { @Override public AuditEventHandler create(AuditEventHandlerConfiguration configuration) throws AuditException { final ElasticsearchAuditEventHandlerConfiguration esHandlerConfiguration = new ElasticsearchAuditEventHandlerConfigura...
### Question: SmsServiceHandlerFunction implements Predicate<String> { @Override public boolean apply(String serviceName) { for (Predicate<String> handled : ALREADY_HANDLED) { if (handled.apply(serviceName)) { return false; } } return true; } @Inject SmsServiceHandlerFunction(@Named("authenticationServices") Set<Strin...
### Question: SmsJsonConverter { public Map<String, Set<String>> fromJson(JsonValue jsonValue) throws JsonException, BadRequestException { return fromJson(null, jsonValue); } @Inject SmsJsonConverter(ServiceSchema schema); JsonValue toJson(Map<String, Set<String>> attributeValuePairs, boolean validate); JsonValue toJs...
### Question: SmsResourceProvider { protected String realmFor(Context context) { return context.containsContext(RealmContext.class) ? context.asContext(RealmContext.class).getResolvedRealm() : null; } SmsResourceProvider(ServiceSchema schema, SchemaType type, List<ServiceSchema> subSchemaPath, String uriPath, ...
### Question: SmsResourceProvider { @Action public Promise<ActionResponse, ResourceException> getType(Context context) { try { return newActionResponse(getTypeValue(context)).asPromise(); } catch (SMSException | SSOException e) { return new InternalServerErrorException("Could not get service schema", e).asPromise(); } ...
### Question: CoreTokenResource implements CollectionResourceProvider { public Promise<ResourceResponse, ResourceException> deleteInstance(Context serverContext, String tokenId, DeleteRequest deleteRequest) { String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(serverContext); try { store.deleteAsync...
### Question: UserPushDeviceProfileManager { public PushDeviceSettings createDeviceProfile() { byte[] secretBytes = new byte[SECRET_BYTE_LENGTH]; secureRandom.nextBytes(secretBytes); String sharedSecret = Base64.encode(secretBytes); return new PushDeviceSettings(sharedSecret, DEVICE_NAME); } @Inject UserPushDeviceProf...
### Question: PassThroughFilter implements Filter { @Override public Promise<ActionResponse, ResourceException> filterAction(Context context, ActionRequest request, RequestHandler next) { return next.handleAction(context, request); } @Override Promise<ActionResponse, ResourceException> filterAction(Context context, Ac...
### Question: PassThroughFilter implements Filter { @Override public Promise<ResourceResponse, ResourceException> filterCreate(Context context, CreateRequest request, RequestHandler next) { return next.handleCreate(context, request); } @Override Promise<ActionResponse, ResourceException> filterAction(Context context, ...
### Question: PassThroughFilter implements Filter { @Override public Promise<ResourceResponse, ResourceException> filterDelete(Context context, DeleteRequest request, RequestHandler next) { return next.handleDelete(context, request); } @Override Promise<ActionResponse, ResourceException> filterAction(Context context, ...
### Question: AttributeUtils { public static boolean isBinaryAttribute(String attributeName) { return attributeName != null && attributeName.endsWith(BINARY_FLAG); } private AttributeUtils(); static boolean isStaticAttribute(String attributeName); static String removeStaticAttributeFlag(String attributeName); static b...
### Question: AttributeUtils { public static String removeBinaryAttributeFlag(String attributeName) { if (isBinaryAttribute(attributeName)) { return attributeName.substring(0, attributeName.lastIndexOf(BINARY_FLAG)); } else { return attributeName; } } private AttributeUtils(); static boolean isStaticAttribute(String a...
### Question: AttributeUtils { public static boolean isStaticAttribute(String attributeName) { return attributeName != null && attributeName.startsWith(STATIC_QUOTE) && attributeName.endsWith(STATIC_QUOTE); } private AttributeUtils(); static boolean isStaticAttribute(String attributeName); static String removeStaticAt...
### Question: AttributeUtils { public static String removeStaticAttributeFlag(String attributeName) { if (isStaticAttribute(attributeName)) { return attributeName.substring(STATIC_QUOTE.length(), attributeName.length() - STATIC_QUOTE.length()); } else { return attributeName; } } private AttributeUtils(); static boolea...
### Question: PassThroughFilter implements Filter { @Override public Promise<ResourceResponse, ResourceException> filterPatch(Context context, PatchRequest request, RequestHandler next) { return next.handlePatch(context, request); } @Override Promise<ActionResponse, ResourceException> filterAction(Context context, Act...
### Question: ValidateIPaddress { public static boolean isValidIP(String ipAddress) { return ValidateIPaddress.isIPv4(ipAddress) || ValidateIPaddress.isIPv6(ipAddress); } private ValidateIPaddress(); static boolean isIPv4(String ipAddress); static boolean isIPv6(String ipAddress); static boolean isValidIP(String ipAdd...
### Question: PassThroughFilter implements Filter { @Override public Promise<QueryResponse, ResourceException> filterQuery(Context context, QueryRequest request, QueryResourceHandler handler, RequestHandler next) { return next.handleQuery(context, request, handler); } @Override Promise<ActionResponse, ResourceExceptio...
### Question: AMKeyProvider implements KeyProvider { @Override public SecretKey getSecretKey(String certAlias) { try { Key key = ks.getKey(certAlias, privateKeyPass.toCharArray()); if (key instanceof SecretKey) { return (SecretKey) key; } logger.error("Expected a key of type javax.crypto.SecretKey but got " + key.getCl...
### Question: PassThroughFilter implements Filter { @Override public Promise<ResourceResponse, ResourceException> filterRead(Context context, ReadRequest request, RequestHandler next) { return next.handleRead(context, request); } @Override Promise<ActionResponse, ResourceException> filterAction(Context context, Action...
### Question: PassThroughFilter implements Filter { @Override public Promise<ResourceResponse, ResourceException> filterUpdate(Context context, UpdateRequest request, RequestHandler next) { return next.handleUpdate(context, request); } @Override Promise<ActionResponse, ResourceException> filterAction(Context context, ...
### Question: UserPushDeviceProfileManager { public void saveDeviceProfile(@Nonnull String user, @Nonnull String realm, @Nonnull PushDeviceSettings deviceSettings) throws AuthLoginException { Reject.ifNull(user, realm, deviceSettings); try { devicesDao.saveDeviceProfiles(user, realm, jsonUtils.toJsonValues(Collections....
### Question: SnsMessageResource { @Action public Promise<ActionResponse, ResourceException> authenticate(Context context, ActionRequest actionRequest) { return handle(context, actionRequest); } @Inject SnsMessageResource(CTSPersistentStore coreTokenService, PushNotificationService pushNotificationService, ...
### Question: HS256Helper { public String answerAsString() { if (result == null) { return null; } return Base64.encode(result); } HS256Helper(byte[] secret, String challenge); String answerAsString(); byte[] answerAsBytes(); void setSecret(byte[] secret); void setChallenge(String challenge); }### Answer: @Test public ...
### Question: MessageDispatcher { public MessagePromise expect(String messageId, Set<Predicate> predicates) { Reject.ifTrue(StringUtils.isBlank(messageId)); Reject.ifNull(predicates); MessagePromise mp = new MessagePromise(PromiseImpl.<JsonValue, Exception>create(), predicates); cache.put(messageId, mp); return mp; } @...
### Question: MessageDispatcher { public void handle(String messageId, JsonValue content) throws NotFoundException, PredicateNotMetException { Reject.ifNull(content); Reject.ifNull(messageId); MessagePromise messagePromise = cache.getIfPresent(messageId); if (messagePromise != null) { for (Predicate p : messagePromise....
### Question: MessageDispatcher { public boolean forget(String messageId) { MessagePromise messagePromise = cache.getIfPresent(messageId); if (messagePromise != null) { cache.invalidate(messageId); return true; } return false; } @Inject MessageDispatcher(Cache<String, MessagePromise> dispatch, @Named("frPush") Debug d...
### Question: PushMessage { public String getMessageId() { return messageId; } PushMessage(String recipient, String body, String subject, String messageId); PushMessage(String recipient, String body, String subject); String getRecipient(); String getBody(); String getSubject(); String getMessageId(); static final Stri...
### Question: DefaultAuthenticationStatementsProvider implements AuthenticationStatementsProvider { public List<AuthnStatement> get(SAML2Config saml2Config, String authNContextClassRef) throws TokenCreationException { try { AuthnStatement authnStatement = AssertionFactory.getInstance().createAuthnStatement(); authnStat...
### Question: UserPushDeviceProfileManager { public String createRandomBytes(int byteNum) { byte[] secretBytes = new byte[byteNum]; secureRandom.nextBytes(secretBytes); return Base64.encode(secretBytes); } @Inject UserPushDeviceProfileManager(final @Nonnull PushDevicesDao devicesDao, ...
### Question: DirectoryHelper { public String convertToInetUserStatus(String value, String activeValue) { return isActive(value, activeValue) ? STATUS_ACTIVE : STATUS_INACTIVE; } byte[] encodePassword(IdType type, byte[][] binaryValues); byte[] encodePassword(IdType type, Set<String> passwordValues); byte[] encodePass...
### Question: UpgradeServerDefaultsStep extends AbstractUpgradeStep { private Map<String, String> calculateModifiedServerDefaults(Map<String, String> newDefaults, Map<String, String> existingDefaults) throws UpgradeException { Set<String> attrsToUpgrade = ServerUpgrade.getAttrsToUpgrade(); return calculateModifiedServe...
### Question: CrestAuditor { void auditAccessAttempt() { if (auditEventPublisher.isAuditing(realm, ACCESS_TOPIC, EventName.AM_ACCESS_ATTEMPT)) { AMAccessAuditEventBuilder builder = auditEventFactory.accessEvent(realm) .forHttpRequest(context, request) .timestamp(startTime, auditEventPublisher.isLtzEnabled()) .transacti...
### Question: ElevatedConnectionFactoryWrapper implements ConnectionFactory { @Override public Connection getConnection() throws ResourceException { Connection connection = connectionFactory.getConnection(); SSOToken ssoToken = ssoTokenPrivilegedAction.run(); return new ElevatedConnection(connection, ssoToken); } @Inje...
### Question: RestUtils { public static String getMimeHeaderValue(final Context serverContext, final String headerName) { final HttpContext httpContext = serverContext.asContext(HttpContext.class); final String headerValue = httpContext.getHeaderAsString(headerName); try { return headerValue == null ? null : MimeUtilit...
### Question: UpgradeServerDefaultsStep extends AbstractUpgradeStep { private Set<String> calculateDeletedServerDefaults(Map<String, String> existingDefaults) throws IOException { Properties validProperties = new Properties(); validProperties.load(getClass().getResourceAsStream(VALID_SERVER_CONFIG_PROPERTIES)); Map<Str...
### Question: DefaultClientSecretGenerator extends DefaultValues { @Override public Set<String> getDefaultValues() { return generateSecretHolder(); } @Override Set<String> getDefaultValues(); }### Answer: @Test public void testGetDefaultValues() { final DefaultClientSecretGenerator secretGenerator = new DefaultClient...
### Question: ScriptResource extends RealmAwareResource { @Override public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request) { try { serviceFactory.create(getRealm(context)).delete(resourceId); return newResultPromise(newResourceResponse(resourceId, n...
### Question: ScriptConfigurationService implements ScriptingService, ServiceListener { @Override public ScriptConfiguration get(String uuid) throws ScriptException { lock.readLock().lock(); try { failIfUuidDoesNotExist(uuid); ScriptConfiguration realmConfiguration = realmConfigurations.get(uuid); return realmConfigura...
### Question: ObservedContextFactory extends ContextFactory { @Override protected void observeInstructionCount(Context cx, int instructionCount) { final ObservedJavaScriptContext context = (ObservedJavaScriptContext) cx; final long timeout = TimeUnit.MILLISECONDS.convert(manager.getConfiguration().getScriptExecutionTim...
### Question: UmaIdRepoCreationListener implements IdRepoCreationListener { @Override public synchronized void notify(AMIdentityRepository idRepo, String realm) { String normalizedRealm = coreWrapper.convertRealmNameToOrgName(realm); if (!registeredRealms.contains(normalizedRealm)) { idRepo.addEventListener(policyAppli...