Example usage for org.w3c.dom Element getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:org.canova.api.conf.Configuration.java

private void loadResource(Properties properties, Object name, boolean quiet) {
    try {//w  w w  .j a va 2  s  . c om
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        //ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        //allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;

        if (name instanceof URL) { // an URL resource
            URL url = (URL) name;
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) name);
            if (url != null) {
                if (!quiet) {
                    LOG.info("parsing " + url);
                }
                doc = builder.parse(url.toString());
            }
        } else if (name instanceof InputStream) {
            try {
                doc = builder.parse((InputStream) name);
            } finally {
                ((InputStream) name).close();
            }
        } else if (name instanceof Element) {
            root = (Element) name;
        }

        if (doc == null && root == null) {
            if (quiet)
                return;
            throw new RuntimeException(name + " not found");
        }

        if (root == null) {
            root = doc.getDocumentElement();
        }
        if (!"configuration".equals(root.getTagName()))
            LOG.error("bad conf file: top-level element not <configuration>");
        NodeList props = root.getChildNodes();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element))
                continue;
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(properties, prop, quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName()))
                LOG.warn("bad conf file: element not <property>");
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element))
                    continue;
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes())
                    attr = ((Text) field.getFirstChild()).getData().trim();
                if ("value".equals(field.getTagName()) && field.hasChildNodes())
                    value = ((Text) field.getFirstChild()).getData();
                if ("final".equals(field.getTagName()) && field.hasChildNodes())
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
            }

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null && value != null) {
                if (!finalParameters.contains(attr)) {
                    properties.setProperty(attr, value);
                    if (storeResource) {
                        updatingResource.put(attr, name.toString());
                    }
                    if (finalParameter)
                        finalParameters.add(attr);
                } else {
                    LOG.warn(name + ":a attempt to override final parameter: " + attr + ";  Ignoring.");
                }
            }
        }

    } catch (IOException | ParserConfigurationException | SAXException | DOMException e) {
        LOG.error("error parsing conf file: " + e);
        throw new RuntimeException(e);
    }
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

private void processPort(Element portElement) throws CatalogingException {
    try {//from w  w w  .j  a v  a 2s .c  o  m
        String id = getPortId(portElement);

        if (idToWSDLMap.containsKey(id)) {
            return;
        }

        //Create a RIM ServiceBinding instances for service tag 
        ServiceBindingType ebServiceBindingType = bu.rimFac.createServiceBindingType();
        bu.addSlotsToRegistryObject(ebServiceBindingType, dontVersionSlotsMap);

        //Set id
        ebServiceBindingType.setId(id);

        idToRIMMap.put(id, ebServiceBindingType);
        idToWSDLMap.put(id, portElement);

        //Set name
        String nameStr = wsdlDocument.getAttribute(portElement, WSDLConstants.ATTR_NAME);

        ebServiceBindingType.setName(bu.getName(nameStr));

        //Set description
        Element docElement = wsdlDocument.getElement(portElement, WSDLConstants.QNAME_DOCUMENTATION);
        if (docElement != null) {
            String docStr = docElement.getFirstChild().getNodeValue();
            ebServiceBindingType.setDescription(bu.getDescription(docStr));
        }

        catalogTargetNamespace(ebServiceBindingType);

        //Add wsdl Service Classification
        bu.addClassificationToRegistryObject(ebServiceBindingType,
                CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_WSDL_PORT);

        //Set parent link
        Element serviceElement = (Element) portElement.getParentNode();
        ServiceType rimService = (ServiceType) idToRIMMap.get(getServiceId(serviceElement));
        if (rimService != null) {
            ebServiceBindingType.setService(rimService.getId());
        }

        //Add accessURI
        String accessURI = null;

        Element soapAddressElement = wsdlDocument.getElement(portElement, WSDLConstants.QNAME_SOAP_ADDRESS);
        if (soapAddressElement != null) {
            accessURI = wsdlDocument.getAttribute(soapAddressElement, WSDLConstants.ATTR_LOCATION);

            if (accessURI != null) {
                ebServiceBindingType.setAccessURI(accessURI);
            }
        }
        // document get binding
        String bindingStr = wsdlDocument.getAttribute(portElement, WSDLConstants.ATTR_BINDING);
        Element bindingElement = resolveBinding(wsdlDocument, bindingStr);
        if (bindingElement == null) {
            throw new CatalogingException(
                    ServerResourceBundle.getInstance().getString("message.missingRequiredElement",
                            new Object[] { wsdlDocument.getSystemId(), bindingElement }));
        }
        //Now process the Binding instances for the Service
        //Note it may be in an imported document
        processBinding(bindingElement);

        //Set Implements Association between Port and Binding
        ExtrinsicObjectType rimBinding = (ExtrinsicObjectType) idToRIMMap.get(getBindingId(bindingElement));
        AssociationType1 ebAssociationType = bu.createAssociationType(ebServiceBindingType.getId(),
                rimBinding.getId(), CanonicalConstants.CANONICAL_ASSOCIATION_TYPE_ID_Implements);
        //May need a more deterministic algorithm for setting this id??
        ebAssociationType.setId(ebServiceBindingType.getId() + ":Implements:" + rimBinding.getId());
        registryObjects.add(ebAssociationType);
    } catch (CatalogingException ce) {
        throw ce;
    } catch (Throwable e) {
        throw new CatalogingException(e);
    }
}

From source file:com.hpe.application.automation.tools.results.RunResultRecorder.java

private static void addTimeRanges(TimeRangeResult transactionTimeRange, Element slaRuleElement) {
    Node timeRangeNode;//  w  w w.ja  va2  s.  co  m
    Element timeRangeElement;
    NodeList timeRanges = slaRuleElement.getElementsByTagName("TimeRangeInfo");
    if (timeRanges == null || timeRanges.getLength() == 0) {
        return;
    }
    //Taking the goal per transaction -
    double generalGoalValue = Double
            .parseDouble(((Element) timeRanges.item(0)).getAttribute(SLA_GOAL_VALUE_LABEL));
    transactionTimeRange.setGoalValue(generalGoalValue);

    for (int k = 0; k < timeRanges.getLength(); k++) {
        timeRangeNode = timeRanges.item(k);
        timeRangeElement = (Element) timeRangeNode;
        double actualValue = Double.parseDouble(timeRangeElement.getAttribute(SLA_ACTUAL_VALUE_LABEL));
        double goalValue = Double.parseDouble(timeRangeElement.getAttribute(SLA_GOAL_VALUE_LABEL));
        int loadValue = Integer.parseInt(timeRangeElement.getAttribute("LoadValue"));
        double startTime = Double.parseDouble(timeRangeElement.getAttribute("StartTime"));
        double endTIme = Double.parseDouble(timeRangeElement.getAttribute("EndTime"));
        transactionTimeRange.incActualValue(actualValue);
        LrTest.SLA_STATUS slaStatus = LrTest.SLA_STATUS
                .checkStatus(timeRangeElement.getFirstChild().getTextContent());
        TimeRange timeRange = new TimeRange(actualValue, goalValue, slaStatus, loadValue, startTime, endTIme);
        transactionTimeRange.getTimeRanges().add(timeRange);
    }
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

private void processBinding(Element bindingElement) throws CatalogingException {
    try {//  www . j  a  va 2  s. c  om
        String id = getBindingId(bindingElement);

        if (idToWSDLMap.containsKey(id)) {
            return;
        }

        //Create a RIM ExtrinsicObject instance for wsdl binding 
        ExtrinsicObjectType ebExtrinsicObjectType = bu.rimFac.createExtrinsicObjectType();
        bu.addSlotsToRegistryObject(ebExtrinsicObjectType, dontVersionSlotsMap);
        idToRIMMap.put(id, ebExtrinsicObjectType);
        idToWSDLMap.put(id, bindingElement);

        //Set id
        ebExtrinsicObjectType.setId(id);

        //Set name
        String nameStr = wsdlDocument.getAttribute(bindingElement, WSDLConstants.ATTR_NAME);
        ebExtrinsicObjectType.setName(bu.getName(nameStr));

        //Set description
        Element docElement = wsdlDocument.getElement(bindingElement, WSDLConstants.QNAME_DOCUMENTATION);
        if (docElement != null) {
            String docStr = docElement.getFirstChild().getNodeValue();
            ebExtrinsicObjectType.setDescription(bu.getDescription(docStr));
        }

        catalogTargetNamespace(ebExtrinsicObjectType);

        //Add wsdl Service Classification
        //??Update spec to say classification is also required for consistency with WSDL Service and Port mapping.
        ebExtrinsicObjectType.setObjectType(CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_WSDL_BINDING);
        bu.addClassificationToRegistryObject(ebExtrinsicObjectType,
                CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_WSDL_BINDING);

        List<Element> soapBindingElements = wsdlDocument.getElements(bindingElement,
                WSDLConstants.QNAME_SOAP_BINDING);
        Iterator<Element> soapBindingElementItr = soapBindingElements.iterator();
        while (soapBindingElementItr.hasNext()) {
            Element soapBindingElement = soapBindingElementItr.next();

            //Add SOAP Binding Classification
            bu.addClassificationToRegistryObject(ebExtrinsicObjectType,
                    CanonicalConstants.CANONICAL_PROTOCOL_TYPE_ID_SOAP);

            String transport = wsdlDocument.getAttribute(soapBindingElement, WSDLConstants.ATTR_TRANSPORT);
            if (transport.equals(WSDLConstants.URI_SOAP_TRANSPORT_HTTP)) {
                bu.addClassificationToRegistryObject(ebExtrinsicObjectType,
                        CanonicalConstants.CANONICAL_TRANSPORT_TYPE_ID_HTTP);
            }

            String soapStyleStr = wsdlDocument.getAttribute(soapBindingElement, WSDLConstants.ATTR_STYLE);
            String styleNode = null;
            if (soapStyleStr.equalsIgnoreCase(WSDLConstants.RPC)) {
                styleNode = CanonicalConstants.CANONICAL_SOAP_STYLE_TYPE_ID_RPC;
            } else if (soapStyleStr.equalsIgnoreCase(WSDLConstants.DOCUMENT)) {
                styleNode = CanonicalConstants.CANONICAL_SOAP_STYLE_TYPE_ID_DOCUMENT;
            }

            if (styleNode != null) {
                //Add SOAP Style Classification
                bu.addClassificationToRegistryObject(ebExtrinsicObjectType, styleNode);
            }
        }

        ebExtrinsicObjectType.setMimeType("text/xml"); //Add to spec??

        // document get port type
        String portTypeStr = wsdlDocument.getAttribute(bindingElement, WSDLConstants.ATTR_TYPE);
        Element portTypeElement = resolvePortType(wsdlDocument, portTypeStr);
        if (portTypeElement == null) {
            throw new CatalogingException(
                    ServerResourceBundle.getInstance().getString("message.missingRequiredElement",
                            new Object[] { wsdlDocument.getSystemId(), portTypeStr }));
        }
        processPortType(portTypeElement);

        //Set Implements Association between Binding and PortType
        ExtrinsicObjectType rimPortType = (ExtrinsicObjectType) idToRIMMap.get(getPortTypeId(portTypeElement));
        AssociationType1 ebAssociationType = bu.createAssociationType(ebExtrinsicObjectType.getId(),
                rimPortType.getId(), CanonicalConstants.CANONICAL_ASSOCIATION_TYPE_ID_Implements);
        //May need a more deterministic algorithm for setting this id??
        ebAssociationType.setId(ebExtrinsicObjectType.getId() + ":Implements:" + rimPortType.getId());
        registryObjects.add(ebAssociationType);
    } catch (CatalogingException ce) {
        throw ce;
    } catch (Throwable e) {
        throw new CatalogingException(e);
    }
}

From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java

public void copyPageTemplatesPostOp(int oldMenuKey, CopyContext copyContext) throws VerticalCopyException {

    int newMenuKey = copyContext.getMenuKey(oldMenuKey);

    Document doc = getPageTemplatesByMenu(newMenuKey, null);
    Element[] pageTemplateElems = XMLTool.getElements(doc.getDocumentElement());

    try {//from  w w  w .j  a  v a  2  s.c om
        for (Element pageTemplateElem : pageTemplateElems) {

            // datasource
            NodeList parameterList = XMLTool.selectNodes(pageTemplateElem,
                    "datasources/datasource/parameters/parameter");
            for (int j = 0; j < parameterList.getLength(); j++) {
                Element parameterElem = (Element) parameterList.item(j);
                String name = parameterElem.getAttribute("name");
                if ("cat".equalsIgnoreCase(name)) {
                    Text text = (Text) parameterElem.getFirstChild();
                    if (text != null) {
                        String oldCategoryKey = text.getData();
                        if (oldCategoryKey != null && oldCategoryKey.length() > 0) {
                            int newCategoryKey = copyContext.getCategoryKey(Integer.parseInt(oldCategoryKey));
                            if (newCategoryKey >= 0) {
                                text.setData(String.valueOf(newCategoryKey));
                            }
                        }
                    }
                } else if ("menu".equalsIgnoreCase(name)) {
                    Text text = (Text) parameterElem.getFirstChild();
                    if (text != null) {
                        String oldKey = text.getData();
                        if (oldKey != null && oldKey.length() > 0) {
                            int newKey = copyContext.getMenuKey(Integer.parseInt(oldKey));
                            if (newKey >= 0) {
                                text.setData(String.valueOf(newKey));
                            }
                        }
                    }
                }
            }
        }

        updatePageTemplate(doc);
    } catch (VerticalUpdateException vue) {
        String message = "Failed to copy page templates (post operation): %t";
        VerticalEngineLogger.errorCopy(this.getClass(), 0, message, vue);
    }
}

From source file:com.rubika.aotalk.util.ItemRef.java

public List<Object> getData(String lowId, String highId, String ql) {
    List<Object> result = new ArrayList<Object>();

    EasyTracker.getInstance().setContext(AOTalk.getContext());
    Tracker tracker = EasyTracker.getTracker();
    long loadTime = System.currentTimeMillis();

    String xml = null;/*from   w w  w . j  av  a2  s  .c o  m*/
    Document doc = null;

    String icon = "";
    String name = "";
    String description = "";
    String flaglist = "";
    String flags = "";
    String requirements = "";
    String can = "";
    String events = "";
    String attributes = "";
    String attacks = "";
    String defenses = "";
    String level = "";

    int lowQL = 0;
    int highQL = 0;

    String xyphosUrl = String.format(Statics.XYPHOS_ITEM_QL_URL, lowId, ql);
    Logging.log(APP_TAG, xyphosUrl);

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(xyphosUrl);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (xml != null) {
        if (xml.contains("<item>")) {
            xml = xml.substring(xml.indexOf("<item>"));
        }

        Pattern pattern = Pattern.compile("<description>(.*?)</description>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(xml);

        while (matcher.find()) {
            xml = xml.replace(matcher.group(1),
                    matcher.group(1).replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
        }

        pattern = Pattern.compile(" name=\"(.*?)\" />", Pattern.DOTALL);
        matcher = pattern.matcher(xml);

        while (matcher.find()) {
            xml = xml.replace(matcher.group(1), matcher.group(1).replaceAll("<b>", "").replaceAll("</b>", ""));
        }

        Logging.log(APP_TAG, xml);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);
        } catch (ParserConfigurationException e) {
            Logging.log(APP_TAG, e.getMessage());
            return null;
        } catch (SAXException e) {
            Logging.log(APP_TAG, e.getMessage());
            return null;
        } catch (IOException e) {
            Logging.log(APP_TAG, e.getMessage());
            return null;
        }

        if (doc != null) {
            NodeList nl = doc.getElementsByTagName("item");

            for (int i = 0; i < nl.getLength(); i++) {
                Element e = (Element) nl.item(i);

                name = getValue(e, "name");
                description = getValue(e, "description").replaceAll("\n", "<br />");
            }

            nl = doc.getElementsByTagName("low");
            for (int x = 0; x < nl.getLength(); x++) {
                Element item = (Element) nl.item(x);
                lowQL = Integer.parseInt(item.getAttribute("ql"));
            }

            nl = doc.getElementsByTagName("high");
            for (int x = 0; x < nl.getLength(); x++) {
                Element item = (Element) nl.item(x);
                highQL = Integer.parseInt(item.getAttribute("ql"));
            }

            nl = doc.getElementsByTagName("attribute");

            int equipmentPageID = -1;
            for (int x = 0; x < nl.getLength(); x++) {
                Element item = (Element) nl.item(x);
                int value = Integer.parseInt(item.getAttribute("value"));

                if (item != null) {
                    if (item.getAttribute("stat") != null) {
                        if (item.getAttribute("stat").equals("79")) {
                            icon = item.getAttribute("value");
                        } else if (item.getAttribute("stat").equals("76")) {
                            equipmentPageID = value;
                        } else if (item.getAttribute("stat").equals("298")) {
                            String slots = ItemValues.getSlot(value, equipmentPageID);

                            if (slots.length() > 0) {
                                attributes += item.getAttribute("name") + " <b>" + slots + "</b><br />";
                            }
                        } else if (item.getAttribute("stat").equals("0")) {
                            flaglist = item.getAttribute("extra") + "<br />";
                        } else if (item.getAttribute("stat").equals("30")) {
                            can = item.getAttribute("extra");
                        } else if (item.getAttribute("stat").equals("54")) {
                            level = String.valueOf(value);
                        } else {
                            if (!item.getAttribute("stat").equals("88")
                                    && !item.getAttribute("stat").equals("2")
                                    && !item.getAttribute("stat").equals("209")
                                    && !item.getAttribute("stat").equals("353")
                                    && !item.getAttribute("stat").equals("12")
                                    && !item.getAttribute("stat").equals("74")
                                    && !item.getAttribute("stat").equals("272")
                                    && !item.getAttribute("stat").equals("270")
                                    && !item.getAttribute("stat").equals("269")
                                    && !item.getAttribute("stat").equals("428")
                                    && !item.getAttribute("stat").equals("419")) {
                                if (item.getAttribute("extra").equals("")) {
                                    attributes += item.getAttribute("name") + " " + item.getAttribute("value")
                                            + "<br />";
                                } else {
                                    attributes += item.getAttribute("name") + " " + item.getAttribute("extra")
                                            + "<br />";
                                }
                            }
                        }
                    }
                }
            }

            nl = doc.getElementsByTagName("attack");

            for (int i = 0; i < nl.getLength(); i++) {
                Element item = (Element) nl.item(i);
                attacks += item.getAttribute("name") + " " + item.getAttribute("percent") + "%<br />";
            }

            nl = doc.getElementsByTagName("defense");

            for (int i = 0; i < nl.getLength(); i++) {
                Element item = (Element) nl.item(i);
                defenses += item.getAttribute("name") + " " + item.getAttribute("percent") + "%<br />";
            }

            nl = doc.getElementsByTagName("action");

            for (int i = 0; i < nl.getLength(); i++) {
                Element item = (Element) nl.item(i);
                NodeList nreq = item.getElementsByTagName("requirement");

                requirements += "<br /><b><i>" + item.getAttribute("name") + "</i></b><br />";

                for (int p = 0; p < nreq.getLength(); p++) {
                    Element ritem = (Element) nreq.item(p);
                    NodeList reqList = ritem.getChildNodes();

                    String req = "%s %s %s %s %s<br />";
                    String target = "";
                    String stat = "";
                    String op = "";
                    String value = "";
                    String subop = "";

                    for (int y = 0; y < reqList.getLength(); y++) {
                        Node reqItem = reqList.item(y);

                        if (!(reqItem instanceof Text)) {

                            Element e = (Element) reqItem;

                            if (e.getNodeName().equals("target")) {
                                target = e.getAttribute("name");
                            }

                            if (e.getNodeName().equals("stat")) {
                                stat = e.getAttribute("name");
                            }

                            if (e.getNodeName().equals("op")) {
                                op = e.getAttribute("name");
                            }

                            if (e.getNodeName().equals("value")) {
                                value = e.getAttribute("num");

                                if (stat.equals("WornItem")) {
                                    value = ItemValues.getWornItem(Integer.parseInt(value));
                                }

                                if (stat.equals("Expansion")) {
                                    value = ItemValues.getExpansion(Integer.parseInt(value));
                                }

                                if (stat.equals("Breed")) {
                                    value = ItemValues.getBreed(Integer.parseInt(value));
                                }

                                if (stat.equals("ExpansionPlayfield")) {
                                    value = ItemValues.getExpansionPlayfield(Integer.parseInt(value));
                                }

                                if (stat.equals("CurrentPlayfield")) {
                                    value = ItemValues.getCurrentPlayfield(Integer.parseInt(value));
                                }

                                if (stat.equals("Faction")) {
                                    value = ItemValues.getFaction(Integer.parseInt(value));
                                }

                                if (stat.equals("Flags")) {
                                    if (op.equals("HasPerk")) {
                                        value = ItemValues.getPerk(Integer.parseInt(value));
                                    }
                                    if (op.equals("HasNotWornItem")) {
                                        value = ItemValues.getHasNotWornItem(Integer.parseInt(value));
                                    }
                                }

                                if (stat.equals("Profession") || stat.equals("VisualProfession")) {
                                    value = ItemValues.getProfession(Integer.parseInt(value));
                                }
                            }

                            if (e.getNodeName().equals("subop")) {
                                subop = e.getAttribute("name");
                            }
                        }
                    }

                    requirements += String.format(req, target, stat, op, value, subop);
                }
            }

            nl = doc.getElementsByTagName("event");

            for (int x = 0; x < nl.getLength(); x++) {
                Element item = (Element) nl.item(x);

                if (item != null) {
                    events += "<br /><b><i>" + item.getAttribute("name") + "</i></b><br />";

                    NodeList nwear = item.getElementsByTagName("function");
                    String funcName = "";

                    for (int y = 0; y < nwear.getLength(); y++) {
                        Element wear = (Element) nwear.item(y);
                        NodeList ntarget = wear.getElementsByTagName("target");
                        NodeList nfunc = wear.getElementsByTagName("func");
                        NodeList nparam = wear.getElementsByTagName("parameters");

                        for (int z = 0; z < ntarget.getLength(); z++) {
                            Element target = (Element) ntarget.item(z);
                            events += target.getAttribute("name") + " ";
                        }

                        for (int z = 0; z < nfunc.getLength(); z++) {
                            Element func = (Element) nfunc.item(z);
                            events += func.getAttribute("name") + " ";
                            funcName = func.getAttribute("name");
                        }

                        for (int z = 0; z < nparam.getLength(); z++) {
                            Element params = (Element) nparam.item(z);
                            NodeList nparams = params.getElementsByTagName("param");

                            for (int i = 0; i < nparams.getLength(); i++) {
                                Element param = (Element) nparams.item(i);

                                if (nparams.getLength() > 1) {
                                    if (i == 0) {
                                        if (funcName.equals("Modify") || funcName.equals("LockSkill")
                                                || funcName.equals("Skill") || funcName.equals("Hit")
                                                || funcName.equals("ChangeVariable")
                                                || funcName.equals("TimedEffect")) {
                                            events += ItemValues.getSkill(
                                                    Integer.parseInt(param.getFirstChild().getNodeValue()));
                                        } else if (funcName.equals("CastStunNano")
                                                || funcName.equals("AreaCastNano")) {
                                            events += ItemValues.lookupItemName(
                                                    Integer.parseInt(param.getFirstChild().getNodeValue()));
                                        } else if (funcName.equals("ResistNanoStrain")) {
                                            events += ItemValues.getNanoStrain(
                                                    Integer.parseInt(param.getFirstChild().getNodeValue()));
                                        } else if (funcName.equals("SetFlag")) {
                                            events += ItemValues.getFlag(
                                                    Integer.parseInt(param.getFirstChild().getNodeValue()));
                                        } else {
                                            events += param.getFirstChild().getNodeValue();
                                        }
                                    } else if (i == 3) {
                                        if (funcName.equals("Teleport")) {
                                            events += ItemValues.getCurrentPlayfield(
                                                    Integer.parseInt(param.getFirstChild().getNodeValue()));
                                        } else if (funcName.equals("HasNotFormula")) {
                                            events += ItemValues.getNano(
                                                    Integer.parseInt(param.getFirstChild().getNodeValue()));
                                        } else {
                                            events += param.getFirstChild().getNodeValue();
                                        }
                                    } else {
                                        if (funcName.equals("AddSkill") || funcName.equals("ChangeVariable")
                                                || funcName.equals("Set")) {
                                            int num = Integer.parseInt(param.getFirstChild().getNodeValue());
                                            events += ItemValues.getSkill(num);
                                        } else {
                                            events += param.getFirstChild().getNodeValue();
                                        }
                                    }
                                } else {
                                    if (funcName.equals("UploadNano") || funcName.equals("CastNano")
                                            || funcName.equals("TeamCastNano")) {
                                        events += ItemValues.lookupItemName(
                                                Integer.parseInt(param.getFirstChild().getNodeValue()));
                                    } else if (funcName.equals("RemoveNanoStrain")) {
                                        events += ItemValues.getNanoStrain(
                                                Integer.parseInt(param.getFirstChild().getNodeValue()));
                                    } else {
                                        events += param.getFirstChild().getNodeValue();
                                    }
                                }

                                events += " ";
                            }
                        }

                        events += "<br />";
                    }
                }
            }
        }

        if (flaglist.contains("NoDrop")) {
            flags += "NODROP";
        }

        if (flaglist.contains("Unique")) {
            if (flags.length() > 0) {
                flags += ", ";
            }
            flags += "UNIQUE";
        }

        if (!flags.equals("")) {
            flags = "<br /><font color=#999999>" + flags + "</font>";
        }

        retval += "<img src=\"" + Statics.ICON_PATH + icon + "\" class=\"item\">" + "<b>" + name + "</b>"
                + flags + "<br /><br />" + "<b>Quality level:</b> " + level + "<br /><br />"
                + "<b>Description</b><br />" + description;

        if (can.length() > 0) {
            retval += "<br /><br /><b>Can</b><br />" + can;
        }

        if (flaglist.length() > 0) {
            retval += "<br /><br /><b>Flags</b><br />" + flaglist;
        }

        if (attributes.length() > 0) {
            retval += "<br /><b>Attributes</b><br />";
            retval += attributes;
        }

        if (attacks.length() > 0) {
            retval += "<br /><b>Attacks</b><br />";
            retval += attacks;
        }

        if (defenses.length() > 0) {
            retval += "<br /><b>Defenses</b><br />";
            retval += defenses;
        }

        if (requirements.length() > 0) {
            requirements = requirements.replace("EqualTo", "=").replace("NotBitAnd", "!=")
                    .replace("BitAnd", "=").replace("Unequal", "!=").replace("LessThan", "<")
                    .replace("GreaterThan", ">");
            retval += "<br /><b>Reqirements</b><br />" + requirements;
        }

        if (events.length() > 0) {
            retval += "<br /><b>Events</b><br />";
            retval += events;
        }

        /*
        retval += "<br /><br />";
        retval += "<font color=#999999>Guides from AO-Universe</font>";
        retval += "<br />";
        retval += "<a href=\"gitem://" + name + "\">Check for guides</a>";
        retval += "<br /><br />";
        retval += "<font color=#999999>Recipes from AO RecipeBook</font>";
        retval += "<br />";
        retval += "<a href=\"aorbid://" + lowId + "\">Check for recipes</a>";
         */
        retval += "<br /><br />";
        retval += "<font color=#999999>Data from Xyphos.org</font>";
        retval += "<br />";
        retval += "<a href=\"chatcmd:///start http://www.xyphos.com/ao/aodb.php?id=" + lowId + "&ql=" + ql
                + "\">Show on web page</a>";

        if (retval.startsWith("<br />")) {
            retval = retval.replaceFirst("<br />", "");
        }
    }

    result.add(retval);
    result.add(lowQL);
    result.add(highQL);
    try {
        result.add(Integer.parseInt(level));
    } catch (NumberFormatException e) {
        Logging.log(APP_TAG, e.getMessage());
        result.add(0);
    }
    result.add(name);

    if (retval != null && retval.length() > 0) {
        tracker.sendTiming("Loading", System.currentTimeMillis() - loadTime, "Item", null);
    }

    return result;
}

From source file:com.amalto.core.history.accessor.ManyFieldAccessor.java

public void create() {
    parent.create();/*from  w  ww .ja va2  s .  com*/

    // TODO Refactor this
    Document domDocument = document.asDOM();
    Node node = getCollectionItemNode();
    if (node == null) {
        Element parentNode = (Element) parent.getNode();
        NodeList children = parentNode.getElementsByTagName(fieldName);
        int currentCollectionSize = children.getLength();
        if (currentCollectionSize > 0) {
            Node refNode = children.item(currentCollectionSize - 1).getNextSibling();
            while (currentCollectionSize <= index) {
                node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
                parentNode.insertBefore(node, refNode);
                currentCollectionSize++;
            }
        } else {
            // Collection is not present at all, append at the end of parent element.
            Node lastAccessedNode = document.getLastAccessedNode();
            if (lastAccessedNode != null) {
                Node refNode = lastAccessedNode.getNextSibling();
                while (refNode != null && !(refNode instanceof Element)) {
                    refNode = refNode.getNextSibling();
                }
                while (currentCollectionSize <= index) {
                    node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
                    if (lastAccessedNode == parentNode) {
                        if (lastAccessedNode == document.asDOM().getDocumentElement()
                                && lastAccessedNode.getChildNodes().getLength() > 0)
                            parentNode.insertBefore(node, parentNode.getFirstChild());
                        else
                            parentNode.appendChild(node);
                    } else if (refNode != null && refNode.getParentNode() == parentNode) {
                        parentNode.insertBefore(node, refNode);
                    } else {
                        parentNode.appendChild(node);
                    }
                    currentCollectionSize++;
                }
            } else {
                while (currentCollectionSize <= index) {
                    node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
                    parentNode.appendChild(node);
                    currentCollectionSize++;
                }
            }
        }
        document.setLastAccessedNode(node);
    } else if (node.getChildNodes().getLength() == 0) {
        // This accessor creates (n-1) empty elements when accessing first collection element at index n.
        // This setLastAccessedNode call allows all (n-1) elements to find their parent.
        if (!(node.getLocalName().equals(document.getLastAccessedNode().getLocalName())
                && document.getLastAccessedNode().getParentNode() == node.getParentNode())) {
            // if last accessed node is parallel with this node, can't modify last accessed node. eg, last accessed
            // node=/feature/vendor[2], this node=/feature/vendor[1], the last accessed is still /feature/vendor[2]
            document.setLastAccessedNode(node);
        }
    }
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to bind Annotation element//  www  .j a v a  2  s  .co m
 * 
 * @param element the Annotation element
 * @return Annotation data object
 * @throws InkMLException
 */
protected Annotation getAnnotation(final Element element) throws InkMLException {
    final Annotation annotation = new Annotation();

    final NamedNodeMap attributesMap = element.getAttributes();
    final int length = attributesMap.getLength();
    for (int index = 0; index < length; index++) {
        final Attr attribute = (Attr) attributesMap.item(index);
        final String attributeName = attribute.getName();
        if ("type".equals(attributeName)) {
            annotation.setType(attribute.getValue());
        } else if ("encoding".equals(attributeName)) {
            annotation.setEncoding(attribute.getValue());
        } else {
            annotation.addToOtherAttributesMap(attributeName, attribute.getValue());
        }
    }
    final Node valueNode = element.getFirstChild();
    if (null != valueNode) {
        annotation.setAnnotationTextValue(valueNode.getNodeValue());
    }
    return annotation;
}

From source file:org.bedework.calsvc.scheduling.hosts.IscheduleClient.java

private void parseResponse(final HostInfo hi, final Response resp) throws CalFacadeException {
    try {//from   w ww .  j  av  a 2  s . c o m
        Document doc = parseContent(resp);
        if (doc == null) {
            throw new CalFacadeException(CalFacadeException.badResponse);
        }

        QName sresponseTag;
        QName responseTag;
        QName recipientTag;
        QName requestStatusTag;
        QName calendarDataTag;
        QName errorTag;
        QName descriptionTag;

        if (hi.getSupportsISchedule()) {
            sresponseTag = IscheduleTags.scheduleResponse;
            responseTag = IscheduleTags.response;
            recipientTag = IscheduleTags.recipient;
            requestStatusTag = IscheduleTags.requestStatus;
            calendarDataTag = IscheduleTags.calendarData;
            errorTag = IscheduleTags.error;
            descriptionTag = IscheduleTags.responseDescription;
        } else {
            sresponseTag = CaldavTags.scheduleResponse;
            responseTag = CaldavTags.response;
            recipientTag = CaldavTags.recipient;
            requestStatusTag = CaldavTags.requestStatus;
            calendarDataTag = CaldavTags.calendarData;
            errorTag = WebdavTags.error;
            descriptionTag = WebdavTags.responseDescription;
        }

        Element root = doc.getDocumentElement();

        if (!XmlUtil.nodeMatches(root, sresponseTag)) {
            throw new CalFacadeException(CalFacadeException.badResponse);
        }

        for (Element el : getChildren(root)) {
            ResponseElement fbel = new ResponseElement();

            if (!XmlUtil.nodeMatches(el, responseTag)) {
                throw new CalFacadeException(CalFacadeException.badResponse);
            }

            /* ================================================================
            11.2.  CALDAV/ISCHEDULE:response XML Element
                    
            Name:  response
            Namespace:  urn:ietf:params:xml:ns:caldav   or
            urn:ietf:params:xml:ns:ischedule   or
                    
            Purpose:  Contains a single response for a POST method request.
            Description:  See Section 6.1.4.
            Definition:
                    
            <!ELEMENT response (recipient,
                    request-status,
                    calendar-data?,
                    error?,
                    response-description?)>
               ================================================================ */

            Iterator<Element> respels = getChildren(el).iterator();

            Element respel = respels.next();

            if (!XmlUtil.nodeMatches(respel, recipientTag)) {
                throw new CalFacadeException(CalFacadeException.badResponse);
            }

            fbel.setRecipient(getElementContent(respel));

            respel = respels.next();

            if (!XmlUtil.nodeMatches(respel, requestStatusTag)) {
                throw new CalFacadeException(CalFacadeException.badResponse);
            }

            fbel.setReqStatus(getElementContent(respel));

            if (respels.hasNext()) {
                respel = respels.next();

                if (XmlUtil.nodeMatches(respel, calendarDataTag)) {
                    String calData = getElementContent(respel);

                    Reader rdr = new StringReader(calData);
                    Icalendar ical = trans.fromIcal(null, rdr);

                    fbel.setCalData(ical.getEventInfo());
                } else if (XmlUtil.nodeMatches(respel, errorTag)) {
                    fbel.setDavError(respel.getFirstChild().getLocalName());
                } else if (XmlUtil.nodeMatches(respel, descriptionTag)) {
                    // XXX Not processed yet
                } else {
                    throw new CalFacadeException(CalFacadeException.badResponse);
                }
            }

            resp.addResponse(fbel);
        }
    } catch (Throwable t) {
        if (debug) {
            error(t);
        }

        resp.setException(t);
    }
}

From source file:autohit.creator.compiler.SimCompiler.java

/**
 *  Processes info section tags. //  w  w  w  .  j a  v  a 2s  . c o m
 */
private void processItem(Element en) throws Exception {
    String tempText;
    String name;
    //runtimeDebug("ENTER --- " + en.getTagName());
    name = en.getTagName().toLowerCase();
    NodeList itemTreeChildren;
    int idx;
    Node sNode;

    // Parse the token and call a handler
    if (name.charAt(0) == 'n') {
        if (name.charAt(1) == 'a') {
            //NAME
            tempText = getText(en.getFirstChild());
            if (tempText == null) {
                runtimeError("Empty <name> tag.");
            } else {
                ob.exec.name = tempText;
                runtimeDebug("TAG <name> name= " + ob.exec.name);
            }
            // optional uid attribute
            if (en.hasAttribute(ATTR_UID)) {
                ob.exec.uid = en.getAttribute(ATTR_UID);
                localname = ob.exec.uid;
                runtimeDebug("TAG <name> uid= " + ob.exec.uid);
            }
        } else {
            // NOTE - optional
            tempText = getText(en.getFirstChild());
            ob.exec.note = tempText;
        }
    } else if (name.charAt(0) == 'v') {
        // VERSION
        ob.exec.major = 0;
        try {
            if (en.hasAttribute(ATTR_VERSIONNUMBER)) {
                tempText = en.getAttribute(ATTR_VERSIONNUMBER);
                ob.exec.major = Integer.parseInt(tempText);
                runtimeDebug("TAG <version> num= " + ob.exec.major);
            } else {
                runtimeError("ERROR: TAG<version> Attr num not present.");
            }
        } catch (Exception e) {
            runtimeError("ERROR: TAG<version> Could not parse value for Attr num.");
        }

    } else if (name.charAt(0) == 'i') {
        if (name.charAt(1) == 'o') {
            // IO - Recurse with it's children.
            itemTreeChildren = en.getChildNodes();
            for (idx = 0; idx < itemTreeChildren.getLength(); idx++) {
                sNode = itemTreeChildren.item(idx);
                if (sNode instanceof Element) {
                    processItem((Element) sNode);
                }
            }
        } else {
            // INPUT - NOT SUPPORTED
        }

    } else if (name.charAt(0) == 'b') {
        // BUFFER - NOT SUPPORTED

    } else if (name.charAt(0) == 'o') {
        ob.exec.output = new NVPair();
        // OUTPUT - Specifies the output variable
        ob.exec.output.name = en.getAttribute(ATTR_NAME);
        if (en.hasAttribute(ATTR_TYPE)) {
            ob.exec.output.value = en.getAttribute(ATTR_TYPE);
        }

    } else {
        runtimeError("Software Detected Fault: creator.compiler.SimCompiler.processItem().  The textual token ["
                + en.getNodeName()
                + "] should have NOT reached this code. Check the XML DTD associated with the SimCompiler.");
        throw (new Exception("Software Detected Fault in creator.compiler.SimCompiler.processItem()."));
    }

    //DEBUG
    //runtimeDebug("EXIT --- " + en.getTagName());
}