Search in sources :

Example 51 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class SmsCollectionProvider method readInstance.

/**
     * Reads a child instance of config. The parent config referenced by the request path is found, and
     * the config is read using the resourceId.
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request) {
    try {
        ServiceConfigManager scm = getServiceConfigManager(context);
        ServiceConfig config = parentSubConfigFor(context, scm);
        ServiceConfig item = checkedInstanceSubConfig(context, resourceId, config);
        JsonValue result = getJsonValue(realmFor(context), item);
        return newResultPromise(newResourceResponse(resourceId, String.valueOf(result.hashCode()), result));
    } catch (SMSException e) {
        debug.warning("::SmsCollectionProvider:: SMSException on read", e);
        return new InternalServerErrorException("Unable to read SMS config: " + e.getMessage()).asPromise();
    } catch (SSOException e) {
        debug.warning("::SmsCollectionProvider:: SSOException on read", e);
        return new InternalServerErrorException("Unable to read SMS config: " + e.getMessage()).asPromise();
    } catch (NotFoundException e) {
        return e.asPromise();
    }
}
Also used : ServiceConfig(com.sun.identity.sm.ServiceConfig) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager)

Example 52 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class SmsJsonConverter method toJson.

/**
     * Will validate the Map representation of the service configuration against the serviceSchema and return a
     * corresponding JSON representation
     *
     * @param attributeValuePairs The schema attribute values.
     * @param realm The realm, or null if global.
     * @return Json representation of attributeValuePairs
     */
public JsonValue toJson(String realm, Map<String, Set<String>> attributeValuePairs) {
    if (!initialised) {
        init();
    }
    final boolean validAttributes;
    try {
        if (realm == null) {
            validAttributes = schema.validateAttributes(attributeValuePairs);
        } else {
            validAttributes = schema.validateAttributes(attributeValuePairs, realm);
        }
    } catch (SMSException e) {
        debug.error("schema validation threw an exception while validating the attributes: realm=" + realm + " attributes: " + attributeValuePairs, e);
        throw new JsonException("Unable to validate attributes", e);
    }
    JsonValue parentJson = json(new HashMap<String, Object>());
    if (validAttributes) {
        for (String attributeName : attributeValuePairs.keySet()) {
            String jsonResourceName = attributeNameToResourceName.get(attributeName);
            String name;
            if (jsonResourceName != null) {
                name = jsonResourceName;
            } else {
                name = attributeName;
            }
            AttributeSchema attributeSchema = schema.getAttributeSchema(attributeName);
            if (shouldBeIgnored(attributeName)) {
                continue;
            }
            AttributeSchema.Type type = attributeSchema.getType();
            final Set<String> object = attributeValuePairs.get(attributeName);
            Object jsonAttributeValue = null;
            if (type == null) {
                throw new JsonException("Type not defined.");
            }
            AttributeSchemaConverter attributeSchemaConverter = attributeSchemaConverters.get(name);
            if (isASingleValue(type)) {
                if (!object.isEmpty()) {
                    jsonAttributeValue = attributeSchemaConverter.toJson(object.iterator().next());
                }
            } else if (containsMultipleValues(type)) {
                if (isAMap(attributeSchema.getUIType())) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    Iterator<String> itr = object.iterator();
                    while (itr.hasNext()) {
                        Pair<String, String> entry = nameValueParser.parse(itr.next());
                        map.put(entry.getFirst(), attributeSchemaConverter.toJson(entry.getSecond()));
                    }
                    jsonAttributeValue = map;
                } else {
                    List<Object> list = new ArrayList<Object>();
                    Iterator<String> itr = object.iterator();
                    while (itr.hasNext()) {
                        list.add(attributeSchemaConverter.toJson(itr.next()));
                    }
                    jsonAttributeValue = list;
                }
            }
            String sectionName = attributeNameToSection.get(attributeName);
            if (sectionName != null) {
                parentJson.putPermissive(new JsonPointer("/" + sectionName + "/" + name), jsonAttributeValue);
            } else {
                parentJson.put(name, jsonAttributeValue);
            }
        }
    } else {
        throw new JsonException("Invalid attributes");
    }
    return parentJson;
}
Also used : JsonException(org.forgerock.json.JsonException) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) JsonPointer(org.forgerock.json.JsonPointer) AttributeSchema(com.sun.identity.sm.AttributeSchema) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HashBiMap(org.forgerock.guava.common.collect.HashBiMap) BiMap(org.forgerock.guava.common.collect.BiMap) Pair(org.forgerock.util.Pair)

Example 53 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class SmsServerPropertiesResource method getSchema.

private JsonValue getSchema(Properties syntaxProperties, Properties titleProperties, boolean isDefault) {
    JsonValue template = json(object());
    for (String tabName : getTabNames()) {
        try {
            Document propertySheet = getPropertySheet(tabName);
            Map<String, Set<String>> options = getOptions(propertySheet, tabName);
            List<String> sectionNames = getSectionNames(propertySheet);
            Set<String> optionalAttributes = getOptionalAttributes(propertySheet, tabName);
            int sectionOrder = 0;
            for (String sectionName : sectionNames) {
                final String sectionPath = "/properties/" + tabName + "/" + sectionName;
                template.putPermissive(new JsonPointer(sectionPath + "/title"), titleProperties.getProperty(sectionName));
                template.putPermissive(new JsonPointer(sectionPath + "/propertyOrder"), sectionOrder++);
                int attributeOrder = 0;
                for (String attributeName : getAttributeNamesForSection(sectionName, propertySheet)) {
                    final String title = titleProperties.getProperty(attributeName);
                    String property = syntaxProperties.getProperty(attributeName);
                    if (property == null) {
                        property = "";
                    }
                    final String type = syntaxRawToReal.get(property);
                    final Set<String> attributeOptions = getAttributeOptions(options, attributeName, type);
                    final boolean isOptional;
                    if (isDefault) {
                        isOptional = optionalAttributes.contains(attributeName);
                    } else {
                        isOptional = true;
                    }
                    final String path = sectionPath + "/" + attributeName;
                    if (attributeOptions != null && !attributeOptions.isEmpty()) {
                        template.putPermissive(new JsonPointer(path + "/type/enum"), attributeOptions);
                    } else {
                        template.putPermissive(new JsonPointer(path + "/type"), type);
                    }
                    template.putPermissive(new JsonPointer(path + "/title"), title);
                    template.putPermissive(new JsonPointer(path + "/propertyOrder"), attributeOrder++);
                    template.putPermissive(new JsonPointer(path + "/required"), !isOptional);
                    template.putPermissive(new JsonPointer(path + "/pattern"), ".+");
                    allAttributeNamesInNamedTabs.add(attributeName);
                }
            }
        } catch (ParserConfigurationException | IOException | XPathExpressionException | SAXException e) {
            logger.error("Error reading property sheet for tab " + tabName, e);
        }
    }
    return template;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) XPathExpressionException(javax.xml.xpath.XPathExpressionException) JsonValue(org.forgerock.json.JsonValue) JsonPointer(org.forgerock.json.JsonPointer) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 54 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class SmsServerPropertiesResource method getDirectorySchema.

private JsonValue getDirectorySchema(Properties titleProperties, Debug logger) {
    try {
        JsonValue directoryConfigSchema = json(object());
        dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        dBuilder = dbFactory.newDocumentBuilder();
        Document document = dBuilder.parse(getClass().getResourceAsStream(DIRECTORY_CONFIG_XML));
        XPath xPath = XPathFactory.newInstance().newXPath();
        final String sectionExpression = "//propertysheet/section/@defaultValue";
        String sectionRawValue = (String) xPath.compile(sectionExpression).evaluate(document, XPathConstants.STRING);
        String sectionTitle = titleProperties.getProperty(sectionRawValue);
        final String baseExpression = "//propertysheet/section/property/label/@defaultValue";
        NodeList attributes = (NodeList) xPath.compile(baseExpression).evaluate(document, XPathConstants.NODESET);
        final String path = "/_schema/properties/directoryConfiguration/" + sectionRawValue;
        directoryConfigSchema.putPermissive(new JsonPointer(path + "/title"), sectionTitle);
        for (int i = 0; i < attributes.getLength(); i++) {
            String attributeRawName = attributes.item(i).getNodeValue();
            String attributePath = path + "/" + attributeRawName;
            directoryConfigSchema.putPermissive(new JsonPointer(attributePath + "/title"), titleProperties.getProperty(attributeRawName));
            directoryConfigSchema.putPermissive(new JsonPointer(attributePath + "/propertyOrder"), i);
            directoryConfigSchema.putPermissive(new JsonPointer(attributePath + "/type"), "string");
        }
        final String serverPath = path + "/servers";
        directoryConfigSchema.putPermissive(new JsonPointer(serverPath + "/title"), titleProperties.get("amconfig.serverconfig.xml.server.table.header"));
        directoryConfigSchema.putPermissive(new JsonPointer(serverPath + "/type"), "array");
        directoryConfigSchema.putPermissive(new JsonPointer(serverPath + "/items/type"), "object");
        List<String> columnNames = new ArrayList<>();
        columnNames.add("name");
        columnNames.add("host");
        columnNames.add("port");
        columnNames.add("type");
        for (String columnName : columnNames) {
            final String attributePath = serverPath + "/items/properties/" + SERVER_TABLE_PROPERTY_PREFIX + columnName;
            directoryConfigSchema.putPermissive(new JsonPointer(attributePath + "/title"), titleProperties.getProperty(SERVER_TABLE_PROPERTY_PREFIX + columnName));
            directoryConfigSchema.putPermissive(new JsonPointer(attributePath + "/type"), "string");
            directoryConfigSchema.putPermissive(new JsonPointer(attributePath + "/propertyOrder"), columnNames.indexOf(columnName));
        }
        return directoryConfigSchema;
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
        logger.error("Error creating document builder", e);
    }
    return null;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) JsonPointer(org.forgerock.json.JsonPointer) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 55 with JsonValue

use of org.forgerock.json.JsonValue 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)

Aggregations

JsonValue (org.forgerock.json.JsonValue)575 Test (org.testng.annotations.Test)333 ResourceException (org.forgerock.json.resource.ResourceException)144 ResourceResponse (org.forgerock.json.resource.ResourceResponse)123 RealmContext (org.forgerock.openam.rest.RealmContext)70 Context (org.forgerock.services.context.Context)63 HashSet (java.util.HashSet)56 SSOException (com.iplanet.sso.SSOException)54 ArrayList (java.util.ArrayList)51 BadRequestException (org.forgerock.json.resource.BadRequestException)47 Privilege (com.sun.identity.entitlement.Privilege)46 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)46 SSOToken (com.iplanet.sso.SSOToken)43 SMSException (com.sun.identity.sm.SMSException)42 HashMap (java.util.HashMap)42 NotFoundException (org.forgerock.json.resource.NotFoundException)41 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)41 CreateRequest (org.forgerock.json.resource.CreateRequest)40 OpenSSOPrivilege (com.sun.identity.entitlement.opensso.OpenSSOPrivilege)39 Subject (javax.security.auth.Subject)32