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:org.jasig.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. j ava 2s.c  o  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.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

License:Apache License

private org.dom4j.Element getExportLayoutDom(IPerson person, IUserProfile profile) {
    if (!this.layoutExistsForUser(person)) {
        return null;
    }//  w ww.  j a v a2 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.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
@Transactional/* w w  w . j  ava  2  s .com*/
public void importLayout(org.dom4j.Element layout) {
    if (layout.getNamespaceForPrefix("dlm") == null) {
        layout.add(new Namespace("dlm", "http://www.uportal.org/layout/dlm"));
    }

    //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.jasig.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.jasig.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.jasig.portal.tenants.TemplateDataTenantOperationsListener.java

License:Apache License

@Override
public void onCreate(final ITenant tenant) {

    final StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setRootObject(new RootObjectImpl(tenant));

    /*//w  w w. j  a  va 2s. c  om
     * First load dom4j Documents and sort the entity files into the proper order 
     */
    final Map<PortalDataKey, Set<Document>> importQueue = new HashMap<PortalDataKey, Set<Document>>();
    Resource rsc = null;
    try {
        for (Resource r : templateResources) {
            rsc = r;
            if (log.isDebugEnabled()) {
                log.debug("Loading template resource file for tenant " + "'" + tenant.getFname() + "':  "
                        + rsc.getFilename());
            }
            final Document doc = reader.read(rsc.getInputStream());
            final QName qname = doc.getRootElement().getQName();
            PortalDataKey atLeastOneMatchingDataKey = null;
            for (PortalDataKey pdk : dataKeyImportOrder) {
                // Matching is tougher because it's dom4j <> w3c...
                boolean matches = qname.getName().equals(pdk.getName().getLocalPart())
                        && qname.getNamespaceURI().equals(pdk.getName().getNamespaceURI());
                if (matches) {
                    // Found the right bucket...
                    atLeastOneMatchingDataKey = pdk;
                    Set<Document> bucket = importQueue.get(atLeastOneMatchingDataKey);
                    if (bucket == null) {
                        // First of these we've seen;  create the bucket;
                        bucket = new HashSet<Document>();
                        importQueue.put(atLeastOneMatchingDataKey, bucket);
                    }
                    bucket.add(doc);
                    /*
                     * At this point, we would normally add a break;
                     * statement, but group_membership.xml files need to
                     * match more than one PortalDataKey.
                     */
                }
            }
            if (atLeastOneMatchingDataKey == null) {
                // We can't proceed
                throw new RuntimeException(
                        "No PortalDataKey found for QName:  " + doc.getRootElement().getQName());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to process the specified template:  " + (rsc != null ? rsc.getFilename() : ""), e);
    }

    log.trace("Ready to import data entity templates for new tenant '{}';  importQueue={}", tenant.getName(),
            importQueue);

    /*
     * Now import the identified entities each bucket in turn 
     */
    Document doc = null;
    org.w3c.dom.Document w3c = null;
    try {
        for (PortalDataKey pdk : dataKeyImportOrder) {
            Set<Document> bucket = importQueue.get(pdk);
            if (bucket != null) {
                log.debug("Importing the specified PortalDataKey tenant '{}':  {}", tenant.getName(),
                        pdk.getName());
                for (Document d : bucket) {
                    doc = d;
                    log.trace("Importing document XML={}", doc.asXML());
                    for (String xpath : XPATH_EXPRESSIONS) {
                        @SuppressWarnings("unchecked")
                        List<Node> nodes = doc.selectNodes(xpath);
                        for (Node n : nodes) {
                            String inpt, otpt;
                            switch (n.getNodeType()) {
                            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                                Attribute a = (Attribute) n;
                                inpt = a.getValue();
                                otpt = processText(inpt, ctx);
                                if (!otpt.equals(inpt)) {
                                    a.setValue(otpt);
                                }
                                break;
                            case org.w3c.dom.Node.TEXT_NODE:
                                Text t = (Text) n;
                                inpt = t.getText();
                                otpt = processText(inpt, ctx);
                                if (!otpt.equals(inpt)) {
                                    t.setText(otpt);
                                }
                                break;
                            default:
                                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                                throw new RuntimeException(msg);
                            }
                        }
                    }
                    w3c = writer.write(doc, domImpl);
                    Source source = new DOMSource(w3c);
                    source.setSystemId(rsc.getFilename()); // must be set, else import chokes
                    dataHandlerService.importData(source, pdk);
                }
            }
        }

    } catch (Exception e) {
        log.warn("w3c DOM=" + this.nodeToString(w3c));
        throw new RuntimeException(
                "Failed to process the specified template document:  " + (doc != null ? doc.asXML() : ""), e);
    }

}

From source file:org.jbpm.gd.jpdl.properties.TaskFormGenerationDialog.java

License:Open Source License

private void addForm(Document document) {
    Element element = getElementFor(taskName, document);
    if (element == null) {
        element = document.getRootElement().addElement("form");
        element.addAttribute("task", taskName);
    }/* w  w  w .  j ava 2  s. c  o  m*/
    Attribute form = element.attribute("form");
    if (form == null) {
        element.addAttribute("form", fileNameText.getText());
    } else {
        form.setValue(fileNameText.getText());
    }
}

From source file:org.jivesoftware.openfire.container.PluginManager.java

License:Open Source License

/**
 * Loads a plug-in module into the container. Loading consists of the
 * following steps:<ul>//from   w  w  w  .ja  v  a  2 s. c o  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 jive.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());
    Plugin 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 Openfire
            // required to run.
            Element minServerVersion = (Element) pluginXML.selectSingleNode("/plugin/minServerVersion");
            if (minServerVersion != null) {
                Version requiredVersion = new Version(minServerVersion.getTextTrim());
                Version currentVersion = XMPPServer.getInstance().getServerInfo().getVersion();
                if (requiredVersion.isNewerThan(currentVersion)) {
                    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("Plugin " + pluginName + " is running in development mode.");
                Log.info("Plugin " + 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 = (Plugin) 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.
                List 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) {
                    List 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("Plugin " + pluginDir + " could not be loaded: no plugin.xml file found");
        }
    } catch (Throwable e) {
        Log.error("Error loading plugin: " + pluginDir, e);
    }
}

From source file:org.mule.intents.AppBuilder.java

License:Open Source License

protected void addSchemaLocations(Document snippet) {
    Attribute att = snippet.getRootElement().attribute(xsiQN);
    if (att == null) {
        return;/*www  .  j  a  v a 2  s  . c  om*/
    }

    Attribute existing = config.getRootElement().attribute(xsiQN);
    if (existing == null) {
        config.getRootElement().addAttribute(xsiQN, "");
        existing = config.getRootElement().attribute(xsiQN);
    }

    //save schemaLocations
    for (StringTokenizer tokenizer = new StringTokenizer(att.getValue(), " "); tokenizer.hasMoreTokens();) {
        String x = tokenizer.nextToken();
        String y = tokenizer.nextToken();
        schemaLocations.put(x, y);
    }

    StringBuilder buf = new StringBuilder();
    for (String s : schemaLocations.keySet()) {
        buf.append(s).append(" ").append(schemaLocations.get(s)).append("\n");
    }

    existing.setValue(buf.toString());

    System.out.println("xsi:schemaLocation = " + existing.getValue());
}

From source file:org.openadaptor.auxil.convertor.map.Dom4JDocumentMapFacade.java

License:Open Source License

private Object modify(Node node, Attribute attribute) {
    Object old = null;/* w w  w  .  j  a  v  a2s  .  c  o m*/
    if (node instanceof Element) { //Set or replace value of attribute on Element
        Element element = (Element) node;
        String attrName = attribute.getName();
        Attribute existing = element.attribute(attrName);
        if (existing != null) {
            element.remove(existing);
            old = existing;
        }
        element.add(attribute);
    } else if (node instanceof Attribute) { //Modify the value of the existing attribute.
        Attribute existing = (Attribute) node;
        old = DocumentHelper.createAttribute(null, existing.getName(), existing.getValue());
        existing.setValue(attribute.getValue());
    } else {
        throw new RecordException(
                "Target of put(x,Attribute) must be empty or an existing Element or Attribute. Got: " + node);
    }
    return old;
}

From source file:org.openadaptor.auxil.convertor.map.Dom4JDocumentMapFacade.java

License:Open Source License

private Object modify(Node node, String value) {
    Object old = null;//from   ww w.j  a  va2  s.  c o  m
    if (node instanceof Element) { //Set the text of the element
        Element element = (Element) node;
        old = element.getText();
        element.setText(value);
    } else if (node instanceof Attribute) {//Test the value of the attribute
        Attribute attribute = (Attribute) node;
        old = attribute.getValue();
        attribute.setValue(value);
    } else if (node instanceof Text) {
        Text text = (Text) node;
        old = node.getText();
        text.setText(value);
    }
    return old;
}

From source file:org.opencms.relations.CmsLinkUpdateUtil.java

License:Open Source License

/**
 * Updates the given xml element attribute with the given value.<p> 
 * /*  ww w  . jav a2  s  . co m*/
 * @param parent the element to set the attribute for
 * @param attrName the attribute name
 * @param value the value to set, or <code>null</code> to remove
 */
private static void updateAttribute(Element parent, String attrName, String value) {

    if (parent != null) {
        Attribute attribute = parent.attribute(attrName);
        if (value != null) {
            if (attribute == null) {
                parent.addAttribute(attrName, value);
            } else {
                attribute.setValue(value);
            }
        } else {
            // remove only if exists
            if (attribute != null) {
                parent.remove(attribute);
            }
        }
    }
}