Example usage for org.w3c.dom Element getNodeName

List of usage examples for org.w3c.dom Element getNodeName

Introduction

In this page you can find the example usage for org.w3c.dom Element getNodeName.

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:com.moviejukebox.reader.MovieNFOReader.java

/**
 * Parse Actors from the XML NFO file.// w  w w  .java2s .co m
 *
 * @param nlElements
 * @param movie
 */
private static void parseActors(NodeList nlElements, Movie movie) {
    // check if we have a node
    if (nlElements == null || nlElements.getLength() == 0) {
        return;
    }

    // check if we should override
    boolean overrideActors = OverrideTools.checkOverwriteActors(movie, NFO_PLUGIN_ID);
    boolean overridePeopleActors = OverrideTools.checkOverwritePeopleActors(movie, NFO_PLUGIN_ID);
    if (!overrideActors && !overridePeopleActors) {
        // nothing to do if nothing should be overridden
        return;
    }

    // count for already set actors
    int count = 0;
    // flag to indicate if cast must be cleared
    boolean clearCast = Boolean.TRUE;
    boolean clearPeopleCast = Boolean.TRUE;

    for (int actorLoop = 0; actorLoop < nlElements.getLength(); actorLoop++) {
        // Get all the name/role/thumb nodes
        Node nActors = nlElements.item(actorLoop);
        NodeList nlCast = nActors.getChildNodes();
        Node nElement;

        String aName = Movie.UNKNOWN;
        String aRole = Movie.UNKNOWN;
        String aThumb = Movie.UNKNOWN;
        Boolean firstActor = Boolean.TRUE;

        if (nlCast.getLength() > 1) {
            for (int looper = 0; looper < nlCast.getLength(); looper++) {
                nElement = nlCast.item(looper);
                if (nElement.getNodeType() == Node.ELEMENT_NODE) {
                    Element eCast = (Element) nElement;
                    if ("name".equalsIgnoreCase(eCast.getNodeName())) {
                        if (firstActor) {
                            firstActor = Boolean.FALSE;
                        } else {

                            if (overrideActors) {
                                // clear cast if not already done
                                if (clearCast) {
                                    movie.clearCast();
                                    clearCast = Boolean.FALSE;
                                }
                                // add actor
                                movie.addActor(aName, NFO_PLUGIN_ID);
                            }

                            if (overridePeopleActors && (count < MAX_COUNT_ACTOR)) {
                                // clear people cast if not already done
                                if (clearPeopleCast) {
                                    movie.clearPeopleCast();
                                    clearPeopleCast = Boolean.FALSE;
                                }
                                // add actor
                                if (movie.addActor(Movie.UNKNOWN, aName, aRole, aThumb, Movie.UNKNOWN,
                                        NFO_PLUGIN_ID)) {
                                    count++;
                                }
                            }
                        }
                        aName = eCast.getTextContent();
                        aRole = Movie.UNKNOWN;
                        aThumb = Movie.UNKNOWN;
                    } else if ("role".equalsIgnoreCase(eCast.getNodeName())
                            && StringUtils.isNotBlank(eCast.getTextContent())) {
                        aRole = eCast.getTextContent();
                    } else if ("thumb".equalsIgnoreCase(eCast.getNodeName())
                            && StringUtils.isNotBlank(eCast.getTextContent())) {
                        // thumb will be skipped if there's nothing in there
                        aThumb = eCast.getTextContent();
                    }
                    // There's a case where there might be a different node here that isn't name, role or thumb, but that will be ignored
                }
            }
        } else {
            // This looks like a Mede8er node in the "<actor>Actor Name</actor>" format, so just get the text element
            aName = nActors.getTextContent();
        }

        if (overrideActors) {
            // clear cast if not already done
            if (clearCast) {
                movie.clearCast();
                clearCast = Boolean.FALSE;
            }
            // add actor
            movie.addActor(aName, NFO_PLUGIN_ID);
        }

        if (overridePeopleActors && (count < MAX_COUNT_ACTOR)) {
            // clear people cast if not already done
            if (clearPeopleCast) {
                movie.clearPeopleCast();
                clearPeopleCast = Boolean.FALSE;
            }
            // add actor
            if (movie.addActor(Movie.UNKNOWN, aName, aRole, aThumb, Movie.UNKNOWN, NFO_PLUGIN_ID)) {
                count++;
            }
        }
    }
}

From source file:importer.handler.post.stages.Discriminator.java

boolean isSibling(Element elem) {
    String name = elem.getNodeName();
    return siblings.containsKey(name);
}

From source file:importer.handler.post.stages.Discriminator.java

boolean isCorrectedElem(Element elem) {
    String eName = elem.getNodeName();
    return eName.equals(reg) || eName.equals(corr) || eName.equals(expan);
}

From source file:fi.csc.kapaVirtaAS.WSDLManipulator.java

public void generateVirtaKapaWSDL() throws Exception {
    // Fetch current WSDL-file
    File inputFile = new File("opiskelijatiedot.wsdl");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(inputFile);
    doc.setXmlVersion("1.0");
    doc.getDocumentElement().normalize();

    // Manipulate WSDL to meet the requirements of xroad

    // Root element <wsdl:definitions> attribute manipulations
    Element root = doc.getDocumentElement();
    root.setAttribute("xmlns:" + conf.getXroadSchemaPrefixForWSDL(), conf.getXroadSchema());
    root.setAttribute("xmlns:" + conf.getXroadIdSchemaPrefixForWSDL(), conf.getXroadIdSchema());

    root = replaceAttribute(root, "xmlns:tns", conf.getAdapterServiceSchema());
    root = replaceAttribute(root, "targetNamespace", conf.getAdapterServiceSchema());

    // Schema elements <xs:schema> attribute manipulations
    NodeList schemas = root.getElementsByTagName("xs:schema");

    for (int i = 0; i < schemas.getLength(); ++i) {
        Node schema = schemas.item(i);
        if (schema != null) {
            NamedNodeMap schemaAttributes = schema.getAttributes();
            if (schemaAttributes != null && schemaAttributes.getNamedItem("xmlns:virtaluku") != null) {
                schemaAttributes.getNamedItem("xmlns:virtaluku").setTextContent(conf.getAdapterServiceSchema());

                if (schemaAttributes != null && schemaAttributes.getNamedItem("targetNamespace") != null) {
                    schemaAttributes.getNamedItem("targetNamespace")
                            .setTextContent(conf.getAdapterServiceSchema());
                }/*from ww w . j a v  a  2  s  .  co m*/

                Element el = (Element) schema.appendChild(doc.createElement("xs:import"));
                el.setAttribute("id", conf.getXroadSchemaPrefixForWSDL());
                el.setAttribute("namespace", conf.getXroadSchema());
                el.setAttribute("schemaLocation", conf.getXroadSchema());

                // Remove Request part from xs:element -elements
                NodeList elementsInSchema = schema.getChildNodes();
                for (int j = 0; j < elementsInSchema.getLength(); ++j) {
                    Element el1 = (Element) elementsInSchema.item(j);
                    if (el1.getNodeName() == "xs:element") {
                        replaceAttribute(el1, "name",
                                StringUtils.substringBefore(el1.getAttribute("name"), "Request"));
                    }
                }
            }

        }
    }

    // Append xroad request headers
    Element xroadReqHeadersElement = doc.createElement("wsdl:message");
    xroadReqHeadersElement.setAttribute("name", "requestheader");

    for (String xroadHeader : conf.getXroadHeaders()) {
        Element reqHeader = doc.createElement("wsdl:part");
        reqHeader.setAttribute("name", xroadHeader);
        reqHeader.setAttribute("element", conf.getXroadSchemaPrefixForWSDL() + ":" + xroadHeader);
        xroadReqHeadersElement.appendChild(reqHeader);
    }

    root.appendChild(xroadReqHeadersElement);

    NodeList childrenList = root.getChildNodes();
    for (int i = 0; i < childrenList.getLength(); ++i) {

        if (childrenList.item(i).getNodeName().contains(":binding")) {
            NodeList binding = childrenList.item(i).getChildNodes();
            for (int j = 0; j < binding.getLength(); ++j) {
                if (binding.item(j).getNodeName().contains(":operation")) {
                    Element el1 = (Element) binding.item(j)
                            .appendChild(doc.createElement(conf.getXroadIdSchemaPrefixForWSDL() + ":version"));
                    el1.setTextContent(conf.getVirtaVersionForXRoad());

                    for (Node child = binding.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {

                        // Append xroad wsdl:binding operation headers
                        if (child.getNodeName().contains(":input") || child.getNodeName().contains(":output")) {
                            Element el = (Element) child;
                            for (String xroadHeader : conf.getXroadHeaders()) {
                                el.appendChild(soapHeader(doc.createElement("soap:header"), "tns:requestheader",
                                        xroadHeader, "literal"));
                            }
                        }

                        if (child.getNodeName().contains(":input")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "name",
                                    StringUtils.substringBefore(el.getAttribute("name"), "Request"));
                        }
                    }
                }
            }
            // Remove Request from wsdl:message > wsdl:part element so that can see element
        } else if (childrenList.item(i).getNodeName().contains(":message") && childrenList.item(i)
                .getAttributes().getNamedItem("name").getNodeValue().contains("Request")) {
            Element part = (Element) childrenList.item(i).getFirstChild().getNextSibling();
            replaceAttribute(part, "element",
                    StringUtils.substringBefore(part.getAttribute("element"), "Request"));
        }

        // Change wsdl input names to meet XRoad standard
        if (childrenList.item(i).getNodeName().contains(":portType")) {
            NodeList binding = childrenList.item(i).getChildNodes();
            for (int j = 0; j < binding.getLength(); ++j) {
                if (binding.item(j).getNodeName().contains(":operation")) {
                    for (Node child = binding.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeName().contains(":input")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "name",
                                    StringUtils.substringBefore(el.getAttribute("name"), "Request"));
                        }
                    }
                }
            }
        }

        // Append kapaVirtaAS service address
        if (childrenList.item(i).getNodeName().contains(":service")) {
            NodeList service = childrenList.item(i).getChildNodes();
            for (int j = 0; j < service.getLength(); ++j) {
                if (service.item(j).getNodeName().contains(":port")) {
                    for (Node child = service.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeName().contains(":address")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "location", conf.getAdapterServiceSOAPURL());
                        }
                    }
                }
            }
        }
    }

    // Write manipulated WSDL to file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(conf.getAdapterServiceWSDLPath() + "/kapavirta_as.wsdl"));
    transformer.transform(source, result);
}

From source file:com.mdt.rtm.Invoker.java

public Element invoke(Param... params) throws ServiceException {
    Element result;/*www  .j a v a2s . c  om*/

    long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation;
    if (timeSinceLastInvocation < INVOCATION_INTERVAL) {
        // In order not to invoke the RTM service too often
        try {
            Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation);
        } catch (InterruptedException e) {
            throw new ServiceInternalException(
                    "Unexpected interruption while attempting to pause for some time before invoking the RTM service back",
                    e);
        }
    }

    log.debug("Invoker running at " + new Date());

    HttpClient client = new HttpClient();
    if (proxyHostName != null) {
        // Sets an HTTP proxy and the credentials for authentication
        client.getHostConfiguration().setProxy(proxyHostName, proxyPortNumber);
        if (proxyLogin != null) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyLogin, proxyPassword));
        }
    }
    GetMethod method = new GetMethod(serviceBaseUrl + REST_SERVICE_URL_POSTFIX);
    method.setRequestHeader(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8");
    NameValuePair[] pairs = new NameValuePair[params.length + 1];
    int i = 0;
    for (Param param : params) {
        log.debug("  setting " + param.getName() + "=" + param.getValue());
        pairs[i++] = param.toNameValuePair();
    }
    pairs[i++] = new NameValuePair(API_SIG_PARAM, calcApiSig(params));
    method.setQueryString(pairs);

    try {
        URI methodUri;
        try {
            methodUri = method.getURI();
            log.info("Executing the method:" + methodUri);
        } catch (URIException exception) {
            String message = "Cannot determine the URI of the web method";
            log.error(message);
            throw new ServiceInternalException(message, exception);
        }
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
            throw new ServiceInternalException("method failed: " + method.getStatusLine());
        }

        // THINK: this method is deprecated, but the only way to get the body as a string, without consuming
        // the body input stream: the HttpMethodBase issues a warning but does not let you call the "setResponseStream()" method!
        String responseBodyAsString = method.getResponseBodyAsString();
        log.info("  Invocation response:\r\n" + responseBodyAsString);
        Document responseDoc = builder.parse(method.getResponseBodyAsStream());
        Element wrapperElt = responseDoc.getDocumentElement();
        if (!wrapperElt.getNodeName().equals("rsp")) {
            throw new ServiceInternalException(
                    "unexpected response returned by RTM service: " + responseBodyAsString);
        } else {
            String stat = wrapperElt.getAttribute("stat");
            if (stat.equals("fail")) {
                Node errElt = wrapperElt.getFirstChild();
                while (errElt != null
                        && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) {
                    errElt = errElt.getNextSibling();
                }
                if (errElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + responseBodyAsString);
                } else {
                    throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")),
                            ((Element) errElt).getAttribute("msg"));
                }
            } else {
                Node dataElt = wrapperElt.getFirstChild();
                while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE
                        || dataElt.getNodeName().equals("transaction") == true)) {
                    try {
                        Node nextSibling = dataElt.getNextSibling();
                        if (nextSibling == null) {
                            break;
                        } else {
                            dataElt = nextSibling;
                        }
                    } catch (IndexOutOfBoundsException exception) {
                        // Some implementation may throw this exception, instead of returning a null sibling
                        break;
                    }
                }
                if (dataElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + responseBodyAsString);
                } else {
                    result = (Element) dataElt;
                }
            }
        }

    } catch (HttpException e) {
        throw new ServiceInternalException("", e);
    } catch (IOException e) {
        throw new ServiceInternalException("", e);
    } catch (SAXException e) {
        throw new ServiceInternalException("", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    lastInvocation = System.currentTimeMillis();
    return result;
}

From source file:com.nridge.core.base.io.xml.DocumentListXML.java

/**
 * Parses an XML DOM element and loads it into a bag list.
 *
 * @param anElement DOM element./*  w  ww.  ja  v  a  2s . co m*/
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    String nodeName;
    Document document;
    Element nodeElement;
    DocumentXML documentXML;

    nodeName = anElement.getNodeName();
    if (StringUtils.endsWithIgnoreCase(nodeName, IO.XML_LIST_NODE_NAME)) {
        NodeList nodeList = anElement.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            nodeItem = nodeList.item(i);

            if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
                continue;

            // We really do not know how the node was named, so we will just accept it.

            nodeElement = (Element) nodeItem;
            documentXML = new DocumentXML();
            documentXML.load(nodeElement);
            document = documentXML.getDocument();
            if (document != null)
                mDocumentList.add(document);
        }
    }
}

From source file:com.nridge.core.base.io.xml.DataBagListXML.java

/**
 * Parses an XML DOM element and loads it into a bag list.
 *
 * @param anElement DOM element./*from  w  ww  .  j a  va2  s.c  o m*/
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    String nodeName;
    DataBag dataBag;
    Element nodeElement;
    DataBagXML dataBagXML;

    nodeName = anElement.getNodeName();
    if (StringUtils.endsWithIgnoreCase(nodeName, "List")) {
        NodeList nodeList = anElement.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            nodeItem = nodeList.item(i);

            if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
                continue;

            nodeName = nodeItem.getNodeName();
            if (StringUtils.endsWithIgnoreCase(nodeName, "DataBag")) {
                nodeElement = (Element) nodeItem;
                dataBagXML = new DataBagXML();
                dataBagXML.load(nodeElement);
                dataBag = dataBagXML.getBag();
                if (dataBag != null)
                    mDataBagList.add(dataBag);
            }
        }
    }
}

From source file:org.finra.jtaf.core.parsing.CommandLibraryParser.java

private final List<InvocationTarget> processLibrary(Element elem, MessageCollector mc) throws ParsingException {
    if (elem.getNodeName().equalsIgnoreCase("library")) {
        List<InvocationTarget> invocationTargets = new ArrayList<InvocationTarget>();
        ExceptionAccumulator acc = new ExceptionAccumulator();

        for (Element child : ParserHelper.getChildren(elem)) {
            try {
                invocationTargets.add(processInvocationTarget(child, mc));
            } catch (Throwable th) {
                mc.error(th.getMessage());
                acc.add(th);/*from  w  w  w  .j av  a 2s.c  om*/
            }
        }

        if (!acc.isEmpty()) {
            throw acc;
        }

        return invocationTargets;
    } else {
        throw new UnexpectedElementException(elem);
    }
}

From source file:net.sf.cb2xml.convert.MainframeToXml.java

private Element convertNode(Element element, Context context) throws JCopybookUnmarshallException {
    String text = null;//ww  w  .j av a2s . c  o m
    String resultElementName = element.getAttribute("name").replaceAll("[^0-9^A-Z\\-]+", "||");
    Element resultElement = resultDocument.createElement(resultElementName);
    try {
        int length = Integer.parseInt(element.getAttribute("display-length"));
        int childElementCount = 0;
        NodeList nodeList = element.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                Element childElement = (Element) node;
                if (!childElement.getAttribute("level").equals("88")
                        && "item".equals(childElement.getNodeName())) {
                    childElementCount++;
                    if (childElement.hasAttribute("occurs")) {
                        boolean dependOn = StringUtils.isNotEmpty(childElement.getAttribute("depending-on"));
                        BigInteger count = numerics.get(childElement.getAttribute("depending-on"));
                        int childOccurs = Integer.parseInt(childElement.getAttribute("occurs"));
                        if (dependOn && count != null) {
                            childOccurs = count.intValue();
                        }
                        for (int j = 0; j < childOccurs; j++) {
                            resultElement.appendChild(convertNode(childElement, context));
                        }
                    } else {
                        if (!"item".equals(childElement.getAttribute("name")))
                            resultElement.appendChild(convertNode(childElement, context));
                    }
                }
            }
        }
        if (childElementCount == 0 && !"true".equals(element.getAttribute("redefined"))) {
            text = mainframeBuffer.substring(context.offset, context.offset + length);
            if ("true".equals(element.getAttribute("numeric"))) {
                String textForNumeric = text.trim();
                if (textForNumeric.isEmpty()) {
                    textForNumeric = "true".equals(element.getAttribute("signed")) ? "{" : "0";
                }
                textForNumeric = removeLeftZeros(textForNumeric);
                if ("true".equals(element.getAttribute("signed"))) {
                    String originalDigit = textForNumeric.substring(textForNumeric.length() - 1,
                            textForNumeric.length());
                    String digit = SignedNumericMappingTable.decodeMap.get(originalDigit);
                    if (digit == null)
                        throw new Exception("bad signed numeric last digit: " + originalDigit);
                    textForNumeric = (digit.startsWith("-") ? "-" : "")
                            + textForNumeric.substring(0, textForNumeric.length() - 1)
                            + (digit.length() == 2 ? digit.substring(1) : digit);
                }
                if (textForNumeric.length() == 0)
                    text = "0";
                else if (StringUtils.isNotEmpty(element.getAttribute("scale"))) {
                    int scale = Integer.parseInt(element.getAttribute("scale"));
                    textForNumeric = getDecimalValue(textForNumeric, scale);
                } else
                    numerics.put(resultElementName, new BigInteger(textForNumeric));
                text = textForNumeric;
            }
            context.offset += length;
            Text textNode = resultDocument.createTextNode(text.trim());
            resultElement.appendChild(textNode);
        }
        return resultElement;
    } catch (Exception e) {
        if (e instanceof JCopybookUnmarshallException)
            throw (JCopybookUnmarshallException) e;
        throw new JCopybookUnmarshallException(
                String.format("can't parse copybook string on element '%s' and text '%s'", resultElementName,
                        text),
                e, mainframeBuffer, XmlUtils.domToString(resultElement.getOwnerDocument()).toString(),
                resultElementName, text, element.getOwnerDocument());
    }
}

From source file:com.cloud.agent.api.storage.OVFHelper.java

private OVFDiskController getController(Element controllerItem) {
    OVFDiskController dc = new OVFDiskController();
    NodeList child = controllerItem.getChildNodes();
    for (int l = 0; l < child.getLength(); l++) {
        if (child.item(l) instanceof Element) {
            Element el = (Element) child.item(l);
            if ("rasd:ElementName".equals(el.getNodeName())) {
                dc._name = el.getTextContent();
            }/* w  w w.  j a  v a 2 s.c  o  m*/
            if ("rasd:ResourceSubType".equals(el.getNodeName())) {
                dc._subType = el.getTextContent();
            }
        }
    }
    return dc;
}