use of org.forgerock.json.resource.NotSupportedException in project OpenAM by OpenRock.
the class Endpoints method from.
/**
* Produce a {@code Handler} from the annotated methods on the provided object.
* <p>
* This method currently only distinguishes requests by their method type. In future this
* should be extended to support selection by request and response media types, and request
* path.
* @param obj The object containing annotated methods.
* @return A new {@code Handler}.
*/
public static Handler from(final Object obj) {
final Map<String, AnnotatedMethod> methods = new HashMap<>();
methods.put("DELETE", AnnotatedMethod.findMethod(obj, Delete.class));
methods.put("GET", AnnotatedMethod.findMethod(obj, Get.class));
methods.put("POST", AnnotatedMethod.findMethod(obj, Post.class));
methods.put("PUT", AnnotatedMethod.findMethod(obj, Put.class));
return new Handler() {
@Override
public Promise<Response, NeverThrowsException> handle(Context context, Request request) {
AnnotatedMethod method = methods.get(getMethod(request));
if (method == null) {
Response response = new Response(Status.METHOD_NOT_ALLOWED);
response.setEntity(new NotSupportedException().toJsonValue().getObject());
return newResultPromise(response);
}
return method.invoke(context, request);
}
};
}
use of org.forgerock.json.resource.NotSupportedException in project OpenAM by OpenRock.
the class SmsCollectionProvider method queryCollection.
/**
* Queries for child instances of config. The parent config referenced by the request path is found, and
* all child config for the type is returned.
* <p>
* Note that only query filter is supported, and only a filter of value {@code true} (i.e. all values).
* Sorting and paging are not supported.
* {@inheritDoc}
*/
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
if (!"true".equals(request.getQueryFilter().toString())) {
return new NotSupportedException("Query not supported: " + request.getQueryFilter()).asPromise();
}
if (request.getPagedResultsCookie() != null || request.getPagedResultsOffset() > 0 || request.getPageSize() > 0) {
return new NotSupportedException("Query paging not currently supported").asPromise();
}
try {
ServiceConfigManager scm = getServiceConfigManager(context);
String realm = realmFor(context);
if (subSchemaPath.isEmpty()) {
Set<String> instanceNames = new TreeSet<String>(scm.getInstanceNames());
for (String instanceName : instanceNames) {
ServiceConfig config = type == SchemaType.GLOBAL ? scm.getGlobalConfig(instanceName) : scm.getOrganizationConfig(realm, instanceName);
if (config != null) {
JsonValue value = getJsonValue(realm, config);
handler.handleResource(newResourceResponse(instanceName, String.valueOf(value.hashCode()), value));
}
}
} else {
ServiceConfig config = parentSubConfigFor(context, scm);
Set<String> names = config.getSubConfigNames("*", lastSchemaNodeName());
for (String configName : names) {
JsonValue value = getJsonValue(realm, config.getSubConfig(configName));
handler.handleResource(newResourceResponse(configName, String.valueOf(value.hashCode()), value));
}
}
return newResultPromise(newQueryResponse());
} catch (SMSException e) {
debug.warning("::SmsCollectionProvider:: SMSException on query", e);
return new InternalServerErrorException("Unable to query SMS config: " + e.getMessage()).asPromise();
} catch (SSOException e) {
debug.warning("::SmsCollectionProvider:: SSOException on query", e);
return new InternalServerErrorException("Unable to query SMS config: " + e.getMessage()).asPromise();
}
}
use of org.forgerock.json.resource.NotSupportedException in project OpenAM by OpenRock.
the class OathDevicesResource method actionCollection.
/**
* {@inheritDoc}
*/
@Override
public Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request) {
try {
//could be admin
final AMIdentity identity = getUserIdFromUri(context);
final AuthenticatorOathService realmOathService = oathServiceFactory.create(getRealm(context));
switch(request.getAction()) {
case SKIP:
try {
final boolean setValue = request.getContent().get(VALUE).asBoolean();
realmOathService.setUserSkipOath(identity, setValue ? AuthenticatorOathService.SKIPPABLE : AuthenticatorOathService.NOT_SKIPPABLE);
return newResultPromise(newActionResponse(JsonValueBuilder.jsonValue().build()));
} catch (SSOException | IdRepoException e) {
debug.error("OathDevicesResource :: SKIP action - Unable to set value in user store.", e);
return new InternalServerErrorException().asPromise();
}
case CHECK:
try {
final Set resultSet = identity.getAttribute(realmOathService.getSkippableAttributeName());
boolean result = false;
if (CollectionUtils.isNotEmpty(resultSet)) {
String tmp = (String) resultSet.iterator().next();
int resultInt = Integer.valueOf(tmp);
if (resultInt == AuthenticatorOathService.SKIPPABLE) {
result = true;
}
}
return newResultPromise(newActionResponse(JsonValueBuilder.jsonValue().put(RESULT, result).build()));
} catch (SSOException | IdRepoException e) {
debug.error("OathDevicesResource :: CHECK action - Unable to read value from user store.", e);
return new InternalServerErrorException().asPromise();
}
case //sets their 'skippable' selection to default (NOT_SET) and deletes their profiles attribute
RESET:
try {
realmOathService.setUserSkipOath(identity, AuthenticatorOathService.NOT_SET);
realmOathService.removeAllUserDevices(identity);
return newResultPromise(newActionResponse(JsonValueBuilder.jsonValue().put(RESULT, true).build()));
} catch (SSOException | IdRepoException e) {
debug.error("OathDevicesResource :: Action - Unable to reset identity attributes", e);
return new InternalServerErrorException().asPromise();
}
default:
return new NotSupportedException().asPromise();
}
} catch (SMSException e) {
debug.error("OathDevicesResource :: Action - Unable to communicate with the SMS.", e);
return new InternalServerErrorException().asPromise();
} catch (SSOException | InternalServerErrorException e) {
debug.error("OathDevicesResource :: Action - Unable to retrieve identity data from request context", e);
return new InternalServerErrorException().asPromise();
}
}
use of org.forgerock.json.resource.NotSupportedException in project OpenAM by OpenRock.
the class IdentityResourceV2 method createRegistrationEmail.
/**
* This method will create a confirmation email that contains a {@link org.forgerock.openam.cts.api.tokens.Token},
* confirmationId and email that was provided in the request.
* @param context Current Server Context
* @param request Request from client to retrieve id
*/
private Promise<ActionResponse, ResourceException> createRegistrationEmail(final Context context, final ActionRequest request, final String realm, final RestSecurity restSecurity) {
JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
final JsonValue jVal = request.getContent();
String emailAddress = null;
String confirmationLink;
String tokenID;
try {
if (restSecurity == null) {
if (debug.warningEnabled()) {
debug.warning("IdentityResource.createRegistrationEmail(): Rest Security not created. " + "restSecurity={}", restSecurity);
}
throw new NotFoundException("Rest Security Service not created");
}
if (!restSecurity.isSelfServiceRestEndpointEnabled()) {
if (debug.warningEnabled()) {
debug.warning("IdentityResource.createRegistrationEmail(): Self-Registration set to : {}", restSecurity.isSelfServiceRestEndpointEnabled());
}
throw new NotSupportedException("Legacy Self Service REST Endpoint is not enabled.");
}
if (!restSecurity.isSelfRegistration()) {
if (debug.warningEnabled()) {
debug.warning("IdentityResource.createRegistrationEmail(): Self-Registration set to : {}", restSecurity.isSelfRegistration());
}
throw new NotSupportedException("Self Registration is not enabled.");
}
// Get full deployment URL
HttpContext header = context.asContext(HttpContext.class);
String baseURL = baseURLProviderFactory.get(realm).getRootURL(header);
// Get the email address provided from registration page
emailAddress = jVal.get(EMAIL).asString();
if (StringUtils.isBlank(emailAddress)) {
throw new BadRequestException("Email not provided");
}
String subject = jVal.get("subject").asString();
String message = jVal.get("message").asString();
// Retrieve email registration token life time
Long tokenLifeTime = restSecurity.getSelfRegTLT();
// Create CTS Token
org.forgerock.openam.cts.api.tokens.Token ctsToken = generateToken(emailAddress, "anonymous", tokenLifeTime, realm);
// Store token in datastore
CTSHolder.getCTS().createAsync(ctsToken);
tokenID = ctsToken.getTokenId();
// Create confirmationId
String confirmationId = Hash.hash(tokenID + emailAddress + SystemProperties.get(AM_ENCRYPTION_PWD));
// Build Confirmation URL
String confURL = restSecurity.getSelfRegistrationConfirmationUrl();
StringBuilder confURLBuilder = new StringBuilder(100);
if (StringUtils.isEmpty(confURL)) {
confURLBuilder.append(baseURL).append("/json/confirmation/register");
} else if (confURL.startsWith("/")) {
confURLBuilder.append(baseURL).append(confURL);
} else {
confURLBuilder.append(confURL);
}
confirmationLink = confURLBuilder.append("?confirmationId=").append(requestParamEncode(confirmationId)).append("&email=").append(requestParamEncode(emailAddress)).append("&tokenId=").append(requestParamEncode(tokenID)).append("&realm=").append(realm).toString();
// Send Registration
sendNotification(emailAddress, subject, message, realm, confirmationLink);
if (debug.messageEnabled()) {
debug.message("IdentityResource.createRegistrationEmail() :: Sent notification to={} with subject={}. " + "In realm={} for token ID={}", emailAddress, subject, realm, tokenID);
}
return newResultPromise(newActionResponse(result));
} catch (BadRequestException be) {
debug.warning("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, be);
return be.asPromise();
} catch (NotFoundException nfe) {
debug.warning("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, nfe);
return nfe.asPromise();
} catch (NotSupportedException nse) {
if (debug.warningEnabled()) {
debug.warning("IdentityResource.createRegistrationEmail(): Operation not enabled. email={}", emailAddress, nse);
}
return nse.asPromise();
} catch (Exception e) {
debug.error("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, e);
return new NotFoundException("Email not sent").asPromise();
}
}
use of org.forgerock.json.resource.NotSupportedException in project OpenAM by OpenRock.
the class IdentityResourceV2 method actionInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ActionResponse, ResourceException> actionInstance(final Context context, final String resourceId, final ActionRequest request) {
String action = request.getAction();
if ("changePassword".equalsIgnoreCase(action)) {
RealmContext realmContext = context.asContext(RealmContext.class);
final String realm = realmContext.getResolvedRealm();
JsonValue value = request.getContent();
try {
String userPassword = value.get(USER_PASSWORD).asString();
if (StringUtils.isBlank(userPassword)) {
throw new BadRequestException("'" + USER_PASSWORD + "' attribute not set in JSON content.");
}
String currentPassword = value.get(CURRENT_PASSWORD).asString();
if (StringUtils.isBlank(currentPassword)) {
throw new BadRequestException("'" + CURRENT_PASSWORD + "' attribute not set in JSON content.");
}
IdentityRestUtils.changePassword(context, realm, resourceId, currentPassword, userPassword);
if (debug.messageEnabled()) {
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
debug.message("IdentityResource.actionInstance :: ACTION of change password for " + resourceId + " in realm " + realm + " performed by " + principalName);
}
return newResultPromise(newActionResponse(json(object())));
} catch (ResourceException re) {
debug.warning("Cannot change password! " + resourceId + ":" + re);
return re.asPromise();
}
} else {
return new NotSupportedException(action + " not supported for resource instances").asPromise();
}
}
Aggregations