Example usage for org.dom4j Attribute setValue

List of usage examples for org.dom4j Attribute setValue

Introduction

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

Prototype

void setValue(String value);

Source Link

Document

Sets the value of this attribute or this method will throw an UnsupportedOperationException if it is read-only.

Usage

From source file:net.unicon.academus.apps.briefcase.migrate.BriefcaseMigrator.java

License:Open Source License

public static void main(String[] args) {

    System.out.println("Starting Briefcase portlet migration of data from Academus 1.5 " + " to Academus 1.6");

    if (args.length == 2) {
        try {//from ww w . j  av  a  2 s .  c  om
            DataSource ds = new SimpleDataSource();

            SAXReader reader = new SAXReader();

            // replace the old urls with the new classpaths
            System.out.println("Updating the resource urls.");
            updateUrl(ds);
            updateSharedResourceUrls(ds);

            // replace the OWNER access type.
            System.out.println("Updating the accessTypes.");
            updateAccessType(ds);

            // set the uni_sequence table for the RdbmsAccessBroker Counter
            // and the FSA_Kernel_Sequencer
            updateSequencers(ds);

            // read the old config file
            // and correct the classpaths for all the access brokers.  
            Document oldDoc = reader.read(args[0]);

            DOMDocumentFactory dFac = new DOMDocumentFactory();

            // Get all access brokers
            List brokers = oldDoc.selectNodes("//access-broker");
            Element broker = null;

            // Change access brokers to point to alchemist instead of academus
            for (int i = 0; i < brokers.size(); i++) {
                broker = (Element) brokers.get(i);
                String implValue = broker.attributeValue("impl").replaceFirst("academus", "alchemist");
                broker.addAttribute("impl", implValue);
            }

            // Get the Access Broker under the personal Drive, and make sure it's a JIT broker
            Element targetsJitAccessBroker = (Element) ((Element) oldDoc.selectNodes(
                    "/briefcase/drive[@handle='personal']/access-broker[@impl='net.unicon.alchemist.access.jit.JitAccessBroker']")
                    .get(0)).detach();

            // Only enter this code if the personal drive section was successful selected
            if (targetsJitAccessBroker != null) {

                // Create new permissions element, mirroring targets element
                Element permissionsJitAccessBroker = (Element) targetsJitAccessBroker.clone();

                // Change handles
                targetsJitAccessBroker.addAttribute("handle", "personal-resourses-t");
                permissionsJitAccessBroker.addAttribute("handle", "personal-resourses-p");

                // Create new permissions access-broker
                Element permAccessBroker = dFac.createElement(new QName("access-broker"), 2);
                permAccessBroker.addAttribute("handle", "personal-jit");
                permAccessBroker.addAttribute("impl", PermissionsAccessBroker.class.getName());

                // Create new access element and add it to permAccessBroker
                Element permAccess = dFac.createElement(new QName("access"), 1);
                permAccess.addAttribute("impl", BriefcaseAccessType.class.getName());
                permAccessBroker.add(permAccess);

                // Create targets and permissions elements and add to the new permissions access-broker
                Element targets = permAccessBroker.addElement("targets");
                targets.add(targetsJitAccessBroker);

                Element permissions = permAccessBroker.addElement("permissions");
                permissions.add(permissionsJitAccessBroker);

                // Add new permissions access broker to the drive
                Element curDrive = (Element) oldDoc.selectNodes("/briefcase/drive[@handle='personal']").get(0);
                curDrive.add(permAccessBroker);

                //
                // Change targets internals
                //

                List targetsAccess = targets.selectNodes("access-broker/jit-rule/behavior/access");
                for (int i = 0; i < targetsAccess.size(); i++) {

                    // Add impl attribute with value of fully-qualified class name
                    ((Element) targetsAccess.get(i)).addAttribute("impl", DummyAccessType.class.getName());

                    // Get all child type elements and remove them
                    List types = ((Element) targetsAccess.get(i)).elements();
                    for (int j = 0; j < types.size(); j++) {
                        ((Element) types.get(j)).detach();
                    }

                    // Add a single dummy element
                    Element eType = dFac.createElement(new QName("type"), 2);
                    eType.addAttribute("value", "GRANT");
                    eType.addAttribute("handle", "DUMMY");

                    ((Element) targetsAccess.get(i)).add(eType);

                }

                // Add internal access broker's access element
                Element targetsIAccessBroker = (Element) (targets.selectNodes("access-broker/access-broker")
                        .get(0));
                Element targetsIAccess = dFac.createElement(new QName("access"), 1);
                targetsIAccess.addAttribute("impl", DummyAccessType.class.getName());
                targetsIAccessBroker.add(targetsIAccess);

                //
                // Change permissions internals
                //

                List permissionsAccess = permissions.selectNodes("access-broker/jit-rule/behavior/access");
                for (int i = 0; i < permissionsAccess.size(); i++) {
                    // Add impl attribute with value of fully-qualified class name
                    ((Element) permissionsAccess.get(i)).addAttribute("impl",
                            BriefcaseAccessType.class.getName());

                    // Get all child type elements and replace them
                    List types = ((Element) permissionsAccess.get(i)).elements();
                    for (int j = 0; j < types.size(); j++) {
                        Attribute value = ((Element) types.get(j)).attribute("value");
                        String text = value.getValue();
                        value.setValue("GRANT");

                        if (text.equals("0")) {
                            BriefcaseAccessType[] aTypes = BriefcaseAccessType.getInstances();
                            ((Element) types.get(j)).addAttribute("handle", aTypes[0].getName());

                            for (int k = 1; k < aTypes.length; k++) {
                                Element eType = dFac.createElement(new QName("type"), 2);
                                eType.addAttribute("value", "GRANT");
                                eType.addAttribute("handle", aTypes[k].getName());
                                ((Element) permissionsAccess.get(i)).add(eType);
                            }
                        } else {
                            ((Element) types.get(j)).addAttribute("handle",
                                    BriefcaseAccessType.getAccessType(Integer.parseInt(text)).getName());
                        }
                    }

                }

                // Change other elements in the permissions section
                List permissionsBehavior = permissions.selectNodes("access-broker/jit-rule/behavior");
                for (int i = 0; i < permissionsBehavior.size(); i++) {
                    Element trigger = (Element) ((Element) permissionsBehavior.get(i)).elements("trigger")
                            .get(0);
                    Element target = (Element) ((Element) permissionsBehavior.get(i)).elements("target").get(0);
                    Element creator = (Element) ((Element) permissionsBehavior.get(i)).elements("creator")
                            .get(0);

                    // Insert trigger text into target
                    target.addAttribute("type", "GROUP");
                    target.addText(trigger.getText());

                    // Remove current creator element
                    creator.detach();

                    // Add new current creator element
                    Element eCreator = dFac.createElement(new QName("creator"), 1);
                    eCreator.addAttribute("impl", DummyCreator.class.getName());
                    ((Element) permissionsBehavior.get(i)).add(eCreator);
                }

                // Change internal access broker's name
                Element permissionsIAccessBroker = (Element) (permissions
                        .selectNodes("access-broker/access-broker").get(0));
                permissionsIAccessBroker.addAttribute("handle", "personal-resources-p-i");

                // Add internal access broker's access element
                Element permissionsIAccess = dFac.createElement(new QName("access"), 1);
                permissionsIAccess.addAttribute("impl", BriefcaseAccessType.class.getName());
                permissionsIAccessBroker.add(permissionsIAccess);

            }

            List access = oldDoc.selectNodes("/briefcase/drive[@handle!='personal']//access");
            for (int i = 0; i < access.size(); i++) {

                // Add impl attribute with value of fully-qualified class name
                ((Element) access.get(i)).addAttribute("impl", BriefcaseAccessType.class.getName());

                List types = ((Element) access.get(i)).elements();
                for (int j = 0; j < types.size(); j++) {
                    Attribute value = ((Element) types.get(j)).attribute("value");
                    String text = value.getValue();
                    value.setValue("GRANT");

                    if (text.equals("0")) {
                        BriefcaseAccessType[] aTypes = BriefcaseAccessType.getInstances();
                        ((Element) types.get(j)).addAttribute("handle", aTypes[0].getName());

                        for (int k = 1; k < aTypes.length; k++) {
                            Element eType = dFac.createElement(new QName("type"), 2);
                            eType.addAttribute("value", "GRANT");
                            eType.addAttribute("handle", aTypes[k].getName());
                            ((Element) access.get(i)).add(eType);
                        }
                    } else {
                        ((Element) types.get(j)).addAttribute("handle",
                                BriefcaseAccessType.getAccessType(Integer.parseInt(text)).getName());
                    }
                }
            }

            // add impl attribute to specify the UserDirectory impl to user-attribute element
            List userAttr = oldDoc.selectNodes("//user-attribute");
            for (int i = 0; i < userAttr.size(); i++) {
                ((Element) userAttr.get(i)).addAttribute("impl",
                        "net.unicon.academus.apps.briefcase.UserAttributeDirectory");
            }

            //replace the resource factory urls  
            List entries = oldDoc
                    .selectNodes("/briefcase/drive[@handle!='personal']//access-broker/entry[@target!='']");
            for (int i = 0; i < entries.size(); i++) {
                ((Element) entries.get(i)).addAttribute("target", ((Element) entries.get(i))
                        .attributeValue("target").replaceAll("academus.resource.factory", "demetrius.fac"));
            }

            // add access element to specify the AccessType to the RdbmsAccessBroker
            brokers = oldDoc.selectNodes("/briefcase/drive[@handle!='personal']//access-broker[@impl='"
                    + RdbmsAccessBroker.class.getName() + "']");

            for (int i = 0; i < brokers.size(); i++) {
                broker = (Element) brokers.get(i);
                Element eType = dFac.createElement(new QName("access"), 1);
                eType.addAttribute("impl", BriefcaseAccessType.class.getName());
                broker.add(eType);
            }

            // add the civis address book information.
            Element drive = (Element) oldDoc.selectSingleNode("briefcase");
            drive.addComment("Civis implementation to be used to resolve usernames and group paths"
                    + " to academus users and groups. This should not require"
                    + " modification, as it utilized the Academus framework for gathering this"
                    + " information.");

            Element civis = dFac.createElement("civis");
            civis.addAttribute("id", "addressBook");
            civis.addAttribute("impl", "net.unicon.civis.fac.academus.AcademusCivisFactory");

            Element restrictor = dFac.createElement("restrictor");
            restrictor.addAttribute("impl", "net.unicon.civis.grouprestrictor.AcademusGroupRestrictor");
            civis.add(restrictor);

            drive.add(civis);

            File f = new File(args[1]);
            PrintWriter pw = new PrintWriter(new FileOutputStream(f));
            pw.write(oldDoc.asXML());
            pw.flush();
            pw.close();

            System.out.println(
                    "Done. Enjoy !! \n Remember to the use the migrated config file with the 1.6 deploy.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        usage();
    }

}

From source file:net.yrom.builder.util.ManifestParser.java

License:Apache License

public void newVersionInfo(int versionCode, String versionName) {
    Attribute code = manifest.attribute(qVersionCode);
    if (versionCode != 0 && Integer.parseInt(code.getValue()) != versionCode)
        code.setValue(String.valueOf(versionCode));
    if (versionName != null && versionName.trim().length() > 0)
        manifest.attribute(qVersionName).setValue(versionName);

}

From source file:net.yrom.builder.util.ManifestParser.java

License:Apache License

/**
 * ?meta-data/*from w ww .  j a  v  a2s  . com*/
 * @param name
 * @param value
 * @param add ???meta-data?
 */
public void replaceMetaData(String name, String value, boolean add) {
    Iterator<Element> iterator = application.elementIterator("meta-data");
    boolean hasData = false;
    for (; iterator.hasNext();) {

        Element data = iterator.next();
        String nameValue = data.attributeValue(androidName);
        if (nameValue != null && nameValue.equals(name)) {
            Attribute attribute = data.attribute(androidValue);
            hasData = attribute.getValue().equals(value);
            if (attribute != null && !hasData) {
                attribute.setValue(value);
                return;
            }
        }
    }
    if (add && !hasData)
        application.addElement("meta-data").addAttribute(androidName, name).addAttribute(androidValue, value);
}

From source file:nl.tue.gale.ae.processor.xmlmodule.ForModule.java

License:Open Source License

@SuppressWarnings("unchecked")
private void replace(Element element, Pattern p, String replace) {
    for (Attribute a : (List<Attribute>) element.attributes()) {
        a.setValue(replace(a.getValue(), p, replace));
    }/*from   www .  ja  v  a 2 s.c om*/
    for (Element e : (List<Element>) element.elements())
        replace(e, p, replace);
}

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  ww  w. ja  va  2  s  .co  m*/
            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 w w.j  a  v  a 2 s  .c om

    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/*from www  .j ava 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);
            }
        }
    }
}

From source file:org.b5chat.crossfire.core.plugin.PluginManager.java

License:Open Source License

/**
 * Loads a plug-in module into the container. Loading consists of the
 * following steps:<ul>/*from   www .jav a2s.  co m*/
 * <p/>
 * <li>Add all jars in the <tt>lib</tt> dir (if it exists) to the class loader</li>
 * <li>Add all files in <tt>classes</tt> dir (if it exists) to the class loader</li>
 * <li>Locate and load <tt>module.xml</tt> into the context</li>
 * <li>For each b5chat.module entry, load the given class as a module and start it</li>
 * <p/>
 * </ul>
 *
 * @param pluginDir the plugin directory.
 */
private void loadPlugin(File pluginDir) {
    // Only load the admin plugin during setup mode.
    if (XmppServer.getInstance().isSetupMode() && !(pluginDir.getName().equals("admin"))) {
        return;
    }
    Log.debug("PluginManager: Loading plugin " + pluginDir.getName());
    IPlugin plugin;
    try {
        File pluginConfig = new File(pluginDir, "plugin.xml");
        if (pluginConfig.exists()) {
            SAXReader saxReader = new SAXReader();
            saxReader.setEncoding("UTF-8");
            Document pluginXML = saxReader.read(pluginConfig);

            // See if the plugin specifies a version of crossfire
            // required to run.
            Element minServerVersion = (Element) pluginXML.selectSingleNode("/plugin/minServerVersion");
            if (minServerVersion != null) {
                String requiredVersion = minServerVersion.getTextTrim();
                Version version = XmppServer.getInstance().getServerInfo().getVersion();
                String hasVersion = version.getMajor() + "." + version.getMinor() + "." + version.getMicro();
                if (hasVersion.compareTo(requiredVersion) < 0) {
                    String msg = "Ignoring plugin " + pluginDir.getName() + ": requires " + "server version "
                            + requiredVersion;
                    Log.warn(msg);
                    System.out.println(msg);
                    return;
                }
            }

            PluginClassLoader pluginLoader;

            // Check to see if this is a child plugin of another plugin. If it is, we
            // re-use the parent plugin's class loader so that the plugins can interact.
            Element parentPluginNode = (Element) pluginXML.selectSingleNode("/plugin/parentPlugin");

            String pluginName = pluginDir.getName();
            String webRootKey = pluginName + ".webRoot";
            String classesDirKey = pluginName + ".classes";
            String webRoot = System.getProperty(webRootKey);
            String classesDir = System.getProperty(classesDirKey);

            if (webRoot != null) {
                final File compilationClassesDir = new File(pluginDir, "classes");
                if (!compilationClassesDir.exists()) {
                    compilationClassesDir.mkdir();
                }
                compilationClassesDir.deleteOnExit();
            }

            if (parentPluginNode != null) {
                String parentPlugin = parentPluginNode.getTextTrim();
                // See if the parent is already loaded.
                if (plugins.containsKey(parentPlugin)) {
                    pluginLoader = classloaders.get(getPlugin(parentPlugin));
                    pluginLoader.addDirectory(pluginDir, classesDir != null);

                } else {
                    // See if the parent plugin exists but just hasn't been loaded yet.
                    // This can only be the case if this plugin name is alphabetically before
                    // the parent.
                    if (pluginName.compareTo(parentPlugin) < 0) {
                        // See if the parent exists.
                        File file = new File(pluginDir.getParentFile(), parentPlugin + ".jar");
                        if (file.exists()) {
                            // Silently return. The child plugin will get loaded up on the next
                            // plugin load run after the parent.
                            return;
                        } else {
                            file = new File(pluginDir.getParentFile(), parentPlugin + ".war");
                            if (file.exists()) {
                                // Silently return. The child plugin will get loaded up on the next
                                // plugin load run after the parent.
                                return;
                            } else {
                                String msg = "Ignoring plugin " + pluginName + ": parent plugin " + parentPlugin
                                        + " not present.";
                                Log.warn(msg);
                                System.out.println(msg);
                                return;
                            }
                        }
                    } else {
                        String msg = "Ignoring plugin " + pluginName + ": parent plugin " + parentPlugin
                                + " not present.";
                        Log.warn(msg);
                        System.out.println(msg);
                        return;
                    }
                }
            }
            // This is not a child plugin, so create a new class loader.
            else {
                pluginLoader = new PluginClassLoader();
                pluginLoader.addDirectory(pluginDir, classesDir != null);
            }

            // Check to see if development mode is turned on for the plugin. If it is,
            // configure dev mode.

            PluginDevEnvironment dev = null;
            if (webRoot != null || classesDir != null) {
                dev = new PluginDevEnvironment();

                System.out.println("IPlugin " + pluginName + " is running in development mode.");
                Log.info("IPlugin " + pluginName + " is running in development mode.");
                if (webRoot != null) {
                    File webRootDir = new File(webRoot);
                    if (!webRootDir.exists()) {
                        // Ok, let's try it relative from this plugin dir?
                        webRootDir = new File(pluginDir, webRoot);
                    }

                    if (webRootDir.exists()) {
                        dev.setWebRoot(webRootDir);
                    }
                }

                if (classesDir != null) {
                    File classes = new File(classesDir);
                    if (!classes.exists()) {
                        // ok, let's try it relative from this plugin dir?
                        classes = new File(pluginDir, classesDir);
                    }

                    if (classes.exists()) {
                        dev.setClassesDir(classes);
                        pluginLoader.addURLFile(classes.getAbsoluteFile().toURI().toURL());
                    }
                }
            }

            String className = pluginXML.selectSingleNode("/plugin/class").getText().trim();
            plugin = (IPlugin) pluginLoader.loadClass(className).newInstance();
            if (parentPluginNode != null) {
                String parentPlugin = parentPluginNode.getTextTrim();
                // See if the parent is already loaded.
                if (plugins.containsKey(parentPlugin)) {
                    pluginLoader = classloaders.get(getPlugin(parentPlugin));
                    classloaders.put(plugin, pluginLoader);
                }
            }

            plugins.put(pluginName, plugin);
            pluginDirs.put(plugin, pluginDir);

            // If this is a child plugin, register it as such.
            if (parentPluginNode != null) {
                String parentPlugin = parentPluginNode.getTextTrim();
                List<String> childrenPlugins = parentPluginMap.get(plugins.get(parentPlugin));
                if (childrenPlugins == null) {
                    childrenPlugins = new ArrayList<String>();
                    parentPluginMap.put(plugins.get(parentPlugin), childrenPlugins);
                }
                childrenPlugins.add(pluginName);
                // Also register child to parent relationship.
                childPluginMap.put(plugin, parentPlugin);
            } else {
                // Only register the class loader in the case of this not being
                // a child plugin.
                classloaders.put(plugin, pluginLoader);
            }

            // Check the plugin's database schema (if it requires one).
            if (!DbConnectionManager.getSchemaManager().checkPluginSchema(plugin)) {
                // The schema was not there and auto-upgrade failed.
                Log.error(pluginName + " - " + LocaleUtils.getLocalizedString("upgrade.database.failure"));
                System.out.println(
                        pluginName + " - " + LocaleUtils.getLocalizedString("upgrade.database.failure"));
            }

            // Load any JSP's defined by the plugin.
            File webXML = new File(pluginDir, "web" + File.separator + "WEB-INF" + File.separator + "web.xml");
            if (webXML.exists()) {
                PluginServlet.registerServlets(this, plugin, webXML);
            }
            // Load any custom-defined servlets.
            File customWebXML = new File(pluginDir,
                    "web" + File.separator + "WEB-INF" + File.separator + "web-custom.xml");
            if (customWebXML.exists()) {
                PluginServlet.registerServlets(this, plugin, customWebXML);
            }

            if (dev != null) {
                pluginDevelopment.put(plugin, dev);
            }

            // Configure caches of the plugin
            configureCaches(pluginDir, pluginName);

            // Init the plugin.
            ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(pluginLoader);
            plugin.initializePlugin(this, pluginDir);
            Thread.currentThread().setContextClassLoader(oldLoader);

            // If there a <adminconsole> section defined, register it.
            Element adminElement = (Element) pluginXML.selectSingleNode("/plugin/adminconsole");
            if (adminElement != null) {
                Element appName = (Element) adminElement
                        .selectSingleNode("/plugin/adminconsole/global/appname");
                if (appName != null) {
                    // Set the plugin name so that the proper i18n String can be loaded.
                    appName.addAttribute("plugin", pluginName);
                }
                // If global images are specified, override their URL.
                Element imageEl = (Element) adminElement
                        .selectSingleNode("/plugin/adminconsole/global/logo-image");
                if (imageEl != null) {
                    imageEl.setText("plugins/" + pluginName + "/" + imageEl.getText());
                    // Set the plugin name so that the proper i18n String can be loaded.
                    imageEl.addAttribute("plugin", pluginName);
                }
                imageEl = (Element) adminElement.selectSingleNode("/plugin/adminconsole/global/login-image");
                if (imageEl != null) {
                    imageEl.setText("plugins/" + pluginName + "/" + imageEl.getText());
                    // Set the plugin name so that the proper i18n String can be loaded.
                    imageEl.addAttribute("plugin", pluginName);
                }
                // Modify all the URL's in the XML so that they are passed through
                // the plugin servlet correctly.
                @SuppressWarnings("unchecked")
                List<Object> urls = adminElement.selectNodes("//@url");
                for (Object url : urls) {
                    Attribute attr = (Attribute) url;
                    attr.setValue("plugins/" + pluginName + "/" + attr.getValue());
                }
                // In order to internationalize the names and descriptions in the model,
                // we add a "plugin" attribute to each tab, sidebar, and item so that
                // the the renderer knows where to load the i18n Strings from.
                String[] elementNames = new String[] { "tab", "sidebar", "item" };
                for (String elementName : elementNames) {
                    @SuppressWarnings("unchecked")
                    List<Object> values = adminElement.selectNodes("//" + elementName);
                    for (Object value : values) {
                        Element element = (Element) value;
                        // Make sure there's a name or description. Otherwise, no need to
                        // override i18n settings.
                        if (element.attribute("name") != null || element.attribute("value") != null) {
                            element.addAttribute("plugin", pluginName);
                        }
                    }
                }

                AdminConsole.addModel(pluginName, adminElement);
            }
            firePluginCreatedEvent(pluginName, plugin);
        } else {
            Log.warn("IPlugin " + pluginDir + " could not be loaded: no plugin.xml file found");
        }
    } catch (Throwable e) {
        Log.error("Error loading plugin: " + pluginDir, e);
    }
}

From source file:org.hibernate.envers.configuration.internal.metadata.MetadataTools.java

License:LGPL

private static void addOrModifyAttribute(Element parent, String name, String value) {
    final Attribute attribute = parent.attribute(name);
    if (attribute == null) {
        parent.addAttribute(name, value);
    } else {//  www. j ava2s. c  om
        attribute.setValue(value);
    }
}

From source file:org.hibernate.envers.configuration.metadata.MetadataTools.java

License:Open Source License

private static void addOrModifyAttribute(Element parent, String name, String value) {
    Attribute attribute = parent.attribute(name);
    if (attribute == null) {
        parent.addAttribute(name, value);
    } else {//from   ww w  . j  a  v  a2s .co  m
        attribute.setValue(value);
    }
}