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.drools.workbench.jcr2vfsmigration.xml.format.AbstractXmlAssetFormat.java

private XmlGenericAttributes parseGenericNodeContent(Node assetNode) {
    // Null-ness already checked before
    NamedNodeMap assetAttribs = assetNode.getAttributes();

    Node commentNode = assetNode.getFirstChild();
    String checkinComment = parseCdataSection(commentNode); // Need the CData parent-node

    return new XmlGenericAttributes(unEscapeXml(assetAttribs.getNamedItem(ASSET_NAME).getNodeValue()),
            assetAttribs.getNamedItem(ASSET_TYPE).getNodeValue(),
            assetAttribs.getNamedItem(ASSET_LAST_CONTRIBUTOR).getNodeValue(), checkinComment,
            new Date(Long.parseLong(assetAttribs.getNamedItem(ASSET_LAST_MODIFIED).getNodeValue(), 10)));
}

From source file:org.drools.workbench.jcr2vfsmigration.xml.format.DataModelAssetFormat.java

protected DataModelAsset doParse(String name, String format, String lastContributor, String checkinComment,
        Date lastModified, Node assetNode) {

    DataModelAsset dataModel = new DataModelAsset(name, format, lastContributor, checkinComment, lastModified);

    NodeList modelNodeList = assetNode.getChildNodes();
    for (int i = 0; i < modelNodeList.getLength(); i++) {
        Node objNode = modelNodeList.item(i);
        if (MODEL_OBJ.equalsIgnoreCase(objNode.getNodeName())) {
            NamedNodeMap objAttribs = objNode.getAttributes();
            String objName = objAttribs.getNamedItem(MODEL_OBJ_NAME).getNodeValue();
            String objSuperType = objAttribs.getNamedItem(MODEL_OBJ_SUPERTYPE).getNodeValue();

            DataModelAsset.DataModelObject obj = dataModel.addDataModelObject(objName, objSuperType);

            NodeList objNodeList = objNode.getChildNodes();
            for (int j = 0; j < objNodeList.getLength(); j++) {
                Node objChildNode = objNodeList.item(j);
                NamedNodeMap childNodeAttribs = objChildNode.getAttributes();

                if (MODEL_OBJ_PROP.equalsIgnoreCase(objChildNode.getNodeName())) {
                    obj.addObjectProperty(childNodeAttribs.getNamedItem(MODEL_OBJ_PROP_NAME).getNodeValue(),
                            childNodeAttribs.getNamedItem(MODEL_OBJ_PROP_TYPE).getNodeValue());

                } else if (MODEL_OBJ_ANN.equalsIgnoreCase(objChildNode.getNodeName())) {
                    obj.addObjectAnnotation(childNodeAttribs.getNamedItem(MODEL_OBJ_ANN_NAME).getNodeValue(),
                            unEscapeXml(childNodeAttribs.getNamedItem(MODEL_OBJ_ANN_KEY).getNodeValue()),
                            unEscapeXml(childNodeAttribs.getNamedItem(MODEL_OBJ_ANN_VALUE).getNodeValue()));
                }/*w  w  w  .  j a va  2  s.c o m*/
            }
        }
    }
    return dataModel;
}

From source file:org.dspace.content.packager.RoleIngester.java

/**
 * Common code to ingest roles from a Document.
 * // w  w w  .  j av  a 2  s  . c o m
 * @param context
 *          DSpace Context
 * @param parent
 *          the Parent DSpaceObject
 * @param document
 *          the XML Document
 * @throws SQLException
 * @throws AuthorizeException
 * @throws PackageException
 */
static void ingestDocument(Context context, DSpaceObject parent, PackageParameters params, Document document)
        throws SQLException, AuthorizeException, PackageException {
    String myEmail = context.getCurrentUser().getEmail();
    String myNetid = context.getCurrentUser().getNetid();

    // Ingest users (EPersons) first so Groups can use them
    NodeList users = document.getElementsByTagName(RoleDisseminator.EPERSON);
    for (int i = 0; i < users.getLength(); i++) {
        Element user = (Element) users.item(i);
        // int userID = Integer.valueOf(user.getAttribute("ID")); // FIXME
        // no way to set ID!
        NodeList emails = user.getElementsByTagName(RoleDisseminator.EMAIL);
        NodeList netids = user.getElementsByTagName(RoleDisseminator.NETID);
        EPerson eperson;
        EPerson collider;
        String email = null;
        String netid = null;
        String identity;
        if (emails.getLength() > 0) {
            email = emails.item(0).getTextContent();
            if (email.equals(myEmail)) {
                continue; // Cannot operate on my own EPerson!
            }
            identity = email;
            collider = EPerson.findByEmail(context, identity);
            // collider = EPerson.find(context, userID);
        } else if (netids.getLength() > 0) {
            netid = netids.item(0).getTextContent();
            if (netid.equals(myNetid)) {
                continue; // Cannot operate on my own EPerson!
            }
            identity = netid;
            collider = EPerson.findByNetid(context, identity);
        } else {
            throw new PackageException("EPerson has neither email nor netid.");
        }

        if (null != collider)
            if (params.replaceModeEnabled()) // -r -f
            {
                eperson = collider;
            } else if (params.keepExistingModeEnabled()) // -r -k
            {
                log.warn("Existing EPerson {} was not restored from the package.", identity);
                continue;
            } else {
                throw new PackageException("EPerson " + identity + " already exists.");
            }
        else {
            eperson = EPerson.create(context);
            log.info("Created EPerson {}.", identity);
        }

        eperson.setEmail(email);
        eperson.setNetid(netid);

        NodeList data;

        data = user.getElementsByTagName(RoleDisseminator.FIRST_NAME);
        if (data.getLength() > 0) {
            eperson.setFirstName(data.item(0).getTextContent());
        } else {
            eperson.setFirstName(null);
        }

        data = user.getElementsByTagName(RoleDisseminator.LAST_NAME);
        if (data.getLength() > 0) {
            eperson.setLastName(data.item(0).getTextContent());
        } else {
            eperson.setLastName(null);
        }

        data = user.getElementsByTagName(RoleDisseminator.LANGUAGE);
        if (data.getLength() > 0) {
            eperson.setLanguage(data.item(0).getTextContent());
        } else {
            eperson.setLanguage(null);
        }

        data = user.getElementsByTagName(RoleDisseminator.CAN_LOGIN);
        eperson.setCanLogIn(data.getLength() > 0);

        data = user.getElementsByTagName(RoleDisseminator.REQUIRE_CERTIFICATE);
        eperson.setRequireCertificate(data.getLength() > 0);

        data = user.getElementsByTagName(RoleDisseminator.SELF_REGISTERED);
        eperson.setSelfRegistered(data.getLength() > 0);

        data = user.getElementsByTagName(RoleDisseminator.PASSWORD_HASH);
        if (data.getLength() > 0) {
            Node element = data.item(0);
            NamedNodeMap attributes = element.getAttributes();

            Node algorithm = attributes.getNamedItem(RoleDisseminator.PASSWORD_DIGEST);
            String algorithmText;
            if (null != algorithm)
                algorithmText = algorithm.getNodeValue();
            else
                algorithmText = null;

            Node salt = attributes.getNamedItem(RoleDisseminator.PASSWORD_SALT);
            String saltText;
            if (null != salt)
                saltText = salt.getNodeValue();
            else
                saltText = null;

            PasswordHash password;
            try {
                password = new PasswordHash(algorithmText, saltText, element.getTextContent());
            } catch (DecoderException ex) {
                throw new PackageValidationException("Unable to decode hexadecimal password hash or salt", ex);
            }
            eperson.setPasswordHash(password);
        } else {
            eperson.setPasswordHash(null);
        }

        // Actually write Eperson info to DB
        // NOTE: this update() doesn't call a commit(). So, Eperson info
        // may still be rolled back if a subsequent error occurs
        eperson.update();
    }

    // Now ingest the Groups
    NodeList groups = document.getElementsByTagName(RoleDisseminator.GROUP);

    // Create the groups and add their EPerson members
    for (int groupx = 0; groupx < groups.getLength(); groupx++) {
        Element group = (Element) groups.item(groupx);
        String name = group.getAttribute(RoleDisseminator.NAME);

        try {
            //Translate Group name back to internal ID format (e.g. COLLECTION_<ID>_ADMIN)
            // TODO: is this necessary? can we leave it in format with Handle in place of <ID>?
            // For now, this is necessary, because we don't want to accidentally
            // create a new group COLLECTION_hdl:123/34_ADMIN, which is equivalent
            // to an existing COLLECTION_45_ADMIN group
            name = PackageUtils.translateGroupNameForImport(context, name);
        } catch (PackageException pe) {
            // If an error is thrown, then this Group corresponds to a
            // Community or Collection that doesn't currently exist in the
            // system.  So, log a warning & skip it for now.
            log.warn("Skipping group named '" + name
                    + "' as it seems to correspond to a Community or Collection that does not exist in the system.  "
                    + "If you are performing an AIP restore, you can ignore this warning as the Community/Collection AIP will likely create this group once it is processed.");
            continue;
        }

        Group groupObj = null; // The group to restore
        Group collider = Group.findByName(context, name); // Existing group?
        if (null != collider) { // Group already exists, so empty it
            if (params.replaceModeEnabled()) // -r -f
            {
                for (Group member : collider.getMemberGroups()) {
                    collider.removeMember(member);
                }
                for (EPerson member : collider.getMembers()) {
                    // Remove all group members *EXCEPT* we don't ever want
                    // to remove the current user from the list of Administrators
                    // (otherwise remainder of ingest will fail)
                    if (!(collider.equals(Group.find(context, 1)) && member.equals(context.getCurrentUser()))) {
                        collider.removeMember(member);
                    }
                }
                log.info("Existing Group {} was cleared. Its members will be replaced.", name);
                groupObj = collider;
            } else if (params.keepExistingModeEnabled()) // -r -k
            {
                log.warn("Existing Group {} was not replaced from the package.", name);
                continue;
            } else {
                throw new PackageException("Group " + name + " already exists");
            }
        } else { // No such group exists  -- so, we'll need to create it!

            // First Check if this is a "typed" group (i.e. Community or Collection associated Group)
            // If so, we'll create it via the Community or Collection
            String type = group.getAttribute(RoleDisseminator.TYPE);
            if (type != null && !type.isEmpty() && parent != null) {
                //What type of dspace object is this group associated with
                if (parent.getType() == Constants.COLLECTION) {
                    Collection collection = (Collection) parent;

                    // Create this Collection-associated group, based on its group type
                    if (type.equals(RoleDisseminator.GROUP_TYPE_ADMIN)) {
                        groupObj = collection.createAdministrators();
                    } else if (type.equals(RoleDisseminator.GROUP_TYPE_SUBMIT)) {
                        groupObj = collection.createSubmitters();
                    } else if (type.equals(RoleDisseminator.GROUP_TYPE_WORKFLOW_STEP_1)) {
                        groupObj = collection.createWorkflowGroup(1);
                    } else if (type.equals(RoleDisseminator.GROUP_TYPE_WORKFLOW_STEP_2)) {
                        groupObj = collection.createWorkflowGroup(2);
                    } else if (type.equals(RoleDisseminator.GROUP_TYPE_WORKFLOW_STEP_3)) {
                        groupObj = collection.createWorkflowGroup(3);
                    }
                } else if (parent.getType() == Constants.COMMUNITY) {
                    Community community = (Community) parent;

                    // Create this Community-associated group, based on its group type
                    if (type.equals(RoleDisseminator.GROUP_TYPE_ADMIN)) {
                        groupObj = community.createAdministrators();
                    }
                }
                //Ignore all other dspace object types
            }

            //If group not yet created, create it with the given name
            if (groupObj == null) {
                groupObj = Group.create(context);
            }

            // Always set the name:  parent.createBlop() is guessing
            groupObj.setName(name);

            log.info("Created Group {}.", groupObj.getName());
        }

        // Add EPeople to newly created Group
        NodeList members = group.getElementsByTagName(RoleDisseminator.MEMBER);
        for (int memberx = 0; memberx < members.getLength(); memberx++) {
            Element member = (Element) members.item(memberx);
            String memberName = member.getAttribute(RoleDisseminator.NAME);
            EPerson memberEPerson = EPerson.findByEmail(context, memberName);
            if (null != memberEPerson)
                groupObj.addMember(memberEPerson);
            else
                throw new PackageValidationException(
                        "EPerson " + memberName + " not found, not added to " + name);
        }

        // Actually write Group info to DB
        // NOTE: this update() doesn't call a commit(). So, Group info
        // may still be rolled back if a subsequent error occurs
        groupObj.update();

    }

    // Go back and add Group members, now that all groups exist
    for (int groupx = 0; groupx < groups.getLength(); groupx++) {
        Element group = (Element) groups.item(groupx);
        String name = group.getAttribute(RoleDisseminator.NAME);
        try {
            // Translate Group name back to internal ID format (e.g. COLLECTION_<ID>_ADMIN)
            name = PackageUtils.translateGroupNameForImport(context, name);
        } catch (PackageException pe) {
            // If an error is thrown, then this Group corresponds to a
            // Community or Collection that doesn't currently exist in the
            // system.  So,skip it for now.
            // (NOTE: We already logged a warning about this group earlier as
            //  this is the second time we are looping through all groups)
            continue;
        }

        // Find previously created group
        Group groupObj = Group.findByName(context, name);
        NodeList members = group.getElementsByTagName(RoleDisseminator.MEMBER_GROUP);
        for (int memberx = 0; memberx < members.getLength(); memberx++) {
            Element member = (Element) members.item(memberx);
            String memberName = member.getAttribute(RoleDisseminator.NAME);
            //Translate Group name back to internal ID format (e.g. COLLECTION_<ID>_ADMIN)
            memberName = PackageUtils.translateGroupNameForImport(context, memberName);
            // Find previously created group
            Group memberGroup = Group.findByName(context, memberName);
            groupObj.addMember(memberGroup);
        }
        // Actually update Group info in DB
        // NOTE: Group info may still be rolled back if a subsequent error occurs
        groupObj.update();
    }
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.XSDUtils.java

/**
 * get the real namespace of the type//from  w  w w  .j a  va 2s .c  om
 * 
 * @param annotations
 * @return null if this is a type inside wsdl, not from TL outside
 */
private String getSourceNamespaceAnnotations(EList<XSDAnnotation> annotations) {
    String orginalNamespace = null;
    if (annotations == null || annotations.size() == 0) {
        return orginalNamespace;
    }
    for (XSDAnnotation at : annotations) {
        EList<Element> list = at.getApplicationInformation();
        for (Element e : list) {
            String nodeName = e.getLocalName();
            // String content = e.getTextContent();
            // if (StringUtils.isEmpty(nodeName) == true) {
            // continue;
            // }
            if (APP_NODE_NAME.equalsIgnoreCase(nodeName) == false) {
                continue;
            }
            NodeList appChildren = e.getChildNodes();
            int len = appChildren.getLength();
            for (int i = 0; i < len; i++) {
                Node appChild = appChildren.item(i);
                if (TL_SOURCE_NODE_NAME.equalsIgnoreCase(appChild.getNodeName()) == false) {
                    continue;
                }
                NamedNodeMap tlSourceAttrs = appChild.getAttributes();
                Node tlNameNode = tlSourceAttrs.getNamedItem(TL_ARRT_NAME);
                Node typeNSNode = tlSourceAttrs.getNamedItem(TL_NS_ATTR_NAME);
                String tlName = tlNameNode.getNodeValue();
                String typeNS = typeNSNode.getNodeValue();
                if (typeNSNode == null || tlNameNode == null) {
                    return null;
                }
                if (SOALogger.DEBUG)
                    logger.debug(tlName + "\t" + typeNS);
                return typeNS;
            }
        }
    }
    return orginalNamespace;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.asset.GetAndUpdateXmlTests.java

private String getNodeAttribute(NodeList nodes, String nodeName, String attr) {
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeName().equals(nodeName)) {
            NamedNodeMap attributes = node.getAttributes();
            return attributes.getNamedItem(attr).getNodeValue();
        }/*from  w  w  w  .  j  a  v a2  s. c  o m*/
    }
    return null;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.asset.UsageCaseXmlTests.java

@Test
public void retrieveUsageCase() throws IOException, ParseException, ParserConfigurationException, SAXException,
        XPathExpressionException {
    assertTrue("The asset with the highest version couldn't be found", bestAsset != null);

    // Once the best asset is determined then the full asset is retrieved
    NamedNodeMap attributes = bestAsset.getAttributes();
    assetUrl = attributes.getNamedItem("rdf:about").getNodeValue();
    String asset = getAssetAsString();
    assetUrl = null; // This is required so that the asset is not deleted
    retrieveArtifact(asset);//from w  w w .  ja v  a  2 s  . c  o m
}

From source file:org.eclipse.lyo.testsuite.oslcv2.asset.UsageCaseXmlTests.java

private void retrieveArtifact(String asset)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    Document document = OSLCUtils.createXMLDocFromResponseBody(asset);
    String path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact/oslc_asset:content";
    XPath xpath = OSLCUtils.getXPath();
    Node content = (Node) xpath.evaluate(path, document, XPathConstants.NODE);
    assertTrue("Could not find the artifact", content != null);

    NamedNodeMap attributes = content.getAttributes();
    String artifactUrl = attributes.getNamedItem("rdf:resource").getNodeValue();
    assertTrue("No artifact could be found in the asset", artifactUrl != null);

    HttpResponse resp = OSLCUtils.getDataFromUrl(artifactUrl, creds, acceptType, contentType, headers);
    EntityUtils.consume(resp.getEntity());
    assertTrue("Expected " + HttpStatus.SC_OK + ", received " + resp.getStatusLine().getStatusCode(),
            resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK);
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {/*w  w w .  ja v  a  2  s  . c om*/

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println();
    }
    return fileName.toString();
}

From source file:org.eclipse.smila.search.lucene.messages.indexstructure.DParameterCodec.java

/**
 * @param element -/* w  w w  . j av a2s . c om*/
 * @return DParameter
 */
public static DParameter decode(Element element) {
    final Log log = LogFactory.getLog(DParameterCodec.class);
    String paramName = null;
    String paramValue = null;
    // decode Term
    final NodeList nl = element.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        /*
         * if (log.isInfoEnabled()) { log.info("DParameterCodec: node " + nl.item(i)); }
         */
        if ("Name".equals(nl.item(i).getLocalName())) {
            paramName = ((Text) nl.item(i).getFirstChild()).getData().trim();
        }

        if ("Value".equals(nl.item(i).getLocalName())) {
            final NamedNodeMap attrs = nl.item(i).getAttributes();
            final Node nilItem = (attrs == null) ? null : attrs.getNamedItem("xsi:nil");
            final String xsiNil = (nilItem == null) ? null : nilItem.getNodeValue();
            final boolean isNil = (xsiNil != null)
                    && (xsiNil.toLowerCase().equals("true") || xsiNil.equals("1"));
            if (isNil) {
                paramValue = null;
            } else {
                paramValue = ((Text) nl.item(i).getFirstChild()).getData().trim();
            }
        }

    }

    final DParameter dParameter = new DParameter(paramName, paramValue);
    return dParameter;
}

From source file:org.eclipse.sw360.licenseinfo.parsers.AbstractCLIParser.java

protected Optional<Node> findNamedAttribute(Node node, String name) {
    NamedNodeMap childNodes = node.getAttributes();
    return Optional.ofNullable(childNodes.getNamedItem(name));
}