use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class ApplicationsResource method queryCollection.
/**
* Queries for a collection of resources.
*
* @param context {@inheritDoc}
* @param request {@inheritDoc}
* @param handler {@inheritDoc}
*/
@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest request, QueryResourceHandler handler) {
//auth
final Subject mySubject = getContextSubject(context);
if (mySubject == null) {
debug.error("ApplicationsResource :: UPDATE : Unknown Subject");
return new BadRequestException().asPromise();
}
//select
final String realm = getRealm(context);
final String principalName = PrincipalRestUtils.getPrincipalNameFromSubject(mySubject);
try {
List<ResourceResponse> results = new ArrayList<>();
final Set<String> appNames = query(request, mySubject, realm);
for (String appName : appNames) {
final Application application = appManager.getApplication(mySubject, realm, appName);
if (application == null) {
debug.warning("Unable to find application " + appName);
continue;
}
ApplicationWrapper wrapper = createApplicationWrapper(application, appTypeManagerWrapper);
results.add(newResourceResponse(wrapper.getName(), null, wrapper.toJsonValue()));
}
QueryResponsePresentation.enableDeprecatedRemainingQueryResponse(request);
return QueryResponsePresentation.perform(handler, request, results);
} catch (EntitlementException e) {
if (debug.errorEnabled()) {
debug.error("ApplicationsResource :: QUERY by " + principalName + ": Failed to query resource.", e);
}
return exceptionMappingHandler.handleError(context, request, e).asPromise();
}
}
use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class IdentityResourceExceptionMappingHandler method handleError.
@Override
public ResourceException handleError(IdRepoException idRepoException) {
int code = Integer.valueOf(idRepoException.getErrorCode());
ResultCode ldapResultCode = ResultCode.valueOf(idRepoException.getLdapErrorIntCode());
if (idRepoException instanceof PasswordPolicyException) {
//Convert the error code for the LDAP code
if (ldapResultCode == ResultCode.INVALID_CREDENTIALS) {
idRepoException = new PasswordPolicyException(ldapResultCode, IdRepoErrorCode.OLD_PASSWORD_INCORRECT, idRepoException.getMessageArgs());
}
if (ldapResultCode == ResultCode.INSUFFICIENT_ACCESS_RIGHTS) {
return new ForbiddenException(idRepoException);
}
if (ldapResultCode == ResultCode.CONSTRAINT_VIOLATION) {
idRepoException = new PasswordPolicyException(idRepoException.getConstraintViolationDetails());
}
return new BadRequestException(idRepoException.getMessage());
}
//compute LDAP error
if (ldapResultCode == ResultCode.NO_SUCH_OBJECT) {
return new NotFoundException(idRepoException);
}
if (ldapResultCode == ResultCode.NOT_ALLOWED_ON_RDN) {
return new ForbiddenException(idRepoException);
}
// Compute error code
switch(code) {
case GENERAL_OBJECT_NOT_FOUND:
return new NotFoundException(idRepoException);
case GENERAL_ACCESS_DENIED:
return new ForbiddenException(idRepoException);
default:
return new InternalServerErrorException(idRepoException);
}
}
use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class MailService method sendEmail.
// Mapping to known type
@SuppressWarnings("unchecked")
private JsonValue sendEmail(String realm, JsonValue jsonValue) throws ResourceException {
String to = jsonValue.get("to").asString();
if (isBlank(to)) {
throw new BadRequestException("to field is missing");
}
String mimeType = jsonValue.get("type").asString();
if (isBlank(mimeType)) {
throw new BadRequestException("mime type needs to be specified");
}
String subject = jsonValue.get("subject").asString();
String body = jsonValue.get("body").asString();
Map<String, Set<String>> mailConfigAttributes;
try {
ServiceConfigManager configManager = new ServiceConfigManager(RestUtils.getToken(), MailServerImpl.SERVICE_NAME, MailServerImpl.SERVICE_VERSION);
ServiceConfig mailConfig = configManager.getOrganizationConfig(realm, null);
mailConfigAttributes = mailConfig.getAttributes();
} catch (SMSException | SSOException e) {
throw new InternalServerErrorException("Cannot create the service " + MailServerImpl.SERVICE_NAME, e);
}
if (isEmpty(mailConfigAttributes)) {
throw new InternalServerErrorException("No service mail config found for realm " + realm);
}
MailServer mailServer;
try {
String attr = mailConfigAttributes.get(MAIL_SERVER_CLASS).iterator().next();
mailServer = mailServerLoader.load(attr, realm);
} catch (IllegalStateException e) {
throw new InternalServerErrorException("Failed to create mail server", e);
}
if (isBlank(subject)) {
subject = mailConfigAttributes.get(MAIL_SUBJECT).iterator().next();
}
if (isBlank(body)) {
body = mailConfigAttributes.get(MAIL_BODY).iterator().next();
}
try {
mailServer.sendEmail(to, subject, body, mimeType);
} catch (MessagingException e) {
throw new InternalServerErrorException("Failed to send email", e);
}
return json(object(field("success", "true")));
}
use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class CrestProtocolEnforcementFilter method defaultProtocolVersion.
private Version defaultProtocolVersion(Request request) throws BadRequestException {
AcceptApiVersionHeader apiVersionHeader;
try {
apiVersionHeader = AcceptApiVersionHeader.valueOf(request);
} catch (IllegalArgumentException e) {
throw new BadRequestException(e);
}
apiVersionHeader.withDefaultProtocolVersion(ENFORCE_PROTOCOL_VERSION);
request.getHeaders().put(apiVersionHeader);
return apiVersionHeader.getProtocolVersion();
}
use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.
the class RestSTSPublishServiceRequestHandler method handleUpdate.
/*
* A PUT to the url composed of the publish endpont + the sts instance id with a payload corresponding to a
* RestSTSInstanceId (wrapped in invocation context information) will result in republishing the existing instance
* (which is a delete followed by a create).
*/
public Promise<ResourceResponse, ResourceException> handleUpdate(Context context, UpdateRequest request) {
String stsId = request.getResourcePath();
String realm = getRealmFromResourceName(request.getResourcePath());
if (!realmValidator.isRealm(realm)) {
logger.warn("Update of rest STS instance state for instance " + stsId + " in realm " + realm + " rejected because realm does not exist");
return new NotFoundException("The specified realm does not exist.").asPromise();
}
/*
Insure that the instance is published before performing an update.
*/
final boolean publishedToSMS;
try {
publishedToSMS = publisher.isInstancePersistedInSMS(stsId, realm);
} catch (STSPublishException e) {
logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught determining whether " + "instance persisted in SMS. Instance not updated. Exception: " + e, e);
return e.asPromise();
}
final boolean publishedToCrest = publisher.isInstanceExposedInCrest(stsId);
if (publishedToSMS) {
if (!publishedToCrest) {
/*
Entering this branch would seem to be an error condition. It could possibly happen in a site deployment,
where a rest sts instance is published to a different server than the current server, and the registered
ServiceListener was not called when the ldap replication created the service entry on the current server.
I will log a warning, and still publish the instance, just for robustness.
*/
logger.warn("The rest sts instance " + stsId + " in realm " + realm + " is present in the SMS, but " + "has not been hung off of the CREST router. This is an illegal state. The instance will be" + " republished.");
}
RestSTSInstanceConfig instanceConfig;
try {
instanceConfig = marshalInstanceConfigFromInvocation(request.getContent());
} catch (BadRequestException e) {
logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught marshalling " + "invocation state to RestSTSInstanceConfig. Instance not updated. The state: " + request.getContent() + "Exception: " + e, e);
return e.asPromise();
}
Injector instanceInjector;
try {
instanceInjector = createInjector(instanceConfig);
} catch (ResourceException e) {
logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught creating an " + "Injector using the RestSTSInstanceConfig. The instance: " + instanceConfig.toJson() + "; Exception: " + e, e);
return e.asPromise();
}
try {
publisher.updateInstanceInSMS(stsId, realm, instanceConfig, instanceInjector.getInstance(RestSTS.class));
return newResultPromise(newResourceResponse(instanceConfig.getDeploymentSubPath(), Integer.toString(instanceConfig.hashCode()), json(object(field(RESULT, SUCCESS)))));
} catch (STSPublishException e) {
logger.error("In RestSTSPublishServiceRequestHandler#handleUpdate, exception caught removing " + "rest sts instance " + instanceConfig.getDeploymentSubPath() + ". This means instance is" + "in indeterminate state, and has not been updated. The instance config: " + instanceConfig + "; Exception: " + e, e);
return e.asPromise();
}
} else {
//404 - realm and id not found in SMS
return new NotFoundException("No rest sts instance with id " + stsId + " in realm " + realm).asPromise();
}
}
Aggregations