use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class RealmResource method readInstance.
/**
* {@inheritDoc}
*/
@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
ResourceResponse resource;
JsonValue jval;
String holdResourceId = checkForTopLevelRealm(resourceId);
try {
hasPermission(context);
if (holdResourceId != null && !holdResourceId.startsWith("/")) {
holdResourceId = "/" + holdResourceId;
}
if (!realmPath.equalsIgnoreCase("/")) {
holdResourceId = realmPath + holdResourceId;
}
OrganizationConfigManager ocm = new OrganizationConfigManager(getSSOToken(), holdResourceId);
// get associated services for this realm , include mandatory service names.
Set serviceNames = ocm.getAssignedServices();
jval = createJsonMessage(SERVICE_NAMES, serviceNames);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
resource = newResourceResponse(resourceId, String.valueOf(System.currentTimeMillis()), jval);
if (debug.messageEnabled()) {
debug.message("RealmResource.readInstance :: READ : Successfully read realm, " + resourceId + " performed by " + principalName);
}
return newResultPromise(resource);
} catch (SSOException sso) {
debug.error("RealmResource.updateInstance() : Cannot READ " + resourceId, sso);
return new PermanentException(401, "Access Denied", null).asPromise();
} catch (ForbiddenException fe) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId + ":" + fe);
return fe.asPromise();
} catch (SMSException smse) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, smse);
try {
configureErrorMessage(smse);
return new BadRequestException(smse.getMessage(), smse).asPromise();
} catch (NotFoundException nf) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, nf);
return nf.asPromise();
} catch (ForbiddenException fe) {
// User does not have authorization
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, fe);
return fe.asPromise();
} catch (PermanentException pe) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, pe);
// Cannot recover from this exception
return pe.asPromise();
} catch (ConflictException ce) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, ce);
return ce.asPromise();
} catch (BadRequestException be) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, be);
return be.asPromise();
} catch (Exception e) {
debug.error("RealmResource.readInstance() : Cannot READ " + resourceId, e);
return new BadRequestException(e.getMessage(), e).asPromise();
}
} catch (Exception e) {
return new BadRequestException(e.getMessage(), e).asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class SmsRealmProvider method handleDelete.
@Override
public Promise<ResourceResponse, ResourceException> handleDelete(Context serverContext, DeleteRequest request) {
RealmContext realmContext = serverContext.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
try {
OrganizationConfigManager realmManager = new OrganizationConfigManager(getSSOToken(), realmPath);
final ResourceResponse resource = getResource(getJsonValue(realmPath));
realmManager.deleteSubOrganization(null, false);
String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(serverContext);
debug.message("RealmResource.deleteInstance :: DELETE of realm " + realmPath + " performed by " + principalName);
return newResultPromise(resource);
} catch (SMSException smse) {
ResourceException exception = configureErrorMessage(smse);
if (exception instanceof NotFoundException) {
debug.warning("RealmResource.deleteInstance() : Cannot find {}", realmPath, smse);
return exception.asPromise();
} else if (exception instanceof ForbiddenException || exception instanceof PermanentException || exception instanceof ConflictException || exception instanceof BadRequestException) {
debug.warning("RealmResource.deleteInstance() : Cannot DELETE {}", realmPath, smse);
return exception.asPromise();
} else {
return new BadRequestException(exception.getMessage(), exception).asPromise();
}
} catch (Exception e) {
return new BadRequestException(e.getMessage(), e).asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class SmsRealmProvider method handleRead.
@Override
public Promise<ResourceResponse, ResourceException> handleRead(Context context, ReadRequest request) {
RealmContext realmContext = context.asContext(RealmContext.class);
String realmPath = realmContext.getResolvedRealm();
if (!request.getResourcePath().isEmpty()) {
//if the resource path is not empty, the realm has not resolved correctly
return new NotFoundException("Realm \"" + RealmUtils.concatenateRealmPath(RealmUtils.cleanRealm(realmPath), RealmUtils.cleanRealm(request.getResourcePath())) + "\" is not a valid realm.").asPromise();
}
try {
JsonValue jsonResponse = getJsonValue(realmPath);
if (debug.messageEnabled()) {
debug.message("RealmResource.readInstance :: READ : Successfully read realm, " + realmPath + " performed by " + PrincipalRestUtils.getPrincipalNameFromServerContext(context));
}
return newResultPromise(getResource(jsonResponse));
} catch (SMSException smse) {
ResourceException exception = configureErrorMessage(smse);
if (exception instanceof NotFoundException) {
debug.warning("RealmResource.readInstance() : Cannot find {}", realmPath, smse);
return exception.asPromise();
} else if (exception instanceof ForbiddenException || exception instanceof PermanentException || exception instanceof ConflictException || exception instanceof BadRequestException) {
debug.warning("RealmResource.readInstance() : Cannot READ {}", realmPath, smse);
return exception.asPromise();
} else {
return new BadRequestException(exception.getMessage(), exception).asPromise();
}
} catch (Exception e) {
return new BadRequestException(e.getMessage(), e).asPromise();
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class XMLResourceExceptionHandler method write.
@Override
public void write(MessageContext context, AuthenticationException exception) {
Reject.ifNull(exception);
try {
ResourceException jre;
if (exception instanceof AuthenticationFailedException) {
jre = new PermanentException(Status.UNAUTHORIZED.getCode(), exception.getMessage(), null);
} else if (exception.getCause() instanceof ResourceException) {
jre = (ResourceException) exception.getCause();
} else {
LOGGER.error(exception.getMessage(), exception);
jre = new InternalServerErrorException("Authentication Failed", exception);
}
AuditTrail auditTrail = context.getAuditTrail();
List<Map<String, Object>> failureReasonList = auditTrail.getFailureReasons();
if (failureReasonList != null && !failureReasonList.isEmpty()) {
jre.setDetail(json(object(field("failureReasons", failureReasonList))));
}
Response response = context.getResponse();
response.setStatus(Status.valueOf(jre.getCode()));
context.<Response>getResponse().getHeaders().put(ContentTypeHeader.valueOf(MediaType.XML_UTF_8.toString()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Transformer transformer = XMLUtils.getTransformerFactory().newTransformer();
transformer.transform(new DOMSource(asXMLDOM(jre.includeCauseInJsonValue().toJsonValue().asMap())), new StreamResult(outputStream));
response.getEntity().setBytes(outputStream.toByteArray());
} catch (TransformerException e1) {
throw new IllegalStateException("Could not write XML to response", e1);
}
}
use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.
the class ClientResource method createInstance.
public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest createRequest) {
String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
Map<String, String> responseVal = new HashMap<String, String>();
try {
if (serviceSchema == null || serviceSchemaManager == null) {
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": No serviceSchema available.");
}
throw new PermanentException(ResourceException.INTERNAL_ERROR, "", null);
}
Map<String, ArrayList<String>> client = (Map<String, ArrayList<String>>) createRequest.getContent().getObject();
String realm = null;
if (client == null || client.isEmpty()) {
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": No client definition.");
}
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client definition", null);
}
//check for id
String id = createRequest.getNewResourceId();
if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_ID)) {
ArrayList<String> idList = client.remove(OAuth2Constants.OAuth2Client.CLIENT_ID);
if (idList != null && !idList.isEmpty()) {
id = idList.iterator().next();
}
}
if (id == null || id.isEmpty()) {
debug.error("ClientResource :: CREATE by " + principal + ": No client ID.");
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client id", null);
}
//get realm
if (client.containsKey(OAuth2Constants.OAuth2Client.REALM)) {
ArrayList<String> realmList = client.remove(OAuth2Constants.OAuth2Client.REALM);
if (realmList != null && !realmList.isEmpty()) {
realm = realmList.iterator().next();
}
}
//check for required parameters
if (!client.containsKey(OAuth2Constants.OAuth2Client.USERPASSWORD) || client.get(OAuth2Constants.OAuth2Client.USERPASSWORD).iterator().next().isEmpty()) {
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No user password.");
}
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing user password", null);
}
if (client.containsKey(OAuth2Constants.OAuth2Client.CLIENT_TYPE)) {
String type = client.get(OAuth2Constants.OAuth2Client.CLIENT_TYPE).iterator().next();
if (!(type.equals("Confidential") || type.equals("Public"))) {
debug.error("ClientResource :: CREATE by " + principal + ": " + "Resource ID: " + id + ": No client type.");
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
}
} else {
debug.error("ClientResource :: CREATE by" + principal + ": " + "Resource ID: " + id + ": No client type.");
throw new PermanentException(ResourceException.BAD_REQUEST, "Missing client type", null);
}
Map<String, Set<String>> attrs = new HashMap<String, Set<String>>();
for (Map.Entry mapEntry : client.entrySet()) {
List<String> list = (ArrayList) mapEntry.getValue();
Set<String> set = new HashSet<String>();
if (isSingle((String) mapEntry.getKey())) {
set.add((String) ((ArrayList) mapEntry.getValue()).get(0));
} else {
for (int i = 0; i < list.size(); i++) {
set.add("[" + i + "]=" + list.get(i));
}
}
attrs.put((String) mapEntry.getKey(), set);
}
Set<String> temp = new HashSet<String>();
temp.add("OAuth2Client");
attrs.put("AgentType", temp);
temp = new HashSet<String>();
temp.add("Active");
attrs.put("sunIdentityServerDeviceStatus", temp);
manager.createIdentity(realm, id, attrs);
responseVal.put("success", "true");
JsonValue response = new JsonValue(responseVal);
ResourceResponse resource = newResourceResponse("results", String.valueOf(System.currentTimeMillis()), response);
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "CREATED_CLIENT", responseVal.toString() };
auditLogger.logAccessMessage("CREATED_CLIENT", obs, null);
}
return newResultPromise(resource);
} catch (IdRepoException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "IdRepo exception.", e);
}
return new InternalServerErrorException("Unable to create client", e).asPromise();
} catch (SSOException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to " + "SSO exception.", e);
}
return new InternalServerErrorException("Unable to create client", e).asPromise();
} catch (PermanentException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
if (debug.errorEnabled()) {
debug.error("ClientResource :: CREATE by " + principal + ": Unable to create client due to exception.", e);
}
return e.asPromise();
} catch (org.forgerock.json.resource.BadRequestException e) {
responseVal.put("success", "false");
if (auditLogger.isAuditLogEnabled()) {
String[] obs = { "FAILED_CREATE_CLIENT", responseVal.toString() };
auditLogger.logErrorMessage("FAILED_CREATE_CLIENT", obs, null);
}
debug.error("ClientResource :: CREATE : Unable to create client due to Bad Request.", e);
return e.asPromise();
}
}
Aggregations