Example usage for org.w3c.dom NamedNodeMap getNamedItem

List of usage examples for org.w3c.dom NamedNodeMap getNamedItem

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getNamedItem.

Prototype

public Node getNamedItem(String name);

Source Link

Document

Retrieves a node specified by name.

Usage

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

private void loadAudienceEvaluators(NodeList nodes) {
    final String evaluatorFactoryAtt = "evaluatorFactory";

    for (int i = 0; i < nodes.getLength(); i++) {
        Node audience = nodes.item(i);
        NamedNodeMap atts = audience.getAttributes();
        Node att = atts.getNamedItem(evaluatorFactoryAtt);
        if (att == null || att.getNodeValue().equals(""))
            throw new RuntimeException(
                    "Required attibute '" + evaluatorFactoryAtt + "' " + "is missing or empty on 'audience' "
                            + " element in\n'" + XmlUtilitiesImpl.toString(audience) + "'");
        String className = att.getNodeValue();

        /*//w w  w. j  a  va2  s. co  m
         * For version 5.0, all uPortal sources were repackaged from 'org.jasig.portal'
         * to 'org.apereo.portal'.  *.fragment-definition.xml files exported from earlier
         * versions of uPortal will contain the old evaluatorFactory name.  We can detect
         * that and intervene here.
         */
        className = className.replace("org.jasig.portal", "org.apereo.portal");

        EvaluatorFactory factory = loadEvaluatorFactory(className, audience);
        addEvaluator(factory, audience);
    }
}

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

private String loadAttribute(String name, NamedNodeMap atts, boolean required, Element e) {
    Node att = atts.getNamedItem(name);
    if (required && (att == null || att.getNodeValue().equals("")))
        throw new RuntimeException("Missing or empty attribute '" + name + "' required by <fragment> in\n'"
                + XmlUtilitiesImpl.toString(e) + "'");
    if (att == null)
        return null;
    return att.getNodeValue();
}

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

/**
 * Returns a valid {@link Noderef} based on the specified arguments or 
 * <code>null</null> if that's not possible.<br/>
 * /*from www  .  ja v  a2  s.  c om*/
 * <strong>This method returns <code>null</code> if the pathref cannot be 
 * resolved to a node on the specified layout.</strong>  It is the 
 * responsibility of calling code to handle this case appropriately.
 * 
 * @return a valid {@link Noderef} or <code>null</null>
 */
public Noderef getNoderefFromPathref(String layoutOwner, String pathref, String fname, boolean isStructRef,
        org.dom4j.Element layoutElement) {

    Validate.notNull(layoutOwner, "Argument 'layoutOwner' cannot be null.");
    Validate.notNull(pathref, "Argument 'pathref' cannot be null.");

    if (log.isTraceEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("getDlmNoderef: [layoutOwner='").append(layoutOwner).append("', pathref='").append(pathref)
                .append("', fname='").append(fname).append("', isStructRef='").append(isStructRef).append("']");
        log.trace(msg.toString());
        log.trace("getDlmNoderef: user layout document follows...\n" + layoutElement.asXML());
    }

    final String[] pathTokens = DLM_PATH_REF_DELIM.split(pathref);
    if (pathTokens.length <= 1) {
        this.log.warn("Invalid DLM PathRef, no delimiter: " + pathref);
        return null;
    }

    if (pathTokens[0].equals(layoutOwner)) {
        // This an internal reference (our own layout);  we have to 
        // use the layoutExment (instead of load-limited-layout) b/c 
        // our layout may not be in the db...
        final org.dom4j.Element target = (org.dom4j.Element) layoutElement.selectSingleNode(pathTokens[1]);
        if (target != null) {
            return new Noderef(target.valueOf("@ID"));
        }

        this.log.warn("Unable to resolve pathref '" + pathref + "' for layoutOwner '" + layoutOwner + "'");
        return null;
    }

    /*
     * We know this Noderef refers to a node on a DLM fragment
     */

    final String layoutOwnerName = pathTokens[0];
    final String layoutPath = pathTokens[1];

    final Integer layoutOwnerUserId = this.userIdentityStore.getPortalUserId(layoutOwnerName);
    if (layoutOwnerUserId == null) {
        this.log.warn("Unable to resolve pathref '" + pathref + "' for layoutOwner '" + layoutOwner
                + "', no userId found for userName: " + layoutOwnerName);
        return null;
    }

    final Tuple<String, DistributedUserLayout> userLayoutInfo = getUserLayoutTuple(layoutOwnerName,
            layoutOwnerUserId);
    final Document userLayout = userLayoutInfo.second.getLayout();

    final Node targetNode = this.xPathOperations.evaluate(layoutPath, userLayout, XPathConstants.NODE);
    if (targetNode == null) {
        this.log.warn("No layout node found for pathref: " + pathref);
        return null;
    }

    final NamedNodeMap attributes = targetNode.getAttributes();
    if (fname != null) {
        final Node fnameAttr = attributes.getNamedItem("fname");
        if (fnameAttr == null) {
            this.log.warn("Layout node for pathref does not have fname attribute: " + pathref);
            return null;
        }

        final String nodeFname = fnameAttr.getTextContent();
        if (!fname.equals(nodeFname)) {
            this.log.warn("fname '" + nodeFname + "' on layout node not match specified fname '" + fname
                    + "' for pathref: " + pathref);
            return null;
        }
    }

    final Node structIdAttr = attributes.getNamedItem("struct-id");
    if (structIdAttr != null) {
        final String structId = structIdAttr.getTextContent();

        if (isStructRef) {
            return new Noderef(layoutOwnerUserId, 1 /* TODO:  remove hard-coded layoutId=1 */, "s" + structId);
        }

        return new Noderef(layoutOwnerUserId, 1 /* TODO:  remove hard-coded layoutId=1 */, "n" + structId);
    }

    final Node idAttr = attributes.getNamedItem("ID");
    return new Noderef(layoutOwnerUserId, 1 /* TODO:  remove hard-coded layoutId=1 */, idAttr.getTextContent());

}

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

@Override
protected Element getStructure(Document doc, LayoutStructure ls) {
    Element structure = null;//w  w  w . j  a  v a  2 s.  c om

    String type = ls.getType();

    if (ls.isChannel()) {
        final IPortletDefinition channelDef = this.portletDefinitionRegistry
                .getPortletDefinition(String.valueOf(ls.getChanId()));
        if (channelDef != null && channelApproved(channelDef.getApprovalDate())) {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(), channelDef,
                    ls.getLocale());
        } else {
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(),
                    MissingPortletDefinition.INSTANCE, null);
        }
    } else {
        // create folder objects including dlm new types in cp namespace
        if (type != null && type.startsWith(Constants.NS)) {
            structure = doc.createElementNS(Constants.NS_URI, type);
        } else {
            structure = doc.createElement("folder");
        }
        structure.setAttribute("name", ls.getName());
        structure.setAttribute("type", (type != null ? type : "regular"));
    }

    structure.setAttribute("hidden", (ls.isHidden() ? "true" : "false"));
    structure.setAttribute("immutable", (ls.isImmutable() ? "true" : "false"));
    structure.setAttribute("unremovable", (ls.isUnremovable() ? "true" : "false"));
    if (localeAware) {
        structure.setAttribute("locale", ls.getLocale()); // for i18n by Shoji
    }

    /*
     * Parameters from up_layout_param are loaded slightly differently for
     * folders and channels. For folders all parameters are added as attributes
     * of the Element. For channels only those parameters with names starting
     * with the dlm namespace Constants.NS are added as attributes to the Element.
     * Others are added as child parameter Elements.
     */
    if (ls.getParameters() != null) {
        for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
            final StructureParameter sp = (StructureParameter) itr.next();
            String pName = sp.getName();

            if (!ls.isChannel()) { // Folder
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                } else {
                    structure.setAttribute(pName, sp.getValue());
                }
            } else // Channel
            {
                // if dealing with a dlm namespace param add as attribute
                if (pName.startsWith(Constants.NS)) {
                    structure.setAttributeNS(Constants.NS_URI, pName, sp.getValue());
                    itr.remove();
                } else {
                    /*
                     * do traditional override processing. some explanation is in
                     * order. The structure element was created by the
                     * ChannelDefinition and only contains parameter children if the
                     * definition had defined parameters. These are checked for each
                     * layout loaded parameter as found in LayoutStructure.parameters.
                     * If a name match is found then we need to see if overriding is
                     * allowed and if so we set the value on the child parameter
                     * element. At that point we are done with that version loaded
                     * from the layout so we remove it from the in-memory set of
                     * parameters that are being merged-in. Then, after all such have
                     * been checked against those added by the channel definition we
                     * add in any remaining as adhoc, unregulated parameters.
                     */
                    final NodeList nodeListParameters = structure.getElementsByTagName("parameter");
                    for (int j = 0; j < nodeListParameters.getLength(); j++) {
                        final Element parmElement = (Element) nodeListParameters.item(j);
                        final NamedNodeMap nm = parmElement.getAttributes();

                        final String nodeName = nm.getNamedItem("name").getNodeValue();
                        if (nodeName.equals(pName)) {
                            final Node override = nm.getNamedItem("override");
                            if (override != null && override.getNodeValue().equals("yes")) {
                                final Node valueNode = nm.getNamedItem("value");
                                valueNode.setNodeValue(sp.getValue());
                            }
                            itr.remove();
                            break; // found the corresponding one so skip the rest
                        }
                    }
                }
            }
        }
        // For channels, add any remaining parameter elements loaded with the
        // layout as adhoc, unregulated, parameter children that can be overridden.
        if (ls.isChannel()) {
            for (final Iterator itr = ls.getParameters().iterator(); itr.hasNext();) {
                final StructureParameter sp = (StructureParameter) itr.next();
                final Element parameter = doc.createElement("parameter");
                parameter.setAttribute("name", sp.getName());
                parameter.setAttribute("value", sp.getValue());
                parameter.setAttribute("override", "yes");
                structure.appendChild(parameter);
            }
        }
    }
    // finish setting up elements based on loaded params
    final String origin = structure.getAttribute(Constants.ATT_ORIGIN);
    final String prefix = ls.isChannel() ? channelPrefix : folderPrefix;

    // if not null we are dealing with a node incorporated from another
    // layout and this node contains changes made by the user so handle
    // id swapping.
    if (!origin.equals("")) {
        structure.setAttributeNS(Constants.NS_URI, Constants.ATT_PLF_ID, prefix + ls.getStructId());
        structure.setAttribute("ID", origin);
    } else if (!ls.isChannel())
    // regular folder owned by this user, need to check if this is a
    // directive or ui element. If the latter then use traditional id
    // structure
    {
        if (type != null && type.startsWith(Constants.NS)) {
            structure.setAttribute("ID", Constants.DIRECTIVE_PREFIX + ls.getStructId());
        } else {
            structure.setAttribute("ID", folderPrefix + ls.getStructId());
        }
    } else {
        logger.debug("Adding identifier {}{}", folderPrefix, ls.getStructId());
        structure.setAttribute("ID", channelPrefix + ls.getStructId());
    }
    structure.setIdAttribute(Constants.ATT_ID, true);
    return structure;
}

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

@Override
protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt)
        throws SQLException {
    if (node == null) { // No more
        return 0;
    }//from w  w  w.  j  a v  a  2 s .c  o  m
    if (node.getNodeName().equals("parameter")) {
        //parameter, skip it and go on to the next node
        return this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    }
    if (!(node instanceof Element)) {
        return 0;
    }

    final Element structure = (Element) node;

    if (logger.isDebugEnabled()) {
        logger.debug("saveStructure XML content: {}", XmlUtilitiesImpl.toString(node));
    }

    // determine the struct_id for storing in the db. For incorporated nodes in
    // the plf their ID is a system-wide unique ID while their struct_id for
    // storing in the db is cached in a dlm:plfID attribute.
    int saveStructId = -1;
    final String plfID = structure.getAttribute(Constants.ATT_PLF_ID);

    if (!plfID.equals("")) {
        saveStructId = Integer.parseInt(plfID.substring(1));
    } else {
        final String id = structure.getAttribute("ID");
        saveStructId = Integer.parseInt(id.substring(1));
    }

    int nextStructId = 0;
    int childStructId = 0;
    int chanId = -1;
    IPortletDefinition portletDef = null;
    final boolean isChannel = node.getNodeName().equals("channel");

    if (isChannel) {
        chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
        portletDef = this.portletDefinitionRegistry.getPortletDefinition(String.valueOf(chanId));
        if (portletDef == null) {
            //Portlet doesn't exist any more, drop the layout node
            return 0;
        }
    }

    if (node.hasChildNodes()) {
        childStructId = this.saveStructure(node.getFirstChild(), structStmt, parmStmt);
    }
    nextStructId = this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    structStmt.clearParameters();
    structStmt.setInt(1, saveStructId);
    structStmt.setInt(2, nextStructId);
    structStmt.setInt(3, childStructId);

    final String externalId = structure.getAttribute("external_id");
    if (externalId != null && externalId.trim().length() > 0) {
        final Integer eID = new Integer(externalId);
        structStmt.setInt(4, eID.intValue());
    } else {
        structStmt.setNull(4, java.sql.Types.NUMERIC);

    }
    if (isChannel) {
        structStmt.setInt(5, chanId);
        structStmt.setNull(6, java.sql.Types.VARCHAR);
    } else {
        structStmt.setNull(5, java.sql.Types.NUMERIC);
        structStmt.setString(6, structure.getAttribute("name"));
    }
    final String structType = structure.getAttribute("type");
    structStmt.setString(7, structType);
    structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
    structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
    structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
    logger.debug(structStmt.toString());
    structStmt.executeUpdate();

    // code to persist extension attributes for dlm
    final NamedNodeMap attribs = node.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        final Node attrib = attribs.item(i);
        final String name = attrib.getNodeName();

        if (name.startsWith(Constants.NS) && !name.equals(Constants.ATT_PLF_ID)
                && !name.equals(Constants.ATT_FRAGMENT) && !name.equals(Constants.ATT_PRECEDENCE)) {
            // a cp extension attribute. Push into param table.
            parmStmt.clearParameters();
            parmStmt.setInt(1, saveStructId);
            parmStmt.setString(2, name);
            parmStmt.setString(3, attrib.getNodeValue());
            logger.debug(parmStmt.toString());
            parmStmt.executeUpdate();
        }
    }
    final NodeList parameters = node.getChildNodes();
    if (parameters != null && isChannel) {
        for (int i = 0; i < parameters.getLength(); i++) {
            if (parameters.item(i).getNodeName().equals("parameter")) {
                final Element parmElement = (Element) parameters.item(i);
                final NamedNodeMap nm = parmElement.getAttributes();
                final String parmName = nm.getNamedItem("name").getNodeValue();
                final String parmValue = nm.getNamedItem("value").getNodeValue();
                final Node override = nm.getNamedItem("override");

                // if no override specified then default to allowed
                if (override != null && !override.getNodeValue().equals("yes")) {
                    // can't override
                } else {
                    // override only for adhoc or if diff from chan def
                    final IPortletDefinitionParameter cp = portletDef.getParameter(parmName);
                    if (cp == null || !cp.getValue().equals(parmValue)) {
                        parmStmt.clearParameters();
                        parmStmt.setInt(1, saveStructId);
                        parmStmt.setString(2, parmName);
                        parmStmt.setString(3, parmValue);
                        logger.debug(parmStmt.toString());
                        parmStmt.executeUpdate();
                    }
                }
            }
        }
    }
    return saveStructId;
}

From source file:org.apereo.portal.rest.LayoutRESTController.java

/**
 * A REST call to get a json feed of the current users layout.  Intent was to provide a layout
 * document without per-tab information for mobile device rendering.
 * @param request The servlet request. Utilized to get the users instance and eventually there layout
 * @param tab The tab name of which you would like to filter; optional; if not provided, will return entire layout.
 * @return json feed of the layout//  w ww. ja v  a 2s  .com
 * @deprecated Use /api/v4-3/dlm/layout.json.  It has much more information about portlets and includes
 *             regions and breakout per tab
 */
@Deprecated
@RequestMapping(value = "/layoutDoc", method = RequestMethod.GET)
public ModelAndView getRESTController(HttpServletRequest request,
        @RequestParam(value = "tab", required = false) String tab) {
    final IPerson person = personManager.getPerson(request);
    List<LayoutPortlet> portlets = new ArrayList<LayoutPortlet>();

    try {

        final IUserInstance ui = userInstanceManager.getUserInstance(request);

        final IUserPreferencesManager upm = ui.getPreferencesManager();

        final IUserProfile profile = upm.getUserProfile();
        final DistributedUserLayout userLayout = userLayoutStore.getUserLayout(person, profile);
        Document document = userLayout.getLayout();

        NodeList portletNodes = null;
        if (tab != null) {
            NodeList folders = document.getElementsByTagName("folder");
            for (int i = 0; i < folders.getLength(); i++) {
                Node node = folders.item(i);
                if (tab.equalsIgnoreCase(node.getAttributes().getNamedItem("name").getNodeValue())) {
                    TabListOfNodes tabNodes = new TabListOfNodes();
                    tabNodes.addAllChannels(node.getChildNodes());
                    portletNodes = tabNodes;
                    break;
                }
            }
        } else {
            portletNodes = document.getElementsByTagName("channel");
        }
        for (int i = 0; i < portletNodes.getLength(); i++) {
            try {

                NamedNodeMap attributes = portletNodes.item(i).getAttributes();
                IPortletDefinition def = portletDao
                        .getPortletDefinitionByFname(attributes.getNamedItem("fname").getNodeValue());
                LayoutPortlet portlet = new LayoutPortlet(def);

                portlet.setNodeId(attributes.getNamedItem("ID").getNodeValue());

                //get alt max URL
                String alternativeMaximizedLink = def.getAlternativeMaximizedLink();
                if (alternativeMaximizedLink != null) {
                    portlet.setUrl(alternativeMaximizedLink);
                    portlet.setAltMaxUrl(true);
                } else {
                    // get the maximized URL for this portlet
                    final IPortalUrlBuilder portalUrlBuilder = urlProvider.getPortalUrlBuilderByLayoutNode(
                            request, attributes.getNamedItem("ID").getNodeValue(), UrlType.RENDER);
                    final IPortletWindowId targetPortletWindowId = portalUrlBuilder.getTargetPortletWindowId();
                    if (targetPortletWindowId != null) {
                        final IPortletUrlBuilder portletUrlBuilder = portalUrlBuilder
                                .getPortletUrlBuilder(targetPortletWindowId);
                        portletUrlBuilder.setWindowState(WindowState.MAXIMIZED);
                    }
                    portlet.setUrl(portalUrlBuilder.getUrlString());
                    portlet.setAltMaxUrl(false);
                }
                portlets.add(portlet);

            } catch (Exception e) {
                log.warn("Exception construction JSON representation of mobile portlet", e);
            }
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("layout", portlets);
        mv.setViewName("json");
        return mv;
    } catch (Exception e) {
        log.error("Error retrieving user layout document", e);
    }

    return null;
}

From source file:org.asqatasun.crawler.util.HeritrixAttributeValueModifier.java

@Override
public Document modifyDocument(Document document, String value) {
    if (value == null || value.isEmpty()) {
        LOGGER.debug(" value is empty " + this.getClass());
        return document;
    }//from   www  . j a v  a 2  s.c  o m
    try {
        Node parentNode = getNodeFromXpath(document);
        NamedNodeMap attr = parentNode.getAttributes();
        Node nodeAttr = attr.getNamedItem(DEFAULT_ATTRIBUTE_NAME);
        if (StringUtils.isNotEmpty(value)) {
            nodeAttr.setTextContent(value);
        } else {
            parentNode.getParentNode().removeChild(parentNode);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Update " + getAttributeValue() + " attribute of bean " + getIdBeanParent()
                    + " with value " + value);
        }
    } catch (XPathExpressionException ex) {
        LOGGER.warn(ex);
    }
    return document;
}

From source file:org.asqatasun.crawler.util.HeritrixAttributeValueModifierAndEraser.java

@Override
public Document modifyDocument(Document document, String value) {
    try {//w  w w  .  j  a v a  2  s  .  c o  m
        Node parentNode = getNodeFromXpath(document);
        NamedNodeMap attr = parentNode.getAttributes();
        Node nodeAttr = attr.getNamedItem(DEFAULT_ATTRIBUTE_NAME);
        if (StringUtils.isNotEmpty(value)) {
            nodeAttr.setTextContent(value);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Update " + getAttributeValue() + " attribute of bean " + getIdBeanParent()
                        + " with value " + value);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Delete " + getAttributeValue() + " attribute of bean " + getIdBeanParent()
                        + " because of null or empty value ");
            }
            parentNode.getParentNode().removeChild(parentNode);
        }
    } catch (XPathExpressionException ex) {
        Logger.getLogger(HeritrixParameterValueModifier.class.getName()).warn(ex);
    }
    return document;
}

From source file:org.asqatasun.crawler.util.HeritrixInverseBooleanAttributeValueModifier.java

@Override
public Document modifyDocument(Document document, String value) {
    if (StringUtils.isBlank(value) || (!value.equalsIgnoreCase(Boolean.FALSE.toString())
            && !value.equalsIgnoreCase(Boolean.TRUE.toString()))) {
        return document;
    }//  w  w  w .  j av a 2s  .  c o m
    try {
        Boolean valueToSet = !Boolean.valueOf(value);
        Node parentNode = getNodeFromXpath(document);
        NamedNodeMap attr = parentNode.getAttributes();
        Node nodeAttr = attr.getNamedItem(DEFAULT_ATTRIBUTE_NAME);
        nodeAttr.setTextContent(valueToSet.toString());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Update " + getAttributeValue() + " attribute of bean " + getIdBeanParent()
                    + " with value " + valueToSet.toString());
        }
    } catch (XPathExpressionException ex) {
        LOGGER.warn(ex);
    }
    return document;
}

From source file:org.asqatasun.processor.DOMHandlerImpl.java

protected Collection<Node> selectChildNodeWithAttributeRecursively(String attributeName, Node node) {// XXX
    Collection<Node> nodes = new ArrayList<Node>();
    NamedNodeMap attributes = node.getAttributes();
    if (attributes != null) {
        Node attribute = attributes.getNamedItem(attributeName);
        if (attribute != null) {
            nodes.add(node);//from  www  .j  a v  a2 s . c  om
        }
    }
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        nodes.addAll(selectChildNodeWithAttributeRecursively(attributeName, childNodes.item(i)));
    }
    return nodes;
}