Search in sources :

Example 21 with ResourceException

use of org.restlet.resource.ResourceException in project OpenAM by OpenRock.

the class ResourceSetRegistrationEndpoint method deleteResourceSet.

/**
     * <p>Deletes the resource set description for the request resource set id as long as the If-Match header matches
     * the current version of the resource set.</p>
     *
     * <p>If no If-Match header is present on the request a 512 Precondition Failed response will be returned.</p>
     *
     * @return An empty representation.
     * @throws NotFoundException If the requested resource set description does not exist.
     * @throws ServerException When an error occurs during removal.
     */
@Delete
public Representation deleteResourceSet() throws NotFoundException, ServerException {
    if (!isConditionalRequest()) {
        throw new ResourceException(512, "precondition_failed", "Require If-Match header to delete Resource Set", null);
    }
    ResourceSetStore store = providerSettingsFactory.get(requestFactory.create(getRequest())).getResourceSetStore();
    ResourceSetDescription resourceSetDescription = store.read(getResourceSetId(), getResourceOwnerId());
    OAuth2Request oAuth2Request = requestFactory.create(getRequest());
    for (ResourceSetRegistrationHook hook : hooks) {
        hook.resourceSetDeleted(oAuth2Request.<String>getParameter("realm"), resourceSetDescription);
    }
    labelRegistration.updateLabelsForDeletedResourceSet(resourceSetDescription);
    store.delete(getResourceSetId(), getResourceOwnerId());
    return createEmptyResponse();
}
Also used : OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) ResourceSetStore(org.forgerock.oauth2.resources.ResourceSetStore) ResourceSetRegistrationHook(org.forgerock.oauth2.restlet.resources.ResourceSetRegistrationHook) ResourceException(org.restlet.resource.ResourceException) ResourceSetDescription(org.forgerock.oauth2.resources.ResourceSetDescription) Delete(org.restlet.resource.Delete)

Example 22 with ResourceException

use of org.restlet.resource.ResourceException in project OpenAM by OpenRock.

the class XacmlService method exportXACML.

/**
     * This version of exportXACML here for testing - it saves trying to mock the static getRealmFromRequest
     * @param realm The realm
     * @return Representation object wrapping the converted XACML
     */
@VisibleForTesting
Representation exportXACML(String realm) {
    List<String> filters = new ArrayList<String>(Arrays.asList(getQuery().getValuesArray(QUERY_PARAM_STRING)));
    PolicySet policySet;
    try {
        if (!checkPermission("READ")) {
            throw new ResourceException(new Status(FORBIDDEN));
        }
        policySet = importExport.exportXACML(realm, getAdminToken(), filters);
        getResponse().setStatus(Status.SUCCESS_OK);
    } catch (EntitlementException e) {
        debug.warning("Reading Policies failed", e);
        throw new ResourceException(new Status(INTERNAL_ERROR, e.getLocalizedMessage(getRequestLocale()), null, null));
    }
    final PolicySet finalPolicySet = policySet;
    Representation result = new OutputRepresentation(XACMLServiceEndpointApplication.APPLICATION_XML_XACML3) {

        @Override
        public void write(OutputStream outputStream) throws IOException {
            try {
                XACMLPrivilegeUtils.writeXMLToStream(finalPolicySet, outputStream);
            } catch (EntitlementException e) {
                throw new IOException(e);
            }
        }
    };
    // OPENAM-4974
    Disposition disposition = new Disposition();
    disposition.setType(Disposition.TYPE_ATTACHMENT);
    disposition.setFilename(getPolicyAttachmentFileName(realm));
    result.setDisposition(disposition);
    return result;
}
Also used : Status(org.restlet.data.Status) EntitlementException(com.sun.identity.entitlement.EntitlementException) OutputRepresentation(org.restlet.representation.OutputRepresentation) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) Disposition(org.restlet.data.Disposition) ResourceException(org.restlet.resource.ResourceException) ResourceException(org.forgerock.json.resource.ResourceException) JacksonRepresentation(org.restlet.ext.jackson.JacksonRepresentation) OutputRepresentation(org.restlet.representation.OutputRepresentation) Representation(org.restlet.representation.Representation) IOException(java.io.IOException) PolicySet(com.sun.identity.entitlement.xacml3.core.PolicySet) VisibleForTesting(org.forgerock.util.annotations.VisibleForTesting)

Example 23 with ResourceException

use of org.restlet.resource.ResourceException in project OpenAM by OpenRock.

the class XacmlServiceTest method testImportXACMLImportFailure.

@Test
public void testImportXACMLImportFailure() throws Exception {
    //given
    Representation representation = mock(Representation.class);
    InputStream is = new ByteArrayInputStream("Hello World".getBytes());
    doReturn(is).when(representation).getStream();
    EntitlementException failure = new EntitlementException(EntitlementException.JSON_PARSE_ERROR);
    doThrow(failure).when(importExport).importXacml(eq("/"), eq(is), any(Subject.class), eq(false));
    try {
        //when
        service.importXACML(representation);
        //then
        fail("Expect exception");
    } catch (ResourceException e) {
        assertThat(e.getStatus().getCode()).isEqualTo(BAD_REQUEST);
        assertThat(e.getMessage()).isEqualTo("JSON Exception.");
    }
}
Also used : EntitlementException(com.sun.identity.entitlement.EntitlementException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JacksonRepresentation(org.restlet.ext.jackson.JacksonRepresentation) Representation(org.restlet.representation.Representation) ResourceException(org.restlet.resource.ResourceException) Subject(javax.security.auth.Subject) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 24 with ResourceException

use of org.restlet.resource.ResourceException in project OpenAM by OpenRock.

the class OAuth2Representation method getRepresentation.

/**
     * Gets the appropriate representation to send to the user agent based from the specified parameters.
     *
     * @param context The Restlet context.
     * @param templateName The name of the template to display.
     * @param dataModel The data model to display on the page.
     * @return A representation of the page to send to the user agent.
     */
Representation getRepresentation(Context context, OAuth2Request request, String templateName, Map<String, Object> dataModel) {
    final String display = request.getParameter("display");
    OAuth2Constants.DisplayType displayType = OAuth2Constants.DisplayType.PAGE;
    if (!isEmpty(display)) {
        displayType = Enum.valueOf(OAuth2Constants.DisplayType.class, display.toUpperCase());
    }
    final Representation representation;
    if (display != null && display.equalsIgnoreCase("popup")) {
        Representation popup = getRepresentation(context, displayType.getFolder(), "authorize.ftl", dataModel);
        try {
            dataModel.put("htmlCode", popup.getText());
        } catch (IOException e) {
            logger.error("Server can not serve the content of authorization page");
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Server can not serve the content of authorization page");
        }
        representation = getRepresentation(context, displayType.getFolder(), "popup.ftl", dataModel);
    } else {
        representation = getRepresentation(context, displayType.getFolder(), templateName, dataModel);
    }
    if (representation != null) {
        return representation;
    }
    logger.error("Server can not serve the content of authorization page");
    throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Server can not serve the content of authorization page");
}
Also used : OAuth2Constants(org.forgerock.oauth2.core.OAuth2Constants) TemplateRepresentation(org.restlet.ext.freemarker.TemplateRepresentation) Representation(org.restlet.representation.Representation) ResourceException(org.restlet.resource.ResourceException) IOException(java.io.IOException)

Example 25 with ResourceException

use of org.restlet.resource.ResourceException in project OpenAM by OpenRock.

the class OpenAMResourceOwnerAuthenticator method authenticate.

private ResourceOwner authenticate(String username, char[] password, String realm, String service) {
    ResourceOwner ret = null;
    AuthContext lc = null;
    try {
        lc = new AuthContext(realm);
        if (service != null) {
            lc.login(AuthContext.IndexType.SERVICE, service, null, ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
        } else {
            lc.login(ServletUtils.getRequest(Request.getCurrent()), ServletUtils.getResponse(Response.getCurrent()));
        }
        while (lc.hasMoreRequirements()) {
            Callback[] callbacks = lc.getRequirements();
            ArrayList missing = new ArrayList();
            // loop through the requires setting the needs..
            for (int i = 0; i < callbacks.length; i++) {
                if (callbacks[i] instanceof NameCallback) {
                    NameCallback nc = (NameCallback) callbacks[i];
                    nc.setName(username);
                } else if (callbacks[i] instanceof PasswordCallback) {
                    PasswordCallback pc = (PasswordCallback) callbacks[i];
                    pc.setPassword(password);
                } else {
                    missing.add(callbacks[i]);
                }
            }
            // there's missing requirements not filled by this
            if (missing.size() > 0) {
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Missing requirements");
            }
            lc.submitRequirements(callbacks);
        }
        // validate the password..
        if (lc.getStatus() == AuthContext.Status.SUCCESS) {
            try {
                // package up the token for transport..
                ret = createResourceOwner(lc);
            } catch (Exception e) {
                logger.error("Unable to get SSOToken", e);
                // because the system is likely down..
                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
            }
        }
    } catch (AuthLoginException le) {
        logger.error("AuthException", le);
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, le);
    } finally {
        if (lc != null && AuthContext.Status.SUCCESS.equals(lc.getStatus())) {
            try {
                lc.logout();
                logger.message("Logged user out.");
            } catch (AuthLoginException e) {
                logger.error("Exception caught logging out of AuthContext after successful login", e);
            }
        }
    }
    return ret;
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) ResourceOwner(org.forgerock.oauth2.core.ResourceOwner) ArrayList(java.util.ArrayList) AuthContext(com.sun.identity.authentication.AuthContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) ResourceException(org.restlet.resource.ResourceException) IdRepoException(com.sun.identity.idm.IdRepoException) ResourceException(org.restlet.resource.ResourceException) ParseException(java.text.ParseException) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Aggregations

ResourceException (org.restlet.resource.ResourceException)60 Representation (org.restlet.representation.Representation)19 VCellApiApplication (org.vcell.rest.VCellApiApplication)16 PermissionException (org.vcell.util.PermissionException)16 IOException (java.io.IOException)13 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)11 ArrayList (java.util.ArrayList)10 StringRepresentation (org.restlet.representation.StringRepresentation)9 Reference (org.restlet.data.Reference)8 Writer (java.io.Writer)7 WriterRepresentation (org.restlet.representation.WriterRepresentation)7 JSONObject (org.json.JSONObject)6 Response (org.restlet.Response)6 User (org.vcell.util.document.User)6 HashMap (java.util.HashMap)5 JsonRepresentation (org.restlet.ext.json.JsonRepresentation)5 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)5 JSONException (org.json.JSONException)4 EntityReference (org.qi4j.api.entity.EntityReference)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4