Search in sources :

Example 21 with BadRequestException

use of org.forgerock.json.resource.BadRequestException in project OpenAM by OpenRock.

the class SmsServerPropertiesResource method readInstance.

@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context serverContext, ReadRequest readRequest) {
    Map<String, String> uriVariables = getUriTemplateVariables(serverContext);
    final String tabName = getTabName(uriVariables);
    if (tabName == null) {
        return new BadRequestException("Tab name not specified.").asPromise();
    }
    final String serverName = getServerName(uriVariables);
    if (serverName == null) {
        return new BadRequestException("Server name not specified.").asPromise();
    }
    try {
        ServiceConfigManager scm = getServiceConfigManager(serverContext);
        ServiceConfig serverConfigs = getServerConfigs(scm);
        Properties defaultAttributes = getAttributes(serverConfigs.getSubConfig(SERVER_DEFAULT_NAME));
        final ServiceConfig serverConfig = serverConfigs.getSubConfig(serverName);
        if (serverConfig == null) {
            return new BadRequestException("Unknown Server " + serverName).asPromise();
        }
        Properties serverSpecificAttributes = getAttributes(serverConfig);
        Map<String, String> defaultSection = new HashMap<>();
        JsonValue result = json(object(field("default", defaultSection)));
        List<String> attributeNamesForTab;
        if (tabName.equalsIgnoreCase(DIRECTORY_CONFIGURATION_TAB_NAME)) {
            InputStream resourceStream = new StringInputStream(getServerConfigXml(serverConfig));
            Document serverXml = dBuilder.parse(resourceStream);
            XPath xPath = XPathFactory.newInstance().newXPath();
            final String baseExpression = "//iPlanetDataAccessLayer/ServerGroup[@name='sms']/";
            String minConnections = (String) xPath.compile(baseExpression + "@" + DSConfigMgr.MIN_CONN_POOL).evaluate(serverXml, XPathConstants.STRING);
            String maxConnections = (String) xPath.compile(baseExpression + "@" + DSConfigMgr.MAX_CONN_POOL).evaluate(serverXml, XPathConstants.STRING);
            String dirDN = (String) xPath.compile(baseExpression + "User/DirDN").evaluate(serverXml, XPathConstants.STRING);
            String directoryPassword = (String) xPath.compile(baseExpression + "User/DirPassword").evaluate(serverXml, XPathConstants.STRING);
            result.put("minConnections", minConnections);
            result.put("maxConnections", maxConnections);
            result.put("dirDN", dirDN);
            result.put("directoryPassword", directoryPassword);
            NodeList serverNames = (NodeList) xPath.compile(baseExpression + "Server/@name").evaluate(serverXml, XPathConstants.NODESET);
            for (int i = 0; i < serverNames.getLength(); i++) {
                final String directoryServerName = serverNames.item(i).getNodeValue();
                final String serverExpression = baseExpression + "Server[@name='" + directoryServerName + "']";
                String hostExpression = serverExpression + "/@host";
                String portExpression = serverExpression + "/@port";
                String typeExpression = serverExpression + "/@type";
                NodeList serverAttributes = (NodeList) xPath.compile(hostExpression + "|" + portExpression + "|" + typeExpression).evaluate(serverXml, XPathConstants.NODESET);
                for (int a = 0; a < serverAttributes.getLength(); a++) {
                    final Node serverAttribute = serverAttributes.item(a);
                    result.addPermissive(new JsonPointer("servers/" + directoryServerName + "/" + serverAttribute.getNodeName()), serverAttribute.getNodeValue());
                }
            }
        } else {
            if (tabName.equalsIgnoreCase(ADVANCED_TAB_NAME)) {
                attributeNamesForTab = getAdvancedTabAttributeNames(serverConfig);
            } else {
                attributeNamesForTab = getDefaultValueNames(tabName);
            }
            for (String attributeName : attributeNamesForTab) {
                final String defaultAttribute = (String) defaultAttributes.get(attributeName);
                if (defaultAttribute != null) {
                    defaultSection.put(attributeName, (String) defaultAttributes.get(attributeName));
                }
                final String serverSpecificAttribute = (String) serverSpecificAttributes.get(attributeName);
                if (serverSpecificAttribute != null) {
                    result.add(attributeName, serverSpecificAttribute);
                }
            }
        }
        return newResultPromise(newResourceResponse(serverName + "/properties/" + tabName, String.valueOf(result.hashCode()), result));
    } catch (SMSException | SSOException | ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
        logger.error("Error reading property sheet for tab " + tabName, e);
    }
    return new BadRequestException("Error reading properties file for " + tabName).asPromise();
}
Also used : XPath(javax.xml.xpath.XPath) HashMap(java.util.HashMap) SMSException(com.sun.identity.sm.SMSException) StringInputStream(com.sun.xml.bind.StringInputStream) InputStream(java.io.InputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) JsonValue(org.forgerock.json.JsonValue) SSOException(com.iplanet.sso.SSOException) JsonPointer(org.forgerock.json.JsonPointer) IOException(java.io.IOException) Properties(java.util.Properties) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) StringInputStream(com.sun.xml.bind.StringInputStream) ServiceConfig(com.sun.identity.sm.ServiceConfig) BadRequestException(org.forgerock.json.resource.BadRequestException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager)

Example 22 with BadRequestException

use of org.forgerock.json.resource.BadRequestException 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();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) ResourceResponse(org.forgerock.json.resource.ResourceResponse) SMSException(com.sun.identity.sm.SMSException) ConflictException(org.forgerock.json.resource.ConflictException) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) PermanentException(org.forgerock.json.resource.PermanentException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) SessionException(com.iplanet.dpro.session.SessionException)

Example 23 with BadRequestException

use of org.forgerock.json.resource.BadRequestException 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();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) SMSException(com.sun.identity.sm.SMSException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) SessionException(com.iplanet.dpro.session.SessionException)

Example 24 with BadRequestException

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();
}
Also used : BadRequestException(org.forgerock.json.resource.BadRequestException) AcceptApiVersionHeader(org.forgerock.http.header.AcceptApiVersionHeader)

Example 25 with BadRequestException

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();
    }
}
Also used : RestSTSInstanceConfig(org.forgerock.openam.sts.rest.config.user.RestSTSInstanceConfig) Injector(com.google.inject.Injector) STSPublishException(org.forgerock.openam.sts.STSPublishException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) RestSTS(org.forgerock.openam.sts.rest.RestSTS)

Aggregations

BadRequestException (org.forgerock.json.resource.BadRequestException)82 JsonValue (org.forgerock.json.JsonValue)44 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)40 ResourceException (org.forgerock.json.resource.ResourceException)39 SSOException (com.iplanet.sso.SSOException)37 NotFoundException (org.forgerock.json.resource.NotFoundException)37 SMSException (com.sun.identity.sm.SMSException)31 ForbiddenException (org.forgerock.json.resource.ForbiddenException)26 ResourceResponse (org.forgerock.json.resource.ResourceResponse)25 IdRepoException (com.sun.identity.idm.IdRepoException)23 PermanentException (org.forgerock.json.resource.PermanentException)22 ConflictException (org.forgerock.json.resource.ConflictException)21 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)20 SSOToken (com.iplanet.sso.SSOToken)19 NotSupportedException (org.forgerock.json.resource.NotSupportedException)17 RealmContext (org.forgerock.openam.rest.RealmContext)17 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)16 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)16 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)14 MessagingException (javax.mail.MessagingException)13