Example usage for org.w3c.dom Element hasAttribute

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

Introduction

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

Prototype

public boolean hasAttribute(String name);

Source Link

Document

Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Usage

From source file:org.springframework.integration.aws.sqs.config.AmazonSQSInboundChannelAdapterParser.java

@Override
protected BeanMetadataElement parseSource(Element element, ParserContext parserContext) {
    String awsCredentials = registerAmazonWSCredentials(element, parserContext);
    //Mandated at xsd level, so has to be present
    String sqsQueue = element.getAttribute(SQS_QUEUE);
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(AmazonSQSMessageSource.class)
            .addConstructorArgReference(awsCredentials).addConstructorArgValue(sqsQueue);
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, IS_TRANSACTIONAL);
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, MAX_REDELIVERY_ATTEMPTS);
    IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, SQS_OPERATIONS);
    String messageTransformerRef = element.getAttribute(MESSAGE_TRANSFORMER);
    boolean hasMessageTransformerRef = StringUtils.hasText(messageTransformerRef);

    boolean hasSnsHeaderPrefix = false;
    String snsNotificationAttribute = element.getAttribute(CHECK_SNS_NOTIFICATION);
    boolean checkSnsNotification = StringUtils.hasText(snsNotificationAttribute);
    String snsHeaderPrefix = null;
    if (checkSnsNotification) {
        snsHeaderPrefix = element.getAttribute(SNS_HEADER_PREFIX);
        hasSnsHeaderPrefix = StringUtils.hasText(snsHeaderPrefix);
    }//ww w  .  j ava 2s.  co m

    if (!element.hasAttribute(SQS_OPERATIONS)) {
        BeanDefinitionBuilder sqsOperationsBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(AmazonSQSOperationsImpl.class)
                .addConstructorArgReference(awsCredentials);
        if (hasMessageTransformerRef) {
            sqsOperationsBuilder.addPropertyReference("messageTransformer", messageTransformerRef);
        }

        if (checkSnsNotification) {
            sqsOperationsBuilder.addPropertyValue("checkSnsNotification", true);
            if (hasSnsHeaderPrefix) {
                sqsOperationsBuilder.addPropertyValue("snsHeaderPrefix", snsHeaderPrefix);
            }
        }

        //sqs_operations attribute not defined, register the default one
        String operationsBean = BeanDefinitionReaderUtils.registerWithGeneratedName(
                sqsOperationsBuilder.getBeanDefinition(), parserContext.getRegistry());
        builder.addPropertyReference("sqsOperations", operationsBean);
    } else {
        if (hasMessageTransformerRef) {
            //This means, we have a reference to both sqs operations and message transformer provided
            throw new BeanDefinitionStoreException(
                    "Both the attributes,  \"sqs-operations\" and \"message-transformer\" are "
                            + "not supported together. Consider injecting the messageTransformer in the sqsOperation's bean definition"
                            + " and provide \"sqs-operations\" attribute only");
        }
        if (checkSnsNotification) {
            logger.warn("check-sns-notification and sns-header-prefix attributes are supported"
                    + " only when default implementation of sqs operations is used");
        }

    }
    return builder.getBeanDefinition();
}

From source file:org.springframework.roo.addon.roobot.eclipse.client.AddOnRooBotEclipseOperationsImpl.java

private boolean verifyRepository(String repoUrl) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc = null;//from w w  w .j  a va 2s .c  om
    try {
        URL obrUrl = null;
        obrUrl = new URL(repoUrl);
        DocumentBuilder db = dbf.newDocumentBuilder();
        if (obrUrl.toExternalForm().endsWith(".zip")) {
            ZipInputStream zip = new ZipInputStream(obrUrl.openStream());
            zip.getNextEntry();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int length = -1;
            while (zip.available() > 0) {
                length = zip.read(buffer, 0, 8192);
                if (length > 0) {
                    baos.write(buffer, 0, length);
                }
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            doc = db.parse(bais);
        } else {
            doc = db.parse(obrUrl.openStream());
        }
        Validate.notNull(doc, "RooBot was unable to parse the repository document of this add-on");
        for (Element resource : XmlUtils.findElements("resource", doc.getDocumentElement())) {
            if (resource.hasAttribute("uri")) {
                if (!resource.getAttribute("uri").startsWith("httppgp")) {
                    log.warning("Sorry, the resource " + resource.getAttribute("uri")
                            + " does not follow HTTPPGP conventions mangraded by Spring Roo so the OBR file at "
                            + repoUrl + " is unacceptable at this time");
                    return false;
                }
            }
        }
        doc = null;
    } catch (Exception e) {
        throw new IllegalStateException("RooBot was unable to parse the repository document of this add-on", e);
    }
    return true;
}

From source file:org.springmodules.validation.bean.conf.loader.xml.DefaultXmlBeanValidationConfigurationLoader.java

/**
 * Handles the given <property> element and updates the given bean validation configuration with the property
 * validation rules.//  ww  w . j a  va  2s.co m
 *
 * @param propertyDefinition The <property> element.
 * @param clazz The validated class.
 * @param configuration The bean validation configuration to update.
 */
protected void handlePropertyDefinition(Element propertyDefinition, Class clazz,
        MutableBeanValidationConfiguration configuration) {
    String propertyName = propertyDefinition.getAttribute(NAME_ATTR);
    if (propertyName == null) {
        logger.error("Could not parse property element. Missing 'name' attribute");
        throw new ValidationConfigurationException(
                "Could not parse property element. Missing 'name' attribute");
    }

    PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(clazz, propertyName);
    if (propertyDescriptor == null) {
        logger.error("Property '" + propertyName + "' does not exist in class '" + clazz.getName() + "'");
    }

    if (propertyDefinition.hasAttribute(CASCADE_ATTR)
            && "true".equals(propertyDefinition.getAttribute(CASCADE_ATTR))) {
        CascadeValidation cascadeValidation = new CascadeValidation(propertyName);
        if (propertyDefinition.hasAttribute(CASCADE_CONDITION_ATTR)) {
            String conditionExpression = propertyDefinition.getAttribute(CASCADE_CONDITION_ATTR);
            cascadeValidation.setApplicabilityCondition(conditionExpressionParser.parse(conditionExpression));
        }
        configuration.addCascadeValidation(cascadeValidation);
    }

    NodeList nodes = propertyDefinition.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        Element ruleDefinition = (Element) node;
        PropertyValidationElementHandler handler = handlerRegistry.findPropertyHandler(ruleDefinition, clazz,
                propertyDescriptor);
        if (handler == null) {
            logger.error("Could not handle element '" + ruleDefinition.getTagName()
                    + "'. Please make sure the proper validation rule definition handler is registered");
            throw new ValidationConfigurationException(
                    "Could not handle element '" + ruleDefinition.getTagName() + "'");
        }
        handler.handle(ruleDefinition, propertyName, configuration);
    }
}

From source file:org.stanwood.media.store.mp4.atomicparsley.AtomicParsleyOutputParser.java

private IAtom parseAtom(Element node) throws MP4Exception {
    String name = node.getAttribute("name"); //$NON-NLS-1$
    if (name.length() == 0) {
        throw new MP4Exception(Messages.getString("AtomicParsleyOutputParser.UnableGetNameOfAtom")); //$NON-NLS-1$
    }/*from w  w  w .  j  av  a2 s.  co m*/
    String rDnsDomain = node.getAttribute("reverseDNSdomain"); //$NON-NLS-1$
    String rDnsName = node.getAttribute("reverseDNSname"); //$NON-NLS-1$
    MP4AtomKey key;
    if (rDnsDomain != null && rDnsDomain.length() > 0 && rDnsName != null && rDnsName.length() > 0) {
        key = MP4AtomKey.fromRDNS(rDnsName, rDnsDomain);
    } else {
        key = MP4AtomKey.fromKey(name);
    }
    if (key == null) {
        log.warn(MessageFormat.format(Messages.getString("AtomicParsleyOutputParser.UnableFindAtom"), name, //$NON-NLS-1$
                rDnsDomain, rDnsName));
        return null;
    }
    if (node.getNodeName().equals("atomString")) { //$NON-NLS-1$
        return new APAtomString(key, node.getTextContent());
    } else if (node.getNodeName().equals("atomRange")) { //$NON-NLS-1$
        short count = (short) parseIntAttribute(node, name, "count"); //$NON-NLS-1$
        short max = 0;
        if (node.hasAttribute("max")) { //$NON-NLS-1$
            max = (short) parseIntAttribute(node, name, "max"); //$NON-NLS-1$
        }
        return new APAtomRange(key, count, max);
    } else if (node.getNodeName().equals("atomNumber")) { //$NON-NLS-1$
        return new APAtomNumber(key, parseLongAttribute(node, name, "value")); //$NON-NLS-1$
    } else if (node.getNodeName().equals("atomBoolean")) { //$NON-NLS-1$
        String value = node.getAttribute("value"); //$NON-NLS-1$
        if (value.equals("1") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("true")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            return new APAtomBoolean(key, true);
        } else {
            return new APAtomBoolean(key, false);
        }
    } else if (node.getNodeName().equals("atomArtwork")) { //$NON-NLS-1$
        return new APAtomArtworkSummary(key, 1);
    }
    throw new MP4Exception(MessageFormat
            .format(Messages.getString("AtomicParsleyOutputParser.UnsupportedAtomNode"), node.getNodeName())); //$NON-NLS-1$
}

From source file:org.ut.medsavant.annotation.format.AnnotationFormatter.java

public String getValue(Pattern constraint, Element e, String a) throws IllegalArgumentException {

    if (!e.hasAttribute(a)) {
        return null;
    }/*from   w ww .j a  v  a2  s  .  c  om*/
    String val = e.getAttribute(a);
    return getValue(constraint, a, val);

}

From source file:org.wandora.modules.ModuleManager.java

/**
 * Parses a single param element and returns its value. Handles all the
 * different cases of how a param elements value can be determined.
 * /*ww  w.j av a  2s . c  om*/
 * @param e The xml param element.
 * @return The value of the parameter.
 */
public Object parseXMLParamElement(Element e)
        throws ReflectiveOperationException, IllegalArgumentException, ScriptException {
    String instance = e.getAttribute("instance");
    if (instance != null && instance.length() > 0) {
        Class cls = Class.forName(instance);
        HashMap<String, Object> params = parseXMLOptionsElement(e);
        if (!params.isEmpty()) {
            Collection<Object> constructorParams = params.values();
            Constructor[] cs = cls.getConstructors();
            ConstructorLoop: for (int i = 0; i < cs.length; i++) {
                Constructor c = cs[i];
                Class[] paramTypes = c.getParameterTypes();
                if (paramTypes.length != constructorParams.size())
                    continue;

                int j = -1;
                for (Object o : constructorParams) {
                    j++;
                    if (o == null) {
                        if (!paramTypes[j].isPrimitive())
                            continue;
                        else
                            continue ConstructorLoop;
                    }

                    if (paramTypes[j].isPrimitive()) {
                        if (paramTypes[j] == int.class) {
                            if (o.getClass() != Integer.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == long.class) {
                            if (o.getClass() != Long.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == double.class) {
                            if (o.getClass() != Double.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == float.class) {
                            if (o.getClass() != Float.class)
                                continue ConstructorLoop;
                        } else if (paramTypes[j] == byte.class) {
                            if (o.getClass() != Byte.class)
                                continue ConstructorLoop;
                        } else
                            continue ConstructorLoop; //did we forget some primitive type?
                    } else if (!o.getClass().isAssignableFrom(paramTypes[j]))
                        continue ConstructorLoop;
                }

                return c.newInstance(constructorParams.toArray());
            }
            throw new NoSuchMethodException(
                    "Couldn't find a constructor that matches parameters parsed from XML.");
        } else {
            return cls.newInstance();
        }
    }

    String clas = e.getAttribute("class");
    if (clas != null && clas.length() > 0) {
        Class cls = Class.forName(clas);
        return cls;
    }

    if (e.hasAttribute("null"))
        return null;

    if (e.hasAttribute("script")) {
        String engine = e.getAttribute("script");
        if (engine.length() == 0 || engine.equalsIgnoreCase("default"))
            engine = ScriptManager.getDefaultScriptEngine();
        ScriptManager scriptManager = new ScriptManager();
        ScriptEngine scriptEngine = scriptManager.getScriptEngine(engine);
        scriptEngine.put("moduleManager", this);
        scriptEngine.put("element", e);

        try {
            String script = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim();
            return scriptManager.executeScript(script, scriptEngine);
        } catch (XPathExpressionException xpee) {
            throw new RuntimeException(xpee);
        }
    }

    if (e.hasAttribute("module")) {
        String moduleName = e.getAttribute("module").trim();
        return new ModuleDelegate(this, moduleName);
    }

    try {
        String value = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim();
        return replaceVariables(value, variables);
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException(xpee);
    }
}

From source file:org.wikipedia.vlsergey.secretary.jwpf.actions.AbstractQueryRevisionsAction.java

protected ParsedRevision parseRevision(Page page, Element revisionElement) throws ProcessException {
    ParsedRevision revisionImpl = new ParsedRevision(page);

    if (StringUtils.isNotEmpty(revisionElement.getAttribute("parsetree"))) {
        revisionImpl.setXml(revisionElement.getAttribute("parsetree"));
    }//from ww  w.j  a v  a  2 s.  co  m

    if (properties.contains(RevisionPropery.COMMENT))
        revisionImpl.setComment(revisionElement.getAttribute("comment"));

    if (properties.contains(RevisionPropery.CONTENT)) {
        revisionImpl.setContent(getText(revisionElement));
    }

    if (properties.contains(RevisionPropery.FLAGS)) {
        revisionImpl.setAnon(revisionElement.hasAttribute("anon"));
        revisionImpl.setBot(revisionElement.hasAttribute("bot"));
        revisionImpl.setMinor(revisionElement.hasAttribute("minor"));
    }

    if (properties.contains(RevisionPropery.IDS)) {
        revisionImpl.setId(new Long(revisionElement.getAttribute("revid")));
    }

    if (properties.contains(RevisionPropery.SIZE) && revisionElement.hasAttribute("size")) {
        revisionImpl.setSize(new Long(revisionElement.getAttribute("size")));
    }

    if (properties.contains(RevisionPropery.TIMESTAMP)) {
        try {
            String timestamp = revisionElement.getAttribute("timestamp");
            Date date = parseDate(timestamp);
            revisionImpl.setTimestamp(date);
        } catch (ParseException exc) {
            throw new ProcessException(exc.getMessage(), exc);
        }
    }

    if (properties.contains(RevisionPropery.USER)) {
        revisionImpl.setUser(revisionElement.getAttribute("user"));
    }

    if (properties.contains(RevisionPropery.FLAGGED)) {
        for (Element revElement : new ListAdapter<Element>(revisionElement.getElementsByTagName("flagged"))) {
            RevisionFlagged revisionFlagged = parseRevisionFlagged(revisionImpl, revElement);

            if (revisionImpl.getFlagged() == null) {
                revisionImpl.setFlagged(new ArrayList<RevisionFlagged>(1));
            }
            revisionImpl.getFlagged().add(revisionFlagged);
        }
    }

    return revisionImpl;
}

From source file:org.wikipedia.vlsergey.secretary.jwpf.actions.AbstractQueryRevisionsAction.java

protected RevisionFlagged parseRevisionFlagged(ParsedRevision revision, Element flaggedElement) {
    /*/* ww  w  .j  av  a  2 s  .  co  m*/
     * <flagged user="Klip game" timestamp="2012-05-04T17:01:13Z" level="0"
     * level_text="stable">
     * 
     * <tags accuracy="1" />
     * 
     * </flagged>
     */
    RevisionFlagged revisionFlagged = new RevisionFlagged();

    if (flaggedElement.hasAttribute("user")) {
        revisionFlagged.setUser(flaggedElement.getAttribute("user"));
    }

    if (flaggedElement.hasAttribute("timestamp")) {
        try {
            String timestamp = flaggedElement.getAttribute("timestamp");
            Date date = parseDate(timestamp);
            revisionFlagged.setTimestamp(date);
        } catch (ParseException exc) {
            throw new ProcessException(exc.getMessage(), exc);
        }
    }

    if (flaggedElement.hasAttribute("level")) {
        try {
            String level = flaggedElement.getAttribute("level");
            Integer integer = Integer.valueOf(level);
            revisionFlagged.setLevel(integer);
        } catch (NumberFormatException exc) {
            throw new ProcessException(exc.getMessage(), exc);
        }
    }

    if (flaggedElement.hasAttribute("level_text")) {
        revisionFlagged.setLevelText(flaggedElement.getAttribute("level_text"));
    }

    List<Integer> tagsAccuracy = new ArrayList<Integer>(1);
    for (Element tagsElement : new ListAdapter<Element>(flaggedElement.getElementsByTagName("tags"))) {
        if (tagsElement.hasAttribute("accuracy")) {
            try {
                String accuracy = tagsElement.getAttribute("accuracy");
                Integer integer = Integer.valueOf(accuracy);
                tagsAccuracy.add(integer);
            } catch (NumberFormatException exc) {
                throw new ProcessException(exc.getMessage(), exc);
            }
        }
    }
    revisionFlagged.setTagsAccuracy(tagsAccuracy);

    return revisionFlagged;
}

From source file:org.wso2.carbon.apimgt.migration.client.MigrateExistingDefaultAPIs.java

/**
 * This method is used to migrate synapse files
 * This changes the synapse api and add the new handlers
 *
 * @throws APIMigrationException//from w w  w . jav a2 s  . c  o m
 */
@Override
public void defaultAPISynapseMigration() throws APIMigrationException {
    String repository = CarbonUtils.getCarbonRepository();
    String tenantRepository = CarbonUtils.getCarbonTenantsDirPath();
    for (Tenant tenant : tenantsArray) {
        log.debug("Start synapseAPIMigration for tenant " + tenant.getId() + "(" + tenant.getDomain() + ")");
        String apiFilePath;
        if (tenant.getId() != MultitenantConstants.SUPER_TENANT_ID) {
            apiFilePath = tenantRepository + "/" + tenant.getId() + "/synapse-configs/default/api";
        } else {
            apiFilePath = repository + "synapse-configs/default/api";
        }
        File APIFiles = new File(apiFilePath);
        File[] synapseFiles = APIFiles.listFiles();

        if (synapseFiles == null) {
            log.debug("No api folder " + apiFilePath + " exists for tenant " + tenant.getId() + "("
                    + tenant.getDomain() + ")");
            continue;
        }

        for (File synapseFile : synapseFiles) {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            docFactory.setNamespaceAware(true);

            try {
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(synapseFile);
                doc.getDocumentElement().normalize();
                Element rootElement = doc.getDocumentElement();

                if (Constants.SYNAPSE_API_ROOT_ELEMENT.equals(rootElement.getNodeName())
                        && !rootElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION)) {
                    ResourceUtil.updateSynapseAPI(doc, synapseFile);
                }
            } catch (ParserConfigurationException e) {
                log.error("Parsing exception encountered for " + synapseFile.getAbsolutePath(), e);
            } catch (SAXException e) {
                log.error("SAX exception encountered for " + synapseFile.getAbsolutePath(), e);
            } catch (IOException e) {
                log.error("IO exception encountered for " + synapseFile.getAbsolutePath(), e);
            } catch (APIMigrationException e) {
                log.error("Updating synapse file failed for " + synapseFile.getAbsolutePath(), e);
            }
        }
        log.debug("End synapseAPIMigration for tenant " + tenant.getId() + "(" + tenant.getDomain() + ")");
    }
}

From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom16to17.java

/**
 * This method is used to migrate synapse files
 * This changes the synapse api and add the new handlers
 *
 * @throws APIMigrationException//  w  ww. ja v  a2 s.  co m
 */

void synapseAPIMigration() {
    String repository = CarbonUtils.getCarbonRepository();
    String tenantRepository = CarbonUtils.getCarbonTenantsDirPath();
    for (Tenant tenant : tenantsArray) {
        log.debug("Start synapseAPIMigration for tenant " + tenant.getId() + "(" + tenant.getDomain() + ")");
        String apiFilePath;
        if (tenant.getId() != MultitenantConstants.SUPER_TENANT_ID) {
            apiFilePath = tenantRepository + "/" + tenant.getId() + "/synapse-configs/default/api";
        } else {
            apiFilePath = repository + "synapse-configs/default/api";
        }
        File APIFiles = new File(apiFilePath);
        File[] synapseFiles = APIFiles.listFiles();

        if (synapseFiles == null) {
            log.debug("No api folder " + apiFilePath + " exists for tenant " + tenant.getId() + "("
                    + tenant.getDomain() + ")");
            continue;
        }

        for (File synapseFile : synapseFiles) {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            docFactory.setNamespaceAware(true);

            try {
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(synapseFile);

                doc.getDocumentElement().normalize();

                Element rootElement = doc.getDocumentElement();

                if (Constants.SYNAPSE_API_ROOT_ELEMENT.equals(rootElement.getNodeName())
                        && rootElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_VERSION)) {
                    SynapseMigration.modifyGoogleAnalyticsTrackingHandler(synapseFile, doc);
                }

            } catch (ParserConfigurationException e) {
                log.error("Parsing exception encountered for " + synapseFile.getAbsolutePath(), e);
            } catch (SAXException e) {
                log.error("SAX exception encountered for " + synapseFile.getAbsolutePath(), e);
            } catch (IOException e) {
                log.error("IO exception encountered for " + synapseFile.getAbsolutePath(), e);
            } catch (XPathExpressionException e) {
                log.error("XPathExpression exception encountered for " + synapseFile.getAbsolutePath(), e);
            } catch (TransformerException e) {
                log.error("Transformer exception encountered for " + synapseFile.getAbsolutePath(), e);
            }
        }

        log.debug("End synapseAPIMigration for tenant " + tenant.getId() + "(" + tenant.getDomain() + ")");
    }
}