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.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected Element getStructure(Document doc, LayoutStructure ls) {
    Element structure = null;/*from  w  w w  . j  a  v a2 s . c o  m*/

    // handle migration of legacy namespace
    String type = ls.getType();
    if (type != null && type.startsWith(Constants.LEGACY_NS)) {
        type = Constants.NS + type.substring(Constants.LEGACY_NS.length());
    }

    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 {
            // Create an error channel if channel is missing or not approved
            String missingChannel = "Unknown";
            if (channelDef != null) {
                missingChannel = channelDef.getName();
            }
            structure = this.getElementForChannel(doc, channelPrefix + ls.getStructId(),
                    MissingPortletDefinition.INSTANCE, null);
            //        structure = MissingPortletDefinition.INSTANCE.getDocument(doc, channelPrefix + ls.getStructId());
            //        structure = MissingPortletDefinition.INSTANCE.getDocument(doc, channelPrefix + ls.getStructId(),
            //                "The '" + missingChannel + "' channel is no longer available. " +
            //                "Please remove it from your layout.",
            //                -1);
        }
    } 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();

            // handle migration of legacy namespace
            if (pName.startsWith(Constants.LEGACY_NS)) {
                pName = Constants.NS + sp.getName().substring(Constants.LEGACY_NS.length());
            }

            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 {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding identifier " + folderPrefix + ls.getStructId());
        }
        structure.setAttribute("ID", channelPrefix + ls.getStructId());
    }
    structure.setIdAttribute(Constants.ATT_ID, true);
    return structure;
}

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

@Override
protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt)
        throws SQLException {
    if (node == null) { // No more
        return 0;
    }//  ww 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 (LOG.isDebugEnabled()) {
        LOG.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"))));
    if (LOG.isDebugEnabled()) {
        LOG.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());
            if (LOG.isDebugEnabled()) {
                LOG.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);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(parmStmt);
                        }
                        parmStmt.executeUpdate();
                    }
                }
            }
        }
    }
    return saveStructId;
}

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

@RequestMapping(value = "/layoutDoc", method = RequestMethod.GET)
public ModelAndView getRESTController(HttpServletRequest request, HttpServletResponse response) {
    final IPerson person = personManager.getPerson(request);
    List<LayoutPortlet> portlets = new ArrayList<LayoutPortlet>();

    try {/*  w  ww .j  av  a 2  s  .co m*/

        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 = document.getElementsByTagName("channel");
        for (int i = 0; i < portletNodes.getLength(); i++) {
            try {

                LayoutPortlet portlet = new LayoutPortlet();
                NamedNodeMap attributes = portletNodes.item(i).getAttributes();
                portlet.setTitle(attributes.getNamedItem("title").getNodeValue());
                portlet.setDescription(attributes.getNamedItem("description").getNodeValue());
                portlet.setNodeId(attributes.getNamedItem("ID").getNodeValue());

                IPortletDefinition def = portletDao
                        .getPortletDefinitionByFname(attributes.getNamedItem("fname").getNodeValue());
                IPortletDefinitionParameter iconParam = def.getParameter("iconUrl");
                if (iconParam != null) {
                    portlet.setIconUrl(iconParam.getValue());
                }

                // 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());
                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.jboss.as.test.integration.management.cli.ModuleTestCase.java

private void checkModuleXml(String slotName, File modulesPath, boolean checkResources,
        boolean checkAbsoluteResources, boolean checkProperties, boolean checkDependencies,
        boolean checkMainClass) throws Exception {
    File testModuleRoot = new File(modulesPath, MODULE_NAME.replace('.', File.separatorChar));
    File slot = new File(testModuleRoot, slotName);
    File moduleXml = new File(slot, "module.xml");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(moduleXml);

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();

    // check resource-root
    XPathExpression pathAttrExpr = xpath.compile("/module/resources/resource-root/@path");
    NodeList nl = (NodeList) pathAttrExpr.evaluate(doc, XPathConstants.NODESET);
    List<String> paths = new ArrayList<>(2);
    for (int i = 0; i < nl.getLength(); i++) {
        paths.add(nl.item(i).getNodeValue());
    }/* ww  w.  j a v a 2  s. c  o m*/
    if (checkResources && checkAbsoluteResources) {
        assertTrue("module.xml should contain two resource-root elements", nl.getLength() == 2);
        assertTrue("module.xml should contain resource-root element with atrribute path=\"Dummy.jar\"",
                paths.contains("Dummy.jar"));
        assertTrue("module.xml should contain resource-root element with atrribute path=\""
                + jarFile2.getCanonicalPath() + "\"", paths.contains(jarFile2.getCanonicalPath()));
    } else if (checkResources && !checkAbsoluteResources) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain resource-root element with atrribute path=\"Dummy.jar\"",
                paths.contains("Dummy.jar"));
    } else if (!checkResources && checkAbsoluteResources) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain resource-root element with atrribute path=\""
                + jarFile2.getCanonicalPath() + "\"", paths.contains(jarFile2.getCanonicalPath()));
    }

    // check properties
    XPathExpression propertiesExpr = xpath.compile("/module/properties/property");
    nl = (NodeList) propertiesExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkProperties) {
        assertTrue("module.xml should contain one property but it has " + nl.getLength() + " properties",
                nl.getLength() == 1);
        NamedNodeMap attributes = nl.item(0).getAttributes();
        String name = attributes.getNamedItem("name").getNodeValue();
        String value = attributes.getNamedItem("value").getNodeValue();
        assertTrue("module.xml should contain property bat=man", name.equals("bat") && value.equals("man"));
    } else {
        assertTrue("module.xml shouldn't contain any properties but it has " + nl.getLength() + " properties",
                nl.getLength() == 0);
    }

    // check dependencies
    XPathExpression dependenciesNameAttrExpr = xpath.compile("/module/dependencies/module/@name");
    nl = (NodeList) dependenciesNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkDependencies) {
        assertTrue("module.xml should contain two resource-root elements", nl.getLength() == 2);
        assertTrue("module.xml should contain module element with atrribute name=\"org.jboss.logging\"",
                nl.item(0).getNodeValue().equals("org.jboss.logging"));
        assertTrue("module.xml should contain module element with atrribute name=\"org.jboss.logmanager\"",
                nl.item(1).getNodeValue().equals("org.jboss.logmanager"));
    } else {
        assertTrue(
                "module.xml shouldn't contain any dependencies but it has " + nl.getLength() + " dependencies",
                nl.getLength() == 0);
    }

    XPathExpression exportDependenciesNameAttrExpr = xpath.compile("/module/dependencies/module/@export");
    nl = (NodeList) exportDependenciesNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkDependencies) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain module element with atrribute export=true",
                nl.item(0).getNodeValue().equals("true"));
    } else {
        assertTrue(
                "module.xml shouldn't contain any dependencies but it has " + nl.getLength() + " dependencies",
                nl.getLength() == 0);
    }

    // check main class
    XPathExpression mainClassNameAttrExpr = xpath.compile("/module/main-class/@name");
    nl = (NodeList) mainClassNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkMainClass) {
        assertTrue("module.xml should contain main-class element", nl.getLength() == 1);
        assertTrue("module.xml should contain main-class element with atrribute name=\"org.jboss.Test\"",
                nl.item(0).getNodeValue().equals("org.jboss.Test"));
    } else {
        assertTrue("module.xml shouldn't contain main-class element", nl.getLength() == 0);
    }

}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Processes the Topics in the BuildDatabase and builds up the images found within the topics XML. If the image reference is
 * blank or invalid it is replaced by the fail penguin image.
 *
 * @param buildData Information and data structures for the build.
 *//*from   www .j  a  va2  s  .  co  m*/
@SuppressWarnings("unchecked")
private void processImageLocations(final BuildData buildData) {
    final List<Integer> topicIds = buildData.getBuildDatabase().getTopicIds();
    for (final Integer topicId : topicIds) {
        final ITopicNode topicNode = buildData.getBuildDatabase().getTopicNodesForTopicID(topicId).get(0);
        final BaseTopicWrapper<?> topic = topicNode.getTopic();

        if (log.isDebugEnabled())
            log.debug("\tProcessing SpecTopic " + topicNode.getId()
                    + (topicNode.getRevision() != null ? (", " + "Revision " + topicNode.getRevision()) : ""));

        /*
         * Images have to be in the image folder in Publican. Here we loop through all the imagedata elements and fix up any
         * reference to an image that is not in the images folder.
         */
        final List<Node> images = XMLUtilities.getChildNodes(topicNode.getXMLDocument(), "imagedata",
                "inlinegraphic");

        for (final Node imageNode : images) {
            final NamedNodeMap attributes = imageNode.getAttributes();
            if (attributes != null) {
                final Node fileRefAttribute = attributes.getNamedItem("fileref");

                if (fileRefAttribute != null && (fileRefAttribute.getNodeValue() == null
                        || fileRefAttribute.getNodeValue().isEmpty())) {
                    fileRefAttribute.setNodeValue("images/" + BuilderConstants.FAILPENGUIN_PNG_NAME + ".jpg");
                    buildData.getImageLocations()
                            .add(new TopicImageData(topic, fileRefAttribute.getNodeValue()));
                } else if (fileRefAttribute != null && fileRefAttribute.getNodeValue() != null) {
                    final String fileRefValue = fileRefAttribute.getNodeValue();
                    if (BuilderConstants.IMAGE_FILE_REF_PATTERN.matcher(fileRefValue).matches()) {
                        if (fileRefValue.startsWith("./images/")) {
                            fileRefAttribute.setNodeValue(fileRefValue.substring(2));
                        } else if (!fileRefValue.startsWith("images/")) {
                            fileRefAttribute.setNodeValue("images/" + fileRefValue);
                        }

                        buildData.getImageLocations()
                                .add(new TopicImageData(topic, fileRefAttribute.getNodeValue()));
                    } else if (!BuilderConstants.COMMON_CONTENT_FILE_REF_PATTERN.matcher(fileRefValue)
                            .matches()) {
                        // The file isn't common content or a pressgang image so mark it as a missing image.
                        fileRefAttribute
                                .setNodeValue("images/" + BuilderConstants.FAILPENGUIN_PNG_NAME + ".jpg");
                        buildData.getImageLocations()
                                .add(new TopicImageData(topic, fileRefAttribute.getNodeValue()));
                    }
                }
            }
        }
    }
}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Returns the value of the specified node attribute or null if it is missing.
 * <p>//from  w ww .  j  a  va 2 s  .co  m
 * 
 * @param name
 *          (local) name of attribute
 * @param node
 *          current element
 * @return the textual contents of the attribute or null
 */
public static String getAttrValue(final String name, final Node node) {
    String value = null;
    final NamedNodeMap atts = node.getAttributes();

    if (atts != null) {
        final Attr attribute = (Attr) atts.getNamedItem(name);

        if (attribute != null) {
            value = attribute.getValue();
        }
    }
    return value;
}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Returns the value of the specified node attribute.
 * <p>//w  w w.  j ava  2  s.  c o  m
 * 
 * @param name
 *          (local) name of attribute
 * @param node
 *          current element
 * @return the textual contents of the attribute
 * @throws XMLParsingException
 *           if specified attribute is missing
 */
public static String getRequiredAttrValue(final String name, final Node node) throws XMLParsingException {
    String value = null;
    final NamedNodeMap atts = node.getAttributes();

    if (atts != null) {
        final Attr attribute = (Attr) atts.getNamedItem(name);

        if (attribute != null) {
            value = attribute.getValue();
        }
    }
    if (value == null) {
        throw new XMLParsingException(
                "Required attribute '" + name + "' of element '" + node.getNodeName() + "' is missing.");
    }
    return value;
}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Returns the attribute value of the given node.
 *///from  w  w w.  java 2s  .  c  o  m
public static String getAttrValue(final Node node, final String attrName) {
    // get attr name and dtype
    final NamedNodeMap atts = node.getAttributes();

    if (atts == null) {
        return null;
    }

    final Attr a = (Attr) atts.getNamedItem(attrName);

    if (a != null) {
        return a.getValue();
    }

    return null;
}

From source file:org.kepler.moml.KeplerMetadataExtractor.java

/** Get the metadata from an input stream optionally printing output if a parsing error occurs.
 *  @param actorStream the input stream/* w  w w  .  ja  v a2 s  .c o m*/
 *  @param printError if true, print a stack trace and error message if a parsing error occurs.
 */
public static KeplerActorMetadata extractActorMetadata(InputStream actorStream, boolean printError)
        throws Exception {
    //if (isTracing)
    //log.trace("ActorCacheObject(" + actorStream.getClass().getName()
    //+ ")");

    KeplerActorMetadata kam = new KeplerActorMetadata();

    ByteArrayOutputStream byteout;
    try {
        // Copy 1024 bytes from actorStream to byteout
        byteout = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int numread = actorStream.read(b, 0, 1024);
        while (numread != -1) {
            byteout.write(b, 0, numread);
            numread = actorStream.read(b, 0, 1024);
        }
        kam.setActorString(byteout.toString());

        // need to get actor name and id from the string
        // thus build a DOM representation
        String nameStr = null;
        try {
            //if (isTracing) log.trace(kam.getActorString());
            StringReader strR = new StringReader(kam.getActorString());

            InputSource xmlIn = new InputSource(strR);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver(new EntityResolver() {
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    if (MOML_PUBLIC_ID_1.equals(publicId)) {
                        return new InputSource(MoMLParser.class.getResourceAsStream("MoML_1.dtd"));
                    } else {
                        return null;
                    }
                }
            });

            // TODO 
            // this causes http://bugzilla.ecoinformatics.org/show_bug.cgi?id=4671
            // when File => Save Archive w/ wf w/ actor w/ < in the name:
            Document doc = builder.parse(xmlIn);
            //if (isTracing) log.trace(doc.toString());

            Element rootNode = doc.getDocumentElement();
            kam.setRootName(rootNode.getNodeName());

            // Get the value of the name attribute of the root node
            NamedNodeMap nnm = rootNode.getAttributes();
            Node namenode = nnm.getNamedItem("name");
            nameStr = namenode.getNodeValue();
            kam.setName(nameStr);

            boolean emptyKeplerDocumentation = true;
            boolean foundKeplerDocumentation = false;
            boolean foundUserLevelDocumentation = false;
            boolean foundAuthor = false;

            // Cycle through the children of the root node
            NodeList probNodes = rootNode.getChildNodes();
            for (int i = 0; i < probNodes.getLength(); i++) {
                Node child = probNodes.item(i);

                if (child.hasAttributes()) {

                    NamedNodeMap childAttrs = child.getAttributes();
                    Node idNode = childAttrs.getNamedItem("name");
                    if (idNode != null) {

                        // the entityId
                        String nameval = idNode.getNodeValue();
                        if (nameval.equals(NamedObjId.NAME)) {
                            Node idNode1 = childAttrs.getNamedItem("value");
                            String idval = idNode1.getNodeValue();
                            kam.setLsid(new KeplerLSID(idval));
                        }

                        // the class name
                        if (nameval.equals("class")) {
                            Node idNode3 = childAttrs.getNamedItem("value");
                            String classname = idNode3.getNodeValue();
                            kam.setClassName(classname);
                        }

                        // the semantic types
                        if (nameval.startsWith("semanticType")) {
                            Node idNode2 = childAttrs.getNamedItem("value");
                            String semtype = idNode2.getNodeValue();
                            kam.addSemanticType(semtype);
                        }

                        // userLevelDocumentation must be contained in KeplerDocumentation 
                        if (nameval.equals("userLevelDocumentation")) {
                            log.warn(nameStr
                                    + " userLevelDocumentation property should be contained in a KeplerDocumentation property.");
                        } else if (nameval.equals("KeplerDocumentation")) {

                            foundKeplerDocumentation = true;

                            final NodeList keplerDocNodeList = child.getChildNodes();
                            if (keplerDocNodeList.getLength() > 0) {

                                emptyKeplerDocumentation = false;

                                for (int j = 0; j < keplerDocNodeList.getLength(); j++) {
                                    final Node docChildNode = keplerDocNodeList.item(j);
                                    final NamedNodeMap docChildNamedNodeMap = docChildNode.getAttributes();

                                    if (docChildNamedNodeMap != null) {

                                        final Node docChildChildName = docChildNamedNodeMap
                                                .getNamedItem("name");

                                        if (docChildChildName != null) {

                                            final String docChildChildNameValue = docChildChildName
                                                    .getNodeValue();

                                            if (docChildChildNameValue.equals("userLevelDocumentation")) {

                                                foundUserLevelDocumentation = true;
                                                final String text = docChildNode.getTextContent();
                                                if (text == null || text.trim().isEmpty()) {
                                                    log.debug(nameStr + " has empty userLevelDocumentation.");
                                                }

                                            } else if (docChildChildNameValue.equals("author")) {
                                                foundAuthor = true;

                                                final String text = docChildNode.getTextContent();
                                                if (text == null || text.trim().isEmpty()) {
                                                    log.debug(nameStr + " has empty author documentation.");
                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (nameval.startsWith(COPY_ATTRIBUTE_PREFIX)) {
                            String value = childAttrs.getNamedItem("value").getNodeValue();
                            kam.addAttribute(nameval, value);
                        }
                    }
                }
            }

            // check documentation
            if (!foundKeplerDocumentation) {
                log.debug(nameStr + " is missing KeplerDocumentation.");
            } else if (emptyKeplerDocumentation) {
                log.debug(nameStr + " KeplerDocumentation is empty.");
            } else if (!foundUserLevelDocumentation && !foundAuthor) {
                log.debug(nameStr + " is missing userLevelDocumentation and author documentation.");
            } else if (!foundUserLevelDocumentation) {
                log.debug(nameStr + " is missing userLevelDocumentation.");
            } else if (!foundAuthor) {
                log.debug(nameStr + " is missing author documentation.");
            }

        } catch (Exception e) {
            if (printError) {
                e.printStackTrace();
                System.out.println("Error parsing Actor KAR DOM \""
                        + ((nameStr == null) ? byteout.toString().substring(0, 300) + "..." : nameStr) + "\": "
                        + e.getMessage());
            }
            kam = null;
        } finally {
            actorStream.close();
            byteout.close();
        }
    } catch (Exception e) {
        kam = null;
        throw new Exception("Error extracting Actor Metadata: " + e.getMessage());
    }

    return kam;
}

From source file:org.kepler.objectmanager.cache.ActorCacheObject.java

/**
 * deserialize this class//from ww  w.  ja  v  a2 s. co  m
 * 
 *@param in
 *            Description of the Parameter
 *@exception IOException
 *                Description of the Exception
 *@exception ClassNotFoundException
 *                Description of the Exception
 */
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    if (isDebugging)
        log.debug("readExternal(" + in.getClass().getName() + ")");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    int numread = in.read(b, 0, 1024);
    while (numread != -1) {
        bos.write(b, 0, numread);
        numread = in.read(b, 0, 1024);
    }
    bos.flush();
    _actorString = bos.toString();
    try {
        StringReader strR = new StringReader(_actorString);
        InputSource xmlIn = new InputSource(strR);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (MOML_PUBLIC_ID_1.equals(publicId)) {
                    return new InputSource(MoMLParser.class.getResourceAsStream("MoML_1.dtd"));
                } else {
                    return null;
                }
            }
        });
        Document doc = builder.parse(xmlIn);
        Node rootNode = doc.getDocumentElement();
        _rootname = rootNode.getNodeName();
        NamedNodeMap nnm = rootNode.getAttributes();
        Node namenode = nnm.getNamedItem("name");
        String nameStr = namenode.getNodeValue();
        this._name = nameStr;
        NodeList probNodes = rootNode.getChildNodes();
        for (int i = 0; i < probNodes.getLength(); i++) {
            Node child = probNodes.item(i);
            if (child.hasAttributes()) {
                NamedNodeMap childAttrs = child.getAttributes();
                Node idNode = childAttrs.getNamedItem("name");
                if (idNode != null) {
                    String nameval = idNode.getNodeValue();
                    if (nameval.equals(NamedObjId.NAME)) {
                        Node idNode1 = childAttrs.getNamedItem("value");
                        String idval = idNode1.getNodeValue();
                        this._lsid = new KeplerLSID(idval);
                    }
                    if (nameval.equals("class")) {
                        Node idNode3 = childAttrs.getNamedItem("value");
                        String classname = idNode3.getNodeValue();
                        this._className = classname;
                    }
                    if (nameval.startsWith("semanticType")) {
                        Node idNode2 = childAttrs.getNamedItem("value");
                        String semtype = idNode2.getNodeValue();
                        _semanticTypes.add(semtype);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException("Error in ActorCacheObject(ReadExternal): " + e.getMessage());
    }
}