Example usage for org.dom4j Attribute getValue

List of usage examples for org.dom4j Attribute getValue

Introduction

In this page you can find the example usage for org.dom4j Attribute getValue.

Prototype

String getValue();

Source Link

Document

Returns the value of the attribute.

Usage

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileImporter.java

License:Apache License

/**
 * Gets the name of the schema./*  w  w  w. ja v  a 2s  .  c om*/
 *
 * @param element
 *      the element
 * @param path
 *      the path
 * @return
 *      the name of the schema
 * @throws XMLSchemaFileImportException
 *      if an error occurs when reading the file
 */
private static String getSchemaName(Element element, String path) throws XMLSchemaFileImportException {
    if (!element.getName().equals(SCHEMA_TAG)) {
        throw new XMLSchemaFileImportException(
                NLS.bind(Messages.getString("XMLSchemaFileImporter.NotValidSchema"), new String[] { path })); //$NON-NLS-1$
    }

    Attribute nameAttribute = element.attribute(NAME_TAG);
    if ((nameAttribute != null) && (!nameAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        return nameAttribute.getValue();
    } else {
        return getNameFromPath(path);
    }
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileImporter.java

License:Apache License

/**
 * Reads an attribute type.//from w w  w  .j  a  v a2  s.  c  o m
 *
 * @param element
 *      the element
 * @param schema
 *      the schema
 */
private static void readAttributeType(Element element, Schema schema) throws XMLSchemaFileImportException {
    MutableAttributeType at = null;

    // OID
    Attribute oidAttribute = element.attribute(OID_TAG);
    if ((oidAttribute != null) && (!oidAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        at = new MutableAttributeType(oidAttribute.getValue());
    } else {
        throw new XMLSchemaFileImportException(Messages.getString("XMLSchemaFileImporter.NoOIDInAttribute")); //$NON-NLS-1$
    }

    // Schema
    at.setSchemaName(schema.getSchemaName());

    // Aliases
    Element aliasesElement = element.element(ALIASES_TAG);
    if (aliasesElement != null) {
        List<String> aliases = new ArrayList<String>();
        for (Iterator<?> i = aliasesElement.elementIterator(ALIAS_TAG); i.hasNext();) {
            Element aliasElement = (Element) i.next();
            aliases.add(aliasElement.getText());
        }
        if (aliases.size() >= 1) {
            at.setNames(aliases.toArray(new String[0]));
        }
    }

    // Description
    Element descriptionElement = element.element(DESCRIPTION_TAG);
    if ((descriptionElement != null) && (!descriptionElement.getText().equals(""))) //$NON-NLS-1$
    {
        at.setDescription(descriptionElement.getText());
    }

    // Superior
    Element superiorElement = element.element(SUPERIOR_TAG);
    if ((superiorElement != null) && (!superiorElement.getText().equals(""))) //$NON-NLS-1$
    {
        at.setSuperiorOid(superiorElement.getText());
    }

    // Usage
    Element usageElement = element.element(USAGE_TAG);
    if ((usageElement != null) && (!usageElement.getText().equals(""))) //$NON-NLS-1$
    {
        try {
            at.setUsage(UsageEnum.valueOf(usageElement.getText()));
        } catch (IllegalArgumentException e) {
            throw new XMLSchemaFileImportException(
                    Messages.getString("XMLSchemaFileImporter.UnceonvertableAttribute"), e); //$NON-NLS-1$
        }
    }

    // Syntax
    Element syntaxElement = element.element(SYNTAX_TAG);
    if ((syntaxElement != null) && (!syntaxElement.getText().equals(""))) //$NON-NLS-1$
    {
        at.setSyntaxOid(syntaxElement.getText());
    }

    // Syntax Length
    Element syntaxLengthElement = element.element(SYNTAX_LENGTH_TAG);
    if ((syntaxLengthElement != null) && (!syntaxLengthElement.getText().equals(""))) //$NON-NLS-1$
    {
        try {
            at.setSyntaxLength(Long.parseLong(syntaxLengthElement.getText()));
        } catch (NumberFormatException e) {
            throw new XMLSchemaFileImportException(
                    Messages.getString("XMLSchemaFileImporter.UnconvertableInteger"), e); //$NON-NLS-1$
        }
    }

    // Obsolete
    Attribute obsoleteAttribute = element.attribute(OBSOLETE_TAG);
    if ((obsoleteAttribute != null) && (!obsoleteAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        at.setObsolete(readBoolean(obsoleteAttribute.getValue()));
    }

    // Single Value
    Attribute singleValueAttribute = element.attribute(SINGLE_VALUE_TAG);
    if ((singleValueAttribute != null) && (!singleValueAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        at.setSingleValued(readBoolean(singleValueAttribute.getValue()));
    }

    // Collective
    Attribute collectiveAttribute = element.attribute(COLLECTIVE_TAG);
    if ((collectiveAttribute != null) && (!collectiveAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        at.setCollective(readBoolean(collectiveAttribute.getValue()));
    }

    // No User Modification
    Attribute noUserModificationAttribute = element.attribute(NO_USER_MODIFICATION_TAG);
    if ((noUserModificationAttribute != null) && (!noUserModificationAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        at.setUserModifiable(!readBoolean(noUserModificationAttribute.getValue()));
    }

    // Equality
    Element equalityElement = element.element(EQUALITY_TAG);
    if ((equalityElement != null) && (!equalityElement.getText().equals(""))) //$NON-NLS-1$
    {
        at.setEqualityOid(equalityElement.getText());
    }

    // Ordering
    Element orderingElement = element.element(ORDERING_TAG);
    if ((orderingElement != null) && (!orderingElement.getText().equals(""))) //$NON-NLS-1$
    {
        at.setOrderingOid(orderingElement.getText());
    }

    // Substring
    Element substringElement = element.element(SUBSTRING_TAG);
    if ((substringElement != null) && (!substringElement.getText().equals(""))) //$NON-NLS-1$
    {
        at.setSubstringOid(substringElement.getText());
    }

    // Adding the attribute type to the schema
    schema.addAttributeType(at);
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileImporter.java

License:Apache License

/**
 * Reads an object class/*from  ww w.  ja  va 2  s . c  o  m*/
 *
 * @param element
 *      the element
 * @param schema
 *      the schema
 * @throws XMLSchemaFileImportException
 */
private static void readObjectClass(Element element, Schema schema) throws XMLSchemaFileImportException {
    MutableObjectClass oc = null;

    // OID
    Attribute oidAttribute = element.attribute(OID_TAG);
    if ((oidAttribute != null) && (!oidAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        oc = new MutableObjectClass(oidAttribute.getValue());
    } else {
        throw new XMLSchemaFileImportException(Messages.getString("XMLSchemaFileImporter.NoOIDInClass")); //$NON-NLS-1$
    }

    // Schema
    oc.setSchemaName(schema.getSchemaName());

    // Aliases
    Element aliasesElement = element.element(ALIASES_TAG);
    if (aliasesElement != null) {
        List<String> aliases = new ArrayList<String>();
        for (Iterator<?> i = aliasesElement.elementIterator(ALIAS_TAG); i.hasNext();) {
            Element aliasElement = (Element) i.next();
            aliases.add(aliasElement.getText());
        }
        if (aliases.size() >= 1) {
            oc.setNames(aliases.toArray(new String[0]));
        }
    }

    // Description
    Element descriptionElement = element.element(DESCRIPTION_TAG);
    if ((descriptionElement != null) && (!descriptionElement.getText().equals(""))) //$NON-NLS-1$
    {
        oc.setDescription(descriptionElement.getText());
    }

    // Superiors
    Element superiorsElement = element.element(SUPERIORS_TAG);
    if (superiorsElement != null) {
        List<String> superiors = new ArrayList<String>();
        for (Iterator<?> i = superiorsElement.elementIterator(SUPERIOR_TAG); i.hasNext();) {
            Element superiorElement = (Element) i.next();
            superiors.add(superiorElement.getText());
        }
        if (superiors.size() >= 1) {
            oc.setSuperiorOids(superiors);
        }
    }

    // Class Type
    Element classTypeElement = element.element(TYPE_TAG);
    if ((classTypeElement != null) && (!classTypeElement.getText().equals(""))) //$NON-NLS-1$
    {
        try {
            oc.setType(ObjectClassTypeEnum.valueOf(classTypeElement.getText()));
        } catch (IllegalArgumentException e) {
            throw new XMLSchemaFileImportException(
                    Messages.getString("XMLSchemaFileImporter.UnconvertableValue"), e); //$NON-NLS-1$
        }
    }

    // Obsolete
    Attribute obsoleteAttribute = element.attribute(OBSOLETE_TAG);
    if ((obsoleteAttribute != null) && (!obsoleteAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        oc.setObsolete(readBoolean(obsoleteAttribute.getValue()));
    }

    // Mandatory Attribute Types
    Element mandatoryElement = element.element(MANDATORY_TAG);
    if (mandatoryElement != null) {
        List<String> mandatoryATs = new ArrayList<String>();
        for (Iterator<?> i = mandatoryElement.elementIterator(ATTRIBUTE_TYPE_TAG); i.hasNext();) {
            Element attributeTypeElement = (Element) i.next();
            mandatoryATs.add(attributeTypeElement.getText());
        }
        if (mandatoryATs.size() >= 1) {
            oc.setMustAttributeTypeOids(mandatoryATs);
        }
    }

    // Optional Attribute Types
    Element optionalElement = element.element(OPTIONAL_TAG);
    if (optionalElement != null) {
        List<String> optionalATs = new ArrayList<String>();
        for (Iterator<?> i = optionalElement.elementIterator(ATTRIBUTE_TYPE_TAG); i.hasNext();) {
            Element attributeTypeElement = (Element) i.next();
            optionalATs.add(attributeTypeElement.getText());
        }
        if (optionalATs.size() >= 1) {
            oc.setMayAttributeTypeOids(optionalATs);
        }
    }

    // Adding the object class to the schema
    schema.addObjectClass(oc);
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileImporter.java

License:Apache License

/**
 * Reads a matching rule.//www  . j a v a2s .  c  o  m
 *
 * @param element
 *      the element
 * @param schema
 *      the schema
 * @throws XMLSchemaFileImportException
 */
private static void readMatchingRule(Element element, Schema schema) throws XMLSchemaFileImportException {
    MutableMatchingRule mr = null;

    // OID
    Attribute oidAttribute = element.attribute(OID_TAG);
    if ((oidAttribute != null) && (!oidAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        mr = new MutableMatchingRule(oidAttribute.getValue());
    } else {
        throw new XMLSchemaFileImportException(
                Messages.getString("XMLSchemaFileImporter.NoMatchingRuleForOID")); //$NON-NLS-1$
    }

    // Schema
    mr.setSchemaName(schema.getSchemaName());

    // Aliases
    Element aliasesElement = element.element(ALIASES_TAG);
    if (aliasesElement != null) {
        List<String> aliases = new ArrayList<String>();
        for (Iterator<?> i = aliasesElement.elementIterator(ALIAS_TAG); i.hasNext();) {
            Element aliasElement = (Element) i.next();
            aliases.add(aliasElement.getText());
        }
        if (aliases.size() >= 1) {
            mr.setNames(aliases.toArray(new String[0]));
        }
    }

    // Description
    Element descriptionElement = element.element(DESCRIPTION_TAG);
    if ((descriptionElement != null) && (!descriptionElement.getText().equals(""))) //$NON-NLS-1$
    {
        mr.setDescription(descriptionElement.getText());
    }

    // Obsolete
    Attribute obsoleteAttribute = element.attribute(OBSOLETE_TAG);
    if ((obsoleteAttribute != null) && (!obsoleteAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        mr.setObsolete(readBoolean(obsoleteAttribute.getValue()));
    }

    // Syntax OID
    Element syntaxOidElement = element.element(SYNTAX_OID_TAG);
    if ((syntaxOidElement != null) && (!syntaxOidElement.getText().equals(""))) //$NON-NLS-1$
    {
        mr.setSyntaxOid(syntaxOidElement.getText());
    }

    // Adding the matching rule to the schema
    schema.addMatchingRule(mr);
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileImporter.java

License:Apache License

/**
 * Reads a syntax.// w  w  w. ja  v  a 2 s  .  c om
 *
 * @param element
 *      the element
 * @param schema
 *      the schema
 * @throws XMLSchemaFileImportException
 */
private static void readSyntax(Element element, Schema schema) throws XMLSchemaFileImportException {
    LdapSyntax syntax = null;

    // OID
    Attribute oidAttribute = element.attribute(OID_TAG);
    if ((oidAttribute != null) && (!oidAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        syntax = new LdapSyntax(oidAttribute.getValue());
    } else {
        throw new XMLSchemaFileImportException(Messages.getString("XMLSchemaFileImporter.InvalidSyntaxForOID")); //$NON-NLS-1$
    }

    // Schema
    syntax.setSchemaName(schema.getSchemaName());

    // Aliases
    Element aliasesElement = element.element(ALIASES_TAG);
    if (aliasesElement != null) {
        List<String> aliases = new ArrayList<String>();
        for (Iterator<?> i = aliasesElement.elementIterator(ALIAS_TAG); i.hasNext();) {
            Element aliasElement = (Element) i.next();
            aliases.add(aliasElement.getText());
        }
        if (aliases.size() >= 1) {
            syntax.setNames(aliases.toArray(new String[0]));
        }
    }

    // Description
    Element descriptionElement = element.element(DESCRIPTION_TAG);
    if ((descriptionElement != null) && (!descriptionElement.getText().equals(""))) //$NON-NLS-1$
    {
        syntax.setDescription(descriptionElement.getText());
    }

    // Obsolete
    Attribute obsoleteAttribute = element.attribute(OBSOLETE_TAG);
    if ((obsoleteAttribute != null) && (!obsoleteAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        syntax.setObsolete(readBoolean(obsoleteAttribute.getValue()));
    }

    // Human Readible
    Attribute humanReadibleAttribute = element.attribute(HUMAN_READABLE_TAG);
    if ((humanReadibleAttribute != null) && (!humanReadibleAttribute.getValue().equals(""))) //$NON-NLS-1$
    {
        syntax.setHumanReadable(readBoolean(humanReadibleAttribute.getValue()));
    }

    // Adding the syntax to the schema
    schema.addSyntax(syntax);
}

From source file:org.apache.poi.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

/**
 * Check the element for the following OPC compliance rules:
 * <p>//from  w  w  w.ja v  a  2  s  .  c  om
 * Rule M4.2: A format consumer shall consider the use of the Markup
 * Compatibility namespace to be an error.
 * </p><p>
 * Rule M4.3: Producers shall not create a document element that contains
 * refinements to the Dublin Core elements, except for the two specified in
 * the schema: <dcterms:created> and <dcterms:modified> Consumers shall
 * consider a document element that violates this constraint to be an error.
 * </p><p>
 * Rule M4.4: Producers shall not create a document element that contains
 * the xml:lang attribute. Consumers shall consider a document element that
 * violates this constraint to be an error.
 *  </p><p>
 * Rule M4.5: Producers shall not create a document element that contains
 * the xsi:type attribute, except for a <dcterms:created> or
 * <dcterms:modified> element where the xsi:type attribute shall be present
 * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace
 * prefix of the Dublin Core namespace. Consumers shall consider a document
 * element that violates this constraint to be an error.
 * </p>
 */
public void checkElementForOPCCompliance(Element el) throws InvalidFormatException {
    // Check the current element
    @SuppressWarnings("unchecked")
    List<Namespace> declaredNamespaces = el.declaredNamespaces();
    Iterator<Namespace> itNS = declaredNamespaces.iterator();
    while (itNS.hasNext()) {
        Namespace ns = itNS.next();

        // Rule M4.2
        if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY))
            throw new InvalidFormatException(
                    "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
    }

    // Rule M4.3
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)
            && !(el.getName().equals(KEYWORD_CREATED) || el.getName().equals(KEYWORD_MODIFIED)))
        throw new InvalidFormatException(
                "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.4
    if (el.attribute(new QName("lang", namespaceXML)) != null)
        throw new InvalidFormatException(
                "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.5
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)) {
        // DCTerms namespace only use with 'created' and 'modified' elements
        String elName = el.getName();
        if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED)))
            throw new InvalidFormatException("Namespace error : " + elName
                    + " shouldn't have the following naemspace -> " + PackageProperties.NAMESPACE_DCTERMS);

        // Check for the 'xsi:type' attribute
        Attribute typeAtt = el.attribute(new QName("type", namespaceXSI));
        if (typeAtt == null)
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute present !");

        // Check for the attribute value => 'dcterms:W3CDTF'
        if (!typeAtt.getValue().equals("dcterms:W3CDTF"))
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute with the value 'dcterms:W3CDTF' !");
    }

    // Check its children
    @SuppressWarnings("unchecked")
    Iterator<Element> itChildren = el.elementIterator();
    while (itChildren.hasNext())
        checkElementForOPCCompliance(itChildren.next());
}

From source file:org.apache.poi.openxml4j.opc.PackageRelationshipCollection.java

License:Apache License

/**
 * Parse the relationship part and add all relationship in this collection.
 *
 * @param relPart/*w ww  .jav a  2 s.  c  o  m*/
 *            The package part to parse.
 * @throws InvalidFormatException
 *             Throws if the relationship part is invalid.
 */
private void parseRelationshipsPart(PackagePart relPart) throws InvalidFormatException {
    try {
        SAXReader reader = new SAXReader();
        logger.log(POILogger.DEBUG, "Parsing relationship: " + relPart.getPartName());
        Document xmlRelationshipsDoc = reader.read(relPart.getInputStream());

        // Browse default types
        Element root = xmlRelationshipsDoc.getRootElement();

        // Check OPC compliance M4.1 rule
        boolean fCorePropertiesRelationship = false;

        for (Iterator i = root.elementIterator(PackageRelationship.RELATIONSHIP_TAG_NAME); i.hasNext();) {
            Element element = (Element) i.next();
            // Relationship ID
            String id = element.attribute(PackageRelationship.ID_ATTRIBUTE_NAME).getValue();
            // Relationship type
            String type = element.attribute(PackageRelationship.TYPE_ATTRIBUTE_NAME).getValue();

            /* Check OPC Compliance */
            // Check Rule M4.1
            if (type.equals(PackageRelationshipTypes.CORE_PROPERTIES))
                if (!fCorePropertiesRelationship)
                    fCorePropertiesRelationship = true;
                else
                    throw new InvalidFormatException(
                            "OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !");

            /* End OPC Compliance */

            // TargetMode (default value "Internal")
            Attribute targetModeAttr = element.attribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME);
            TargetMode targetMode = TargetMode.INTERNAL;
            if (targetModeAttr != null) {
                targetMode = targetModeAttr.getValue().toLowerCase().equals("internal") ? TargetMode.INTERNAL
                        : TargetMode.EXTERNAL;
            }

            // Target converted in URI
            URI target;
            String value = "";
            try {
                value = element.attribute(PackageRelationship.TARGET_ATTRIBUTE_NAME).getValue();

                target = PackagingURIHelper.toURI(value);

            } catch (URISyntaxException e) {
                logger.log(POILogger.ERROR,
                        "Cannot convert " + value + " in a valid relationship URI-> ignored", e);
                continue;
            }
            addRelationship(target, targetMode, type, id);
        }
    } catch (Exception e) {
        logger.log(POILogger.ERROR, e);
        throw new InvalidFormatException(e.getMessage());
    }
}

From source file:org.apereo.portal.io.xml.SpELDataTemplatingStrategy.java

License:Apache License

@Override
public Source processTemplates(Document data, String filename) {

    log.trace("Processing templates for document XML={}", data.asXML());
    for (String xpath : XPATH_EXPRESSIONS) {
        @SuppressWarnings("unchecked")
        List<Node> nodes = data.selectNodes(xpath);
        for (Node n : nodes) {
            String inpt, otpt;/*from   w  w  w .ja  v  a 2  s.c  om*/
            switch (n.getNodeType()) {
            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                Attribute a = (Attribute) n;
                inpt = a.getValue();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    a.setValue(otpt);
                }
                break;
            case org.w3c.dom.Node.TEXT_NODE:
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
                inpt = n.getText();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    n.setText(otpt);
                }
                break;
            default:
                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                throw new RuntimeException(msg);
            }
        }
    }

    final SAXSource rslt = new DocumentSource(data);
    rslt.setSystemId(filename); // must be set, else import chokes
    return rslt;
}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

License:Apache License

private org.dom4j.Element getExportLayoutDom(IPerson person, IUserProfile profile) {
    if (!this.layoutExistsForUser(person)) {
        return null;
    }//from  w  ww.j ava 2 s  .  co  m

    org.dom4j.Document layoutDoc = null;
    try {
        final Document layoutDom = this._safeGetUserLayout(person, profile);
        person.setAttribute(Constants.PLF, layoutDom);
        layoutDoc = this.reader.get().read(layoutDom);
    } catch (final Throwable t) {
        final String msg = "Unable to obtain layout & profile for user '" + person.getUserName()
                + "', profileId " + profile.getProfileId();
        throw new RuntimeException(msg, t);
    }

    if (logger.isDebugEnabled()) {
        // Write out this version of the layout to the log for dev purposes...
        final StringWriter str = new StringWriter();
        final XMLWriter xml = new XMLWriter(str, new OutputFormat("  ", true));
        try {
            xml.write(layoutDoc);
            xml.close();
        } catch (final Throwable t) {
            throw new RuntimeException(
                    "Failed to write the layout for user '" + person.getUserName() + "' to the DEBUG log", t);
        }
        logger.debug("Layout for user: {}\n{}", person.getUserName(), str.getBuffer().toString());
    }

    /*
     * Attempt to detect a corrupted layout; return null in such cases
     */

    if (isLayoutCorrupt(layoutDoc)) {
        logger.warn("Layout for user: {} is corrupt; layout structures will not be exported.",
                person.getUserName());
        return null;
    }

    /*
     * Clean up the DOM for export.
     */

    // (1) Add structure & theme attributes...
    final int structureStylesheetId = profile.getStructureStylesheetId();
    this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, structureStylesheetId, "structure");

    final int themeStylesheetId = profile.getThemeStylesheetId();
    this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, themeStylesheetId, "theme");

    // (2) Remove locale info...
    final Iterator<org.dom4j.Attribute> locale = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@locale").iterator();
    while (locale.hasNext()) {
        final org.dom4j.Attribute loc = locale.next();
        loc.getParent().remove(loc);
    }

    // (3) Scrub unnecessary channel information...
    for (final Iterator<org.dom4j.Element> orphanedChannels = (Iterator<org.dom4j.Element>) layoutDoc
            .selectNodes("//channel[@fname = '']").iterator(); orphanedChannels.hasNext();) {
        // These elements represent UP_LAYOUT_STRUCT rows where the
        // CHAN_ID field was not recognized by ChannelRegistryStore;
        // best thing to do is remove the elements...
        final org.dom4j.Element ch = orphanedChannels.next();
        ch.getParent().remove(ch);
    }
    final List<String> channelAttributeWhitelist = Arrays.asList(new String[] { "fname", "unremovable",
            "hidden", "immutable", "ID", "dlm:plfID", "dlm:moveAllowed", "dlm:deleteAllowed" });
    final Iterator<org.dom4j.Element> channels = (Iterator<org.dom4j.Element>) layoutDoc
            .selectNodes("//channel").iterator();
    while (channels.hasNext()) {
        final org.dom4j.Element oldCh = channels.next();
        final org.dom4j.Element parent = oldCh.getParent();
        final org.dom4j.Element newCh = this.fac.createElement("channel");
        for (final String aName : channelAttributeWhitelist) {
            final org.dom4j.Attribute a = (org.dom4j.Attribute) oldCh.selectSingleNode("@" + aName);
            if (a != null) {
                newCh.addAttribute(a.getQName(), a.getValue());
            }
        }
        parent.elements().add(parent.elements().indexOf(oldCh), newCh);
        parent.remove(oldCh);
    }

    // (4) Convert internal DLM noderefs to external form (pathrefs)...
    for (final Iterator<org.dom4j.Attribute> origins = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@dlm:origin").iterator(); origins.hasNext();) {
        final org.dom4j.Attribute org = origins.next();
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), org.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            org.setValue(dlmPathref.toString());
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        org.getUniquePath(), person.getAttribute(IPerson.USERNAME), org.getValue());
            }
        }
    }
    for (final Iterator<org.dom4j.Attribute> it = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@dlm:target").iterator(); it.hasNext();) {
        final org.dom4j.Attribute target = it.next();
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), target.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            target.setValue(dlmPathref.toString());
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        target.getUniquePath(), person.getAttribute(IPerson.USERNAME), target.getValue());
            }
        }
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) {
        final org.dom4j.Attribute n = names.next();
        if (n.getValue() == null || n.getValue().trim().length() == 0) {
            // Outer <dlm:positionSet> elements don't seem to use the name
            // attribute, though their childern do.  Just skip these so we
            // don't send a false WARNING.
            continue;
        }
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), n.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            n.setValue(dlmPathref.toString());
            // These *may* have fnames...
            if (dlmPathref.getPortletFname() != null) {
                n.getParent().addAttribute("fname", dlmPathref.getPortletFname());
            }
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        n.getUniquePath(), person.getAttribute(IPerson.USERNAME), n.getValue());
            }
        }
    }

    // Remove synthetic Ids, but from non-fragment owners only...
    if (!this.isFragmentOwner(person)) {

        /*
         * In the case of fragment owners, the original database Ids allow
         * us keep (not break) the associations that subscribers have with
         * nodes on the fragment layout.
         */

        // (5) Remove dlm:plfID...
        for (final Iterator<org.dom4j.Attribute> plfid = (Iterator<org.dom4j.Attribute>) layoutDoc
                .selectNodes("//@dlm:plfID").iterator(); plfid.hasNext();) {
            final org.dom4j.Attribute plf = plfid.next();
            plf.getParent().remove(plf);
        }

        // (6) Remove database Ids...
        for (final Iterator<org.dom4j.Attribute> ids = (Iterator<org.dom4j.Attribute>) layoutDoc
                .selectNodes("//@ID").iterator(); ids.hasNext();) {
            final org.dom4j.Attribute a = ids.next();
            a.getParent().remove(a);
        }
    }

    return layoutDoc.getRootElement();
}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
@Transactional/*  w w w .java  2  s.  c  o m*/
public void importLayout(org.dom4j.Element layout) {
    if (layout.getNamespaceForPrefix("dlm") == null) {
        layout.add(new Namespace("dlm", Constants.NS_URI));
    }

    //Remove comments from the DOM they break import
    final List<org.dom4j.Node> comments = layout.selectNodes("//comment()");
    for (final org.dom4j.Node comment : comments) {
        comment.detach();
    }

    //Get a ref to the prefs element and then remove it from the layout
    final org.dom4j.Node preferencesElement = layout.selectSingleNode("preferences");
    if (preferencesElement != null) {
        preferencesElement.getParent().remove(preferencesElement);
    }

    final String ownerUsername = layout.valueOf("@username");

    //Get a ref to the profile element and then remove it from the layout
    final org.dom4j.Node profileElement = layout.selectSingleNode("profile");
    if (profileElement != null) {
        profileElement.getParent().remove(profileElement);

        final org.dom4j.Document profileDocument = new org.dom4j.DocumentFactory().createDocument();
        profileDocument.setRootElement((org.dom4j.Element) profileElement);
        profileDocument.setName(ownerUsername + ".profile");

        final DocumentSource profileSource = new DocumentSource(profileElement);
        this.portalDataHandlerService.importData(profileSource);
    }

    final IPerson person = new PersonImpl();
    person.setUserName(ownerUsername);

    int ownerId;
    try {
        //Can't just pass true for create here, if the user actually exists the create flag also updates the user data
        ownerId = this.userIdentityStore.getPortalUID(person);
    } catch (final AuthorizationException t) {
        if (this.errorOnMissingUser) {
            throw new RuntimeException("Unrecognized user " + person.getUserName()
                    + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.",
                    t);
        }

        //Create the missing user
        ownerId = this.userIdentityStore.getPortalUID(person, true);
    }

    if (ownerId == -1) {
        throw new RuntimeException("Unrecognized user " + person.getUserName()
                + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.");
    }
    person.setID(ownerId);

    IUserProfile profile = null;
    try {
        person.setSecurityContext(new BrokenSecurityContext());
        profile = this.getUserProfileByFname(person, "default");
    } catch (final Throwable t) {
        throw new RuntimeException("Failed to load profile for " + person.getUserName()
                + "; This user must have a profile for import to continue.", t);
    }

    // (6) Add database Ids & (5) Add dlm:plfID ...
    int nextId = 1;
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout
            .selectNodes("folder | dlm:* | channel").iterator(); it.hasNext();) {
        nextId = this.addIdAttributesIfNecessary(it.next(), nextId);
    }
    // Now update UP_USER...
    this.jdbcOperations.update("UPDATE up_user SET next_struct_id = ? WHERE user_id = ?", nextId,
            person.getID());

    // (4) Convert external DLM pathrefs to internal form (noderefs)...
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//@dlm:origin").iterator(); itr.hasNext();) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null,
                true, layout);
        if (dlmNoderef != null) {
            // Change the value only if we have a valid pathref...
            a.setValue(dlmNoderef.toString());
            // For dlm:origin only, also use the noderef as the ID attribute...
            a.getParent().addAttribute("ID", dlmNoderef.toString());
        } else {
            // At least insure the value is between 1 and 35 characters
            a.setValue(BAD_PATHREF_MESSAGE);
        }
    }
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//@dlm:target").iterator(); itr.hasNext();) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null,
                true, layout);
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layout
            .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) {
        final org.dom4j.Attribute a = names.next();
        final String value = a.getValue().trim();
        if (!VALID_PATHREF_PATTERN.matcher(value).matches()) {
            /* Don't send it to getDlmNoderef if we know in advance it's not
             * going to work;  saves annoying/misleading log messages and
             * possibly some processing.  NOTE this is _only_ a problem with
             * the name attribute of some dlm:* elements, which seems to go
             * unused intentionally in some circumstances
             */
            continue;
        }
        final org.dom4j.Attribute fname = a.getParent().attribute("fname");
        Noderef dlmNoderef = null;
        if (fname != null) {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, fname.getValue(),
                    false, layout);
            // Remove the fname attribute now that we're done w/ it...
            fname.getParent().remove(fname);
        } else {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, null, true, layout);
        }
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }

    // (3) Restore chanID attributes on <channel> elements...
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("//channel")
            .iterator(); it.hasNext();) {
        final org.dom4j.Element c = it.next();
        final String fname = c.valueOf("@fname");
        final IPortletDefinition cd = this.portletDefinitionRegistry.getPortletDefinitionByFname(fname);
        if (cd == null) {
            final String msg = "No portlet with fname=" + fname + " exists referenced by node "
                    + c.valueOf("@ID") + " from layout for " + ownerUsername;
            if (errorOnMissingPortlet) {
                throw new IllegalArgumentException(msg);
            } else {
                logger.warn(msg);
                //Remove the bad channel node
                c.getParent().remove(c);
            }
        } else {
            c.addAttribute("chanID", String.valueOf(cd.getPortletDefinitionId().getStringId()));
        }
    }

    // (2) Restore locale info...
    // (This step doesn't appear to be needed for imports)

    // (1) Process structure & theme attributes...
    Document layoutDom = null;
    try {

        final int structureStylesheetId = profile.getStructureStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, structureStylesheetId,
                "structure");

        final int themeStylesheetId = profile.getThemeStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, themeStylesheetId, "theme");

        // From this point forward we need the user's PLF set as DLM expects it...
        for (final Iterator<org.dom4j.Text> it = (Iterator<org.dom4j.Text>) layout
                .selectNodes("descendant::text()").iterator(); it.hasNext();) {
            // How many years have we used Java & XML, and this still isn't easy?
            final org.dom4j.Text txt = it.next();
            if (txt.getText().trim().length() == 0) {
                txt.getParent().remove(txt);
            }
        }

        final org.dom4j.Element copy = layout.createCopy();
        final org.dom4j.Document doc = this.fac.createDocument(copy);
        doc.normalize();
        layoutDom = this.writer.get().write(doc);
        person.setAttribute(Constants.PLF, layoutDom);

    } catch (final Throwable t) {
        throw new RuntimeException("Unable to set UserPreferences for user:  " + person.getUserName(), t);
    }

    // Finally store the layout...
    try {
        this.setUserLayout(person, profile, layoutDom, true, true);
    } catch (final Throwable t) {
        final String msg = "Unable to persist layout for user:  " + ownerUsername;
        throw new RuntimeException(msg, t);
    }

    if (preferencesElement != null) {
        final int ownerUserId = this.userIdentityStore.getPortalUserId(ownerUsername);
        //TODO this assumes a single layout, when multi-layout support exists portlet entities will need to be re-worked to allow for a layout id to be associated with the entity

        //track which entities from the user's pre-existing set are touched (all non-touched entities will be removed)
        final Set<IPortletEntity> oldPortletEntities = new LinkedHashSet<IPortletEntity>(
                this.portletEntityDao.getPortletEntitiesForUser(ownerUserId));

        final List<org.dom4j.Element> entries = preferencesElement.selectNodes("entry");
        for (final org.dom4j.Element entry : entries) {
            final String dlmPathRef = entry.attributeValue("entity");
            final String fname = entry.attributeValue("channel");
            final String prefName = entry.attributeValue("name");

            final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(person.getUserName(),
                    dlmPathRef, fname, false, layout);

            if (dlmNoderef != null && fname != null) {
                final IPortletEntity portletEntity = this.getPortletEntity(fname, dlmNoderef.toString(),
                        ownerUserId);
                oldPortletEntities.remove(portletEntity);

                final List<IPortletPreference> portletPreferences = portletEntity.getPortletPreferences();

                final List<org.dom4j.Element> valueElements = entry.selectNodes("value");
                final List<String> values = new ArrayList<String>(valueElements.size());
                for (final org.dom4j.Element valueElement : valueElements) {
                    values.add(valueElement.getText());
                }

                portletPreferences.add(
                        new PortletPreferenceImpl(prefName, false, values.toArray(new String[values.size()])));

                this.portletEntityDao.updatePortletEntity(portletEntity);
            }
        }

        //Delete all portlet preferences for entities that were not imported
        for (final IPortletEntity portletEntity : oldPortletEntities) {
            portletEntity.setPortletPreferences(null);

            if (portletEntityRegistry.shouldBePersisted(portletEntity)) {
                this.portletEntityDao.updatePortletEntity(portletEntity);
            } else {
                this.portletEntityDao.deletePortletEntity(portletEntity);
            }
        }
    }
}