Example usage for org.w3c.dom Element getElementsByTagNameNS

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

Introduction

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

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Returns a NodeList of all the descendant Elements with a given local name and namespace URI in document order.

Usage

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature//from  www .  j a  va  2s  . c o m
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java

private <T> Collection<? extends DisplayableValue<T>> parseEnumAllowedValues(XSType xsType) {
    if (xsType.isSimpleType()) {
        if (xsType.asSimpleType().isRestriction()) {
            XSRestrictionSimpleType restriction = xsType.asSimpleType().asRestriction();
            List<XSFacet> enumerations = restriction.getDeclaredFacets(XSFacet.FACET_ENUMERATION);
            List<DisplayableValueImpl<T>> enumValues = new ArrayList<DisplayableValueImpl<T>>(
                    enumerations.size());
            for (XSFacet facet : enumerations) {
                String value = facet.getValue().value;
                Element descriptionE = SchemaProcessorUtil.getAnnotationElement(facet.getAnnotation(),
                        SCHEMA_DOCUMENTATION);
                Element appInfo = SchemaProcessorUtil.getAnnotationElement(facet.getAnnotation(),
                        SCHEMA_APP_INFO);
                Element valueE = null;
                if (appInfo != null) {
                    NodeList list = appInfo.getElementsByTagNameNS(PrismConstants.A_LABEL.getNamespaceURI(),
                            PrismConstants.A_LABEL.getLocalPart());
                    if (list.getLength() != 0) {
                        valueE = (Element) list.item(0);
                    }//from ww w  .  ja va  2  s. c o  m
                }
                String label = null;
                if (valueE != null) {
                    label = valueE.getTextContent();
                } else {
                    label = value;
                }

                DisplayableValueImpl<T> edv = new DisplayableValueImpl(value, label,
                        descriptionE != null ? descriptionE.getTextContent() : null);

                enumValues.add(edv);

            }
            if (enumValues != null && !enumValues.isEmpty()) {
                return enumValues;
            }

        }
    }
    return null;
}

From source file:com.mtgi.analytics.aop.config.v11.BtHttpRequestsBeanDefinitionParser.java

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    //compile required constructor arguments from attributes and nested elements.  first up, event type.
    builder.addConstructorArg(element.getAttribute(ATT_EVENT_TYPE));

    //manager ID from enclosing tag, or ref attribute.
    String managerId = parserContext.isNested()
            ? (String) parserContext.getContainingBeanDefinition().getAttribute("id")
            : element.getAttribute(BtNamespaceConstants.ATT_TRACKING_MANAGER);
    builder.addConstructorArgReference(managerId);

    //parameter list to include in event data, if any.
    String paramList = element.getAttribute(ATT_PARAMETERS);
    builder.addConstructorArg(parseList(paramList));

    //parameter list to include in event name, if any
    String nameList = element.getAttribute(ATT_NAME_PARAMETERS);
    builder.addConstructorArg(parseList(nameList));

    //URI patterns, if any.  can be specified as attribute or nested elements.
    ArrayList<Pattern> accum = new ArrayList<Pattern>();
    if (element.hasAttribute(ATT_URI_PATTERN))
        accum.add(Pattern.compile(element.getAttribute(ATT_URI_PATTERN)));

    NodeList nl = element.getElementsByTagNameNS("*", ATT_URI_PATTERN);
    for (int i = 0; i < nl.getLength(); ++i) {
        Element e = (Element) nl.item(i);
        String pattern = e.getTextContent();
        if (StringUtils.hasText(pattern))
            accum.add(Pattern.compile(pattern));
    }//w  w  w. j a  v a 2s  .  com

    if (accum.isEmpty())
        builder.addConstructorArg(null);
    else
        builder.addConstructorArg(accum.toArray(new Pattern[accum.size()]));

    if (parserContext.isNested())
        parserContext.getReaderContext().registerWithGeneratedName(builder.getBeanDefinition());
}

From source file:org.jdal.beans.ServiceBeanDefinitionParser.java

/**
 * {@inheritDoc}/*from ww w.  j  a  v a 2s. c o m*/
 */
public AbstractBeanDefinition parse(Element element, ParserContext parserContext) {

    // default dao and service classes
    String daoClassName = JPA_DAO_CLASS_NAME;
    String serviceClassName = PERSISTENT_SERVICE_CLASS_NAME;
    String name = null;
    boolean declareService = false;

    if (element.hasAttribute(DAO_CLASS))
        daoClassName = element.getAttribute(DAO_CLASS);

    if (element.hasAttribute(SERVICE_CLASS)) {
        serviceClassName = element.getAttribute(SERVICE_CLASS);
        declareService = true;
    }

    if (element.hasAttribute(NAME))
        name = element.getAttribute(NAME);

    if (element.hasAttribute(ENTITY)) {
        String className = element.getAttribute(ENTITY);
        if (name == null) {
            name = StringUtils
                    .uncapitalize(StringUtils.substringAfterLast(className, PropertyUtils.PROPERTY_SEPARATOR));
        }
        parserContext.pushContainingComponent(
                new CompositeComponentDefinition(name, parserContext.extractSource(element)));

        // Dao
        BeanDefinitionBuilder daoBuilder = BeanDefinitionBuilder.genericBeanDefinition(daoClassName);
        NodeList nl = element.getElementsByTagNameNS(element.getNamespaceURI(), CRITERIA);
        if (nl.getLength() > 0) {
            ManagedMap<String, BeanReference> builders = new ManagedMap<String, BeanReference>(nl.getLength());
            for (int i = 0; i < nl.getLength(); i++) {
                Element e = (Element) nl.item(i);
                builders.put(e.getAttribute(NAME), new RuntimeBeanReference(e.getAttribute(BUILDER)));
            }
            daoBuilder.addPropertyValue(CRITERIA_BUILDER_MAP, builders);
        }

        daoBuilder.addConstructorArgValue(ClassUtils.resolveClassName(className, null));
        daoBuilder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        String daoBeanName;

        if (declareService) {
            // use dao suffix
            daoBeanName = name + DAO_SUFFIX;
            registerBeanDefinition(parserContext, daoBuilder, daoBeanName);

            // register service wrapper
            String serviceBeanName = name + SERVICE_SUFFIX;
            BeanDefinitionBuilder serviceBuilder = BeanDefinitionBuilder
                    .genericBeanDefinition(serviceClassName);
            serviceBuilder.addPropertyReference("dao", daoBeanName);
            registerBeanDefinition(parserContext, serviceBuilder, serviceBeanName);
        } else {
            // use service suffix for dao and declare an alias with dao suffix for compatibility with older api.
            daoBeanName = name + SERVICE_SUFFIX;
            String[] aliases = new String[] { name + DAO_SUFFIX };
            BeanComponentDefinition bcd = new BeanComponentDefinition(daoBuilder.getBeanDefinition(),
                    daoBeanName, aliases);
            parserContext.registerBeanComponent(bcd);
        }

        parserContext.popAndRegisterContainingComponent();
    }

    return null;
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaPostProcessor.java

private <T> Collection<? extends DisplayableValue<T>> parseEnumAllowedValues(QName typeName,
        ComplexTypeDefinition ctd, XSType xsType) {
    if (xsType.isSimpleType()) {
        if (xsType.asSimpleType().isRestriction()) {
            XSRestrictionSimpleType restriction = xsType.asSimpleType().asRestriction();
            List<XSFacet> enumerations = restriction.getDeclaredFacets(XSFacet.FACET_ENUMERATION);
            List<DisplayableValueImpl<T>> enumValues = new ArrayList<>(enumerations.size());
            for (XSFacet facet : enumerations) {
                String value = facet.getValue().value;
                Element descriptionE = SchemaProcessorUtil.getAnnotationElement(facet.getAnnotation(),
                        SCHEMA_DOCUMENTATION);
                Element appInfo = SchemaProcessorUtil.getAnnotationElement(facet.getAnnotation(),
                        SCHEMA_APP_INFO);
                Element valueE = null;
                if (appInfo != null) {
                    NodeList list = appInfo.getElementsByTagNameNS(PrismConstants.A_LABEL.getNamespaceURI(),
                            PrismConstants.A_LABEL.getLocalPart());
                    if (list.getLength() != 0) {
                        valueE = (Element) list.item(0);
                    }/*w w w.ja v  a 2s.  co m*/
                }
                String label = null;
                if (valueE != null) {
                    label = valueE.getTextContent();
                } else {
                    label = value;
                }
                DisplayableValueImpl<T> edv = null;
                Class compileTimeClass = prismContext.getSchemaRegistry().getCompileTimeClass(typeName);
                if (ctd != null && !ctd.isRuntimeSchema() && compileTimeClass != null) {

                    String fieldName = null;
                    for (Field field : compileTimeClass.getDeclaredFields()) {
                        XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
                        if (xmlEnumValue != null && xmlEnumValue.value() != null
                                && xmlEnumValue.value().equals(value)) {
                            fieldName = field.getName();
                        }

                    }
                    if (fieldName != null) {
                        T enumValue = (T) Enum.valueOf((Class<Enum>) compileTimeClass, fieldName);
                        edv = new DisplayableValueImpl(enumValue, label,
                                descriptionE != null ? descriptionE.getTextContent() : null);
                    } else {
                        edv = new DisplayableValueImpl(value, label,
                                descriptionE != null ? descriptionE.getTextContent() : null);
                    }

                } else {
                    edv = new DisplayableValueImpl(value, label,
                            descriptionE != null ? descriptionE.getTextContent() : null);
                }
                enumValues.add(edv);

            }
            if (enumValues != null && !enumValues.isEmpty()) {
                return enumValues;
            }

        }
    }
    return null;
}

From source file:io.personium.core.model.impl.fs.DavCmpFsImpl.java

/**
 * load the info from FS for this Dav resouce.
 *//*from w w w .j  a  va2s. co m*/
public final void load() {
    this.metaFile.load();

    /*
     * Analyze JSON Object, and set metadata such as ACL.
     */
    this.name = fsDir.getName();
    this.acl = this.translateAcl(this.metaFile.getAcl());

    @SuppressWarnings("unchecked")
    Map<String, String> props = (Map<String, String>) this.metaFile.getProperties();
    if (props != null) {
        for (Map.Entry<String, String> entry : props.entrySet()) {
            String key = entry.getKey();
            String val = entry.getValue();
            int idx = key.indexOf("@");
            String elementName = key.substring(0, idx);
            String namespace = key.substring(idx + 1);
            QName keyQName = new QName(namespace, elementName);

            Element element = parseProp(val);
            String elementNameSpace = element.getNamespaceURI();
            // ownerRepresentativeAccounts???
            if (Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNTS.equals(keyQName)) {
                NodeList accountNodeList = element.getElementsByTagNameNS(elementNameSpace,
                        Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNT.getLocalPart());
                for (int i = 0; i < accountNodeList.getLength(); i++) {
                    this.ownerRepresentativeAccounts.add(accountNodeList.item(i).getTextContent().trim());
                }
            }
        }
    }
}

From source file:com.fujitsu.dc.core.model.impl.es.DavCmpEsImpl.java

/**
 * ???.//from   w w w  . j av a2  s.co  m
 */
@SuppressWarnings("unchecked")
public final void load() {
    DcGetResponse res = getNode();
    if (res == null) {
        // Box???id????Dav????????
        throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND;
    }
    this.version = res.version();
    this.davNode = DavNode.createFromJsonString(res.getId(), res.sourceAsString());
    if (this.davNode != null) {
        // Map<String, Object> aclObj = (Map<String, Object>) json.get("acl");
        // TODO JSONParse?????. JSON Parse?????????.
        String jsonStr = res.sourceAsString();
        JSONParser parser = new JSONParser();
        try {
            JSONObject jo = (JSONObject) parser.parse(jsonStr);
            JSONObject aclObj = (JSONObject) jo.get(DavNode.KEY_ACL);
            if (aclObj != null) {
                log.debug(aclObj.toJSONString());
                // principal?href ? ID__id?URL???
                // base:xml?
                String baseUrlStr = createBaseUrlStr();
                roleIdToName(aclObj.get(KEY_ACE), baseUrlStr);

                // ConfidentialLevel???
                this.confidentialLevel = (String) aclObj.get(KEY_REQUIRE_SCHEMA_AUTHZ);

                this.acl = Acl.fromJson(aclObj.toJSONString());
                this.acl.setBase(baseUrlStr);
                log.debug(this.acl.toJSON());
            }

            Map<String, String> props = (Map<String, String>) jo.get(DavNode.KEY_PROPS);
            if (props != null) {
                for (Map.Entry<String, String> entry : props.entrySet()) {
                    String key = entry.getKey();
                    String val = entry.getValue();
                    int idx = key.indexOf("@");
                    String elementName = key.substring(0, idx);
                    String namespace = key.substring(idx + 1);
                    QName keyQName = new QName(namespace, elementName);

                    Element element = parseProp(val);
                    String elementNameSpace = element.getNamespaceURI();
                    // ownerRepresentativeAccounts???
                    if (Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNTS.equals(keyQName)) {
                        NodeList accountNodeList = element.getElementsByTagNameNS(elementNameSpace,
                                Key.PROP_KEY_OWNER_REPRESENTIVE_ACCOUNT.getLocalPart());
                        for (int i = 0; i < accountNodeList.getLength(); i++) {
                            this.ownerRepresentativeAccounts
                                    .add(accountNodeList.item(i).getTextContent().trim());
                        }
                    }
                }
            }
        } catch (ParseException e) {
            // ES?JSON???
            throw DcCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(e);
        }
    }
}

From source file:org.jdal.beans.TableBeanDefinitionParser.java

/**
 * {@inheritDoc}//from ww  w . j a  v a 2  s  .c  o m
 */
@SuppressWarnings("rawtypes")
public BeanDefinition parse(Element element, ParserContext parserContext) {
    // Defaults
    String entity = null;

    if (element.hasAttribute(ENTITY))
        entity = element.getAttribute(ENTITY);

    String name = StringUtils.uncapitalize(StringUtils.substringAfterLast(entity, "."));

    if (element.hasAttribute(ID))
        name = element.getAttribute(ID);

    parserContext.pushContainingComponent(
            new CompositeComponentDefinition(name, parserContext.extractSource(element)));

    // Bean names
    String tableModelBeanName = name + LIST_TABLE_MODEL_SUFFIX;
    String tablePanelBeanName = name + TABLE_PANEL_SUFFIX;
    String pageableTableBeanName = name + PAGEABLE_TABLE_SUFFIX;
    String dataSource = name + SERVICE_SUFFIX;
    String paginator = PAGINATOR_VIEW;
    String editor = name + EDITOR_SUFFIX;
    String actions = DefaultsBeanDefinitionParser.DEFAULT_TABLE_ACTIONS;
    String guiFactory = DefaultsBeanDefinitionParser.DEFAULT_GUI_FACTORY;
    String scope = BeanDefinition.SCOPE_PROTOTYPE;

    if (element.hasAttribute(SERVICE_ATTRIBUTE))
        dataSource = element.getAttribute(SERVICE_ATTRIBUTE);

    if (element.hasAttribute(PAGINATOR))
        paginator = element.getAttribute(PAGINATOR);

    if (element.hasAttribute(ACTIONS))
        actions = element.getAttribute(ACTIONS);

    if (element.hasAttribute(GUI_FACTORY))
        guiFactory = element.getAttribute(GUI_FACTORY);

    if (element.hasAttribute(EDITOR))
        editor = element.getAttribute(EDITOR);

    if (element.hasAttribute(SCOPE))
        scope = element.getAttribute(SCOPE);

    // create ListTableModel
    BeanDefinitionBuilder bdb = BeanDefinitionBuilder.genericBeanDefinition(ListTableModel.class);
    bdb.setScope(scope);
    bdb.addPropertyValue("modelClass", entity);
    NodeList nl = element.getElementsByTagNameNS(element.getNamespaceURI(), COLUMNS);

    if (nl.getLength() > 0) {
        List columns = parserContext.getDelegate().parseListElement((Element) nl.item(0),
                bdb.getRawBeanDefinition());
        bdb.addPropertyValue(COLUMNS, columns);
    }
    registerBeanDefinition(element, parserContext, tableModelBeanName, bdb);

    // create PageableTable
    bdb = BeanDefinitionBuilder.genericBeanDefinition(PageableTable.class);
    bdb.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    bdb.addPropertyReference(DATA_SOURCE, dataSource);
    bdb.addPropertyReference(PAGINATOR_VIEW, paginator);
    bdb.addPropertyReference(TABLE_MODEL, tableModelBeanName);
    bdb.addPropertyValue(NAME, pageableTableBeanName);

    if (element.hasAttribute(TABLE_SERVICE))
        bdb.addPropertyReference(Conventions.attributeNameToPropertyName(TABLE_SERVICE),
                element.getAttribute(TABLE_SERVICE));

    if (element.hasAttribute(FILTER))
        bdb.addPropertyReference(FILTER, element.getAttribute(FILTER));

    if (element.hasAttribute(SHOW_MENU))
        bdb.addPropertyValue(Conventions.attributeNameToPropertyName(SHOW_MENU),
                element.getAttribute(SHOW_MENU));

    if (element.hasAttribute(MESSAGE_SOURCE))
        bdb.addPropertyReference(MESSAGE_SOURCE, element.getAttribute(MESSAGE_SOURCE));

    registerBeanDefinition(element, parserContext, pageableTableBeanName, bdb);

    // create TablePanel
    String tablePanelClassName = "org.jdal.swing.table.TablePanel";
    if (element.hasAttribute(TABLE_PANEL_CLASS))
        tablePanelClassName = element.getAttribute(TABLE_PANEL_CLASS);

    bdb = BeanDefinitionBuilder.genericBeanDefinition(tablePanelClassName);
    bdb.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    bdb.addPropertyReference(TABLE, pageableTableBeanName);
    bdb.addPropertyReference(GUI_FACTORY, guiFactory);
    bdb.addPropertyValue(EDITOR_NAME, editor);
    bdb.addPropertyReference(PERSISTENT_SERVICE, dataSource);

    if (element.hasAttribute(FILTER_VIEW))
        bdb.addPropertyReference(Conventions.attributeNameToPropertyName(FILTER_VIEW),
                element.getAttribute(FILTER_VIEW));

    if (!element.hasAttribute(USE_ACTIONS) || "true".equals(element.getAttribute(USE_ACTIONS)))
        bdb.addPropertyReference(ACTIONS, actions);

    registerBeanDefinition(element, parserContext, tablePanelBeanName, bdb);

    parserContext.popAndRegisterContainingComponent();

    return null;
}

From source file:edu.harvard.i2b2.eclipse.plugins.workplace.views.find.TreeNode.java

private XmlValueType updateWorkXml(String newName) {
    if (this.getData().getWorkXml() == null)
        return null;
    if ((this.getData().getWorkXmlI2B2Type().equals("CONCEPT"))) {
        Element rootElement = this.getData().getWorkXml().getAny().get(0);
        NodeList nameElements = rootElement.getElementsByTagName("name");
        nameElements.item(0).setTextContent(newName);

        NodeList synonymElements = rootElement.getElementsByTagName("synonym_cd");
        if (synonymElements.item(0) != null)
            synonymElements.item(0).setTextContent("Y");
    } else if ((this.getData().getWorkXmlI2B2Type().equals("PATIENT_COLL"))) {
        Element rootElement = this.getData().getWorkXml().getAny().get(0);
        NodeList descriptionElements = rootElement.getElementsByTagName("description");
        descriptionElements.item(0).setTextContent(newName);
    } else if ((this.getData().getWorkXmlI2B2Type().equals("ENCOUNTER_COLL"))) {
        Element rootElement = this.getData().getWorkXml().getAny().get(0);
        NodeList descriptionElements = rootElement.getElementsByTagName("description");
        descriptionElements.item(0).setTextContent(newName);
    } else {/* w w w .  jav  a  2  s .co m*/
        Element rootElement = this.getData().getWorkXml().getAny().get(0);
        NodeList nameElements = rootElement.getElementsByTagName("name");
        // Group templates dont have tag 'name'
        if (nameElements.getLength() == 0) {
            nameElements = rootElement.getElementsByTagNameNS("*", "panel");
            if (nameElements.getLength() == 0) {
                nameElements = rootElement.getElementsByTagName("query_name");
                if (nameElements.getLength() == 0) {
                    // if we get to here and no name has been found then its a PDO.
                    // return generically -- change to obs or event etc one level up.
                    return this.getData().getWorkXml();
                }
                // query_name
                else {
                    nameElements.item(0).setTextContent(newName);
                }
            }
            //panel / template name
            else {
                nameElements.item(0).getAttributes().getNamedItem("name").setNodeValue(newName);
            }
        }
        // prev query name
        else
            nameElements.item(0).setTextContent(newName);
    }

    return this.getData().getWorkXml();
}