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:eap.config.ConfigBeanDefinitionParser.java

/**
 * Parses the {@code pointcut} or {@code pointcut-ref} attributes of the supplied
 * {@link Element} and add a {@code pointcut} property as appropriate. Generates a
 * {@link org.springframework.beans.factory.config.BeanDefinition} for the pointcut if  necessary
 * and returns its bean name, otherwise returns the bean name of the referred pointcut.
 *///from  ww  w  . jav  a2  s  .co  m
private Object parsePointcutProperty(Element element, ParserContext parserContext) {
    if (element.hasAttribute(POINTCUT) && element.hasAttribute(POINTCUT_REF)) {
        parserContext.getReaderContext().error(
                "Cannot define both 'pointcut' and 'pointcut-ref' on <advisor> tag.", element,
                this.parseState.snapshot());
        return null;
    } else if (element.hasAttribute(POINTCUT)) {
        // Create a pointcut for the anonymous pc and register it.
        String expression = element.getAttribute(POINTCUT);
        AbstractBeanDefinition pointcutDefinition = createPointcutDefinition(expression);
        pointcutDefinition.setSource(parserContext.extractSource(element));
        return pointcutDefinition;
    } else if (element.hasAttribute(POINTCUT_REF)) {
        String pointcutRef = element.getAttribute(POINTCUT_REF);
        if (!StringUtils.hasText(pointcutRef)) {
            parserContext.getReaderContext().error("'pointcut-ref' attribute contains empty value.", element,
                    this.parseState.snapshot());
            return null;
        }
        return pointcutRef;
    } else {
        parserContext.getReaderContext().error(
                "Must define one of 'pointcut' or 'pointcut-ref' on <advisor> tag.", element,
                this.parseState.snapshot());
        return null;
    }
}

From source file:org.opentraces.metatracker.net.OpenTracesClient.java

/**
 * Throw exception on negative protocol response.
 *///w w  w . ja va  2 s .  c o m
private void throwOnNrsp(Element anElement) throws ClientException {
    if (isNegativeResponse(anElement)) {
        String details = "no details";
        if (anElement.hasAttribute(ATTR_DETAILS)) {
            details = anElement.getAttribute(ATTR_DETAILS);
        }
        throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)),
                anElement.getAttribute(ATTR_ERROR), details);
    }
}

From source file:de.huberlin.wbi.hiway.am.dax.DaxApplicationMaster.java

@Override
public void parseWorkflow() {
    Map<Object, TaskInstance> tasks = new HashMap<>();
    System.out.println("Parsing Pegasus DAX " + getWorkflowFile());

    try {// w  ww .  j  a va 2  s  .  c  om
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new File(getWorkflowFile().getLocalPath().toString()));
        NodeList jobNds = doc.getElementsByTagName("job");

        for (int i = 0; i < jobNds.getLength(); i++) {
            Element jobEl = (Element) jobNds.item(i);
            String id = jobEl.getAttribute("id");
            String taskName = jobEl.getAttribute("name");
            DaxTaskInstance task = new DaxTaskInstance(getRunId(), taskName);
            task.setRuntime(
                    jobEl.hasAttribute("runtime") ? Double.parseDouble(jobEl.getAttribute("runtime")) : 0d);
            tasks.put(id, task);

            StringBuilder arguments = new StringBuilder();
            NodeList argumentNds = jobEl.getElementsByTagName("argument");
            for (int j = 0; j < argumentNds.getLength(); j++) {
                Element argumentEl = (Element) argumentNds.item(j);

                NodeList argumentChildNds = argumentEl.getChildNodes();
                for (int k = 0; k < argumentChildNds.getLength(); k++) {
                    Node argumentChildNd = argumentChildNds.item(k);
                    String argument = "";

                    switch (argumentChildNd.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        Element argumentChildEl = (Element) argumentChildNd;
                        if (argumentChildEl.getNodeName().equals("file")) {
                            if (argumentChildEl.hasAttribute("name")) {
                                argument = argumentChildEl.getAttribute("name");
                            }
                        } else if (argumentChildEl.getNodeName().equals("filename")) {
                            if (argumentChildEl.hasAttribute("file")) {
                                argument = argumentChildEl.getAttribute("file");
                            }
                        }
                        break;
                    case Node.TEXT_NODE:
                        argument = argumentChildNd.getNodeValue().replaceAll("\\s+", " ").trim();
                        break;
                    default:
                    }

                    if (argument.length() > 0) {
                        arguments.append(" ").append(argument);
                    }
                }
            }

            NodeList usesNds = jobEl.getElementsByTagName("uses");
            for (int j = 0; j < usesNds.getLength(); j++) {
                Element usesEl = (Element) usesNds.item(j);
                String link = usesEl.getAttribute("link");
                String fileName = usesEl.getAttribute("file");
                long size = usesEl.hasAttribute("size") ? Long.parseLong(usesEl.getAttribute("size")) : 0l;
                List<String> outputs = new LinkedList<>();

                switch (link) {
                case "input":
                    if (!getFiles().containsKey(fileName)) {
                        Data data = new Data(fileName);
                        data.setInput(true);
                        getFiles().put(fileName, data);
                    }
                    Data data = getFiles().get(fileName);
                    task.addInputData(data, size);
                    break;
                case "output":
                    if (!getFiles().containsKey(fileName))
                        getFiles().put(fileName, new Data(fileName));
                    data = getFiles().get(fileName);
                    task.addOutputData(data, size);
                    data.setInput(false);
                    outputs.add(fileName);
                    break;
                default:
                }

                task.getReport()
                        .add(new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(),
                                task.getLanguageLabel(), Long.valueOf(task.getId()), null,
                                JsonReportEntry.KEY_INVOC_OUTPUT, new JSONObject().put("output", outputs)));
            }

            task.setCommand(taskName + arguments.toString());
            System.out.println(
                    "Adding task " + task + ": " + task.getInputData() + " -> " + task.getOutputData());
        }

        NodeList childNds = doc.getElementsByTagName("child");
        for (int i = 0; i < childNds.getLength(); i++) {
            Element childEl = (Element) childNds.item(i);
            String childId = childEl.getAttribute("ref");
            TaskInstance child = tasks.get(childId);

            NodeList parentNds = childEl.getElementsByTagName("parent");
            for (int j = 0; j < parentNds.getLength(); j++) {
                Element parentEl = (Element) parentNds.item(j);
                String parentId = parentEl.getAttribute("ref");
                TaskInstance parent = tasks.get(parentId);

                child.addParentTask(parent);
                parent.addChildTask(child);
            }
        }

        for (TaskInstance task : tasks.values()) {
            if (task.getChildTasks().size() == 0) {
                for (Data data : task.getOutputData()) {
                    data.setOutput(true);
                }
            }

            task.getReport()
                    .add(new JsonReportEntry(task.getWorkflowId(), task.getTaskId(), task.getTaskName(),
                            task.getLanguageLabel(), Long.valueOf(task.getId()), null,
                            JsonReportEntry.KEY_INVOC_SCRIPT, task.getCommand()));
        }

    } catch (WorkflowStructureUnknownException | IOException | JSONException | ParserConfigurationException
            | SAXException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    getScheduler().addTasks(tasks.values());
}

From source file:de.itsvs.cwtrpc.controller.config.CacheControlConfigBeanDefinitionParser.java

protected AbstractBeanDefinition createUriPattern(Element element, ParserContext parserContext) {
    final String value;
    final Object type;
    final RootBeanDefinition beanDefinition;

    value = element.getAttribute(XmlNames.VALUE_ATTR);
    if (!StringUtils.hasText(value)) {
        parserContext.getReaderContext().error("URI value must not be empty",
                parserContext.extractSource(element));
    }//w w w .j a  v a 2 s.  co m
    if (element.hasAttribute(XmlNames.TYPE_ATTR)) {
        type = element.getAttribute(XmlNames.TYPE_ATTR);
    } else {
        type = CacheControlUriConfig.DEFAULT_PATTERN_TYPE;
    }

    beanDefinition = new RootBeanDefinition(PatternFactory.class);
    beanDefinition.setSource(parserContext.extractSource(element));
    if (parserContext.isDefaultLazyInit()) {
        beanDefinition.setLazyInit(true);
    }
    beanDefinition.setFactoryMethodName("compile");

    beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, type);
    beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, MatcherType.URI);
    beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(2, value);

    return beanDefinition;
}

From source file:com.legstar.jaxb.plugin.CobolJAXBAnnotator.java

/**
 * Attempts to set a default value for the java field based on the COBOL
 * default value./*  ww w .  j a v  a 2  s  .  co  m*/
 * <p/>
 * Will not attempt to initialize arrays or complex types.
 * <p/>
 * Strings which COBOL peer defaults to low values or high values are
 * initialized with an empty string.
 * <p/>
 * Leading plus signs are removed from numerics, they cause
 * NumberFormatException.
 * 
 * @param jf the java field
 * @param e the XML node holding COBOL annotations
 */
protected void setDefaultValue(final JFieldVar jf, final Element e) {
    if (!e.hasAttribute(CobolMarkup.VALUE)) {
        return;
    }
    String value = e.getAttribute(CobolMarkup.VALUE).trim();
    String type = jf.type().binaryName();
    if (type.equals("java.lang.String")) {
        jf.init(JExpr.lit(value));
    } else {
        /* Assume a numeric from now on */
        if (value.length() == 0) {
            return;
        }
        /* Java does not like leading plus sign */
        if (value.startsWith("+")) {
            value = value.substring(1);
        }
        if (type.equals("java.math.BigDecimal")) {
            jf.init(JExpr.direct("new BigDecimal(\"" + value + "\")"));
        } else if (type.equals("java.math.BigInteger")) {
            jf.init(JExpr.direct("new BigInteger(\"" + value + "\")"));
        } else if (type.equals("short")) {
            jf.init(JExpr.lit(Short.parseShort(value)));
        } else if (type.equals("int")) {
            jf.init(JExpr.lit(Integer.parseInt(value)));
        } else if (type.equals("long")) {
            jf.init(JExpr.lit(Long.parseLong(value)));
        } else if (type.equals("float")) {
            jf.init(JExpr.lit(Float.parseFloat(value)));
        } else if (type.equals("double")) {
            jf.init(JExpr.lit(Double.parseDouble(value)));
        }
    }

}

From source file:net.sourceforge.dita4publishers.api.dita.DitaLinkManagementServiceTest.java

public void testKeyWhereUsed() throws Exception {
    // get DOM for the rootMap.

    DitaKeySpace keySpace;/*ww w . j a v a2s  . co m*/

    // Map document contains 6 topicrefs, of which 5 define keys.

    // Test management of key space registry and handling of out-of-date
    // key spaces.

    KeyAccessOptions keyAccessOptions = new KeyAccessOptions();

    DitaKeyDefinitionContext keydefContext = dlmService.registerRootMap(rootMap);
    assertNotNull(keydefContext);
    DitaKeyDefinitionContext candKeydefContext = dlmService.getKeyDefinitionContext(rootMap);
    assertEquals(keydefContext, candKeydefContext);

    keySpace = dlmService.getKeySpace(keyAccessOptions, keydefContext);
    assertNotNull(keySpace);
    assertEquals(rootMap.getDocumentURI(), keySpace.getRootMap(keyAccessOptions).getDocumentURI());

    // Key references:

    DitaReference ref;
    List<DitaReference> refs;
    Document topic01 = null;

    refs = dlmService.getKeyWhereUsed(keyAccessOptions, key01);
    assertNotNull(refs);
    assertEquals(2, refs.size());

    refs = dlmService.getKeyWhereUsed(keyAccessOptions, key01, keydefContext);
    assertNotNull(refs);
    assertEquals(2, refs.size());

    // Key references limited via filter:

    DitaResultSetFilter filter;
    filter = new DitaFilterByType("topic/keyword");
    refs = dlmService.getKeyWhereUsed(keyAccessOptions, key01, filter);
    assertNotNull(refs);
    assertEquals(1, refs.size());
    refs = dlmService.getKeyWhereUsed(keyAccessOptions, key01, filter, topic01);
    assertNotNull(refs);
    assertEquals(1, refs.size());

    ref = refs.get(0);
    assertNotNull(ref);

    assertEquals(true, ref.isDitaElement());
    assertEquals(false, ref.isTopicRef());
    Element elem;

    elem = ref.getElement();
    assertNotNull(elem);
    assertTrue(elem.hasAttribute("class"));
    assertTrue(elem.getAttribute("class").contentEquals(" topic/keyword")); // Note: no trailing slash to work around ML 3.2 bug

    // FIXME: Need more tests for the detailed properties of key definitions and 
    // resources, e.g., navigation titles, titles, etc.

    // Where-used for elements with IDs:

    DitaElementResource potentialTarget;

    List<Document> usedBy;

    Document targetTopic = null;
    // FIXME: construct doc from  topic01Url

    // Target is a topic that is the root element of its containing MO:
    potentialTarget = dlmService.constructDitaElementResource(targetTopic);
    assertNotNull(potentialTarget);
    assertNotNull(potentialTarget.getElement());
    assertTrue(DitaUtil.isDitaTopic(potentialTarget.getElement()));

    // Get direct uses anywhere in the repository:
    usedBy = dlmService.getWhereUsed(keyAccessOptions, potentialTarget);
    assertNotNull(usedBy);
    assertEquals(1, usedBy.size());

    // Get direct uses within a context:

    usedBy = dlmService.getWhereUsed(keyAccessOptions, potentialTarget, keydefContext);
    assertNotNull(usedBy);
    assertEquals(1, usedBy.size());

    usedBy = dlmService.getWhereUsedByKey(keyAccessOptions, potentialTarget, keydefContext);
    assertNotNull(usedBy);

    // Get the key definitions that point to the specified target:

    List<DitaKeyDefinition> keyBindings;
    keyBindings = dlmService.getKeyBindings(keyAccessOptions, potentialTarget);
    assertNotNull(keyBindings);

    keyBindings = dlmService.getKeyBindings(keyAccessOptions, potentialTarget, keydefContext);
    assertNotNull(keyBindings);

}

From source file:com.cloudbees.sdk.CommandServiceImpl.java

private Plugin parsePluginFile(File file) throws FileNotFoundException, XPathExpressionException {
    InputStream inputStream = new FileInputStream(file);
    try {/*from   www  .  ja va  2s. c  om*/
        InputSource input = new InputSource(inputStream);
        Document doc = XmlHelper.readXML(input);
        Plugin plugin = new Plugin();
        Element e = doc.getDocumentElement();
        if (e.getTagName().equalsIgnoreCase("plugin")) {
            if (e.hasAttribute("artifact"))
                plugin.setArtifact(e.getAttribute("artifact"));

            NodeList nodes = e.getChildNodes();
            List<String> jars = new ArrayList<String>();
            plugin.setJars(jars);
            List<CommandProperties> commands = new ArrayList<CommandProperties>();
            plugin.setProperties(commands);
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (node.getNodeName().equals("jar"))
                    jars.add(node.getTextContent().trim());
                else if (node.getNodeName().equals("command")) {
                    CommandProperties commandProperties = new CommandProperties();
                    commandProperties.setGroup(getAttribute(node, "group"));
                    commandProperties.setName(getAttribute(node, "name"));
                    commandProperties.setPattern(getAttribute(node, "pattern"));
                    commandProperties.setDescription(getAttribute(node, "description"));
                    commandProperties.setClassName(getAttribute(node, "className"));
                    String str = getAttribute(node, "experimental");
                    if (str != null)
                        commandProperties.setExperimental(Boolean.parseBoolean(str));
                    str = getAttribute(node, "priority");
                    if (str != null)
                        commandProperties.setPriority(Integer.parseInt(str));
                    commands.add(commandProperties);
                }
            }
        }
        return plugin;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:de.itsvs.cwtrpc.controller.config.CacheControlConfigBeanDefinitionParser.java

protected AbstractBeanDefinition createUriConfigBeanDefinition(Element element, ParserContext parserContext) {
    final BeanDefinitionBuilder bdd;

    bdd = BeanDefinitionBuilder.rootBeanDefinition(CacheControlUriConfig.class);
    if (parserContext.isDefaultLazyInit()) {
        bdd.setLazyInit(true);/*from  w ww .ja  v  a 2s.  c om*/
    }
    bdd.getRawBeanDefinition().setSource(parserContext.extractSource(element));
    bdd.addConstructorArgValue(createUriPattern(element, parserContext));

    if (element.hasAttribute(XmlNames.SERVICE_INTERFACE_ATTR)) {
        bdd.addPropertyValue("serviceInterface", element.getAttribute(XmlNames.SERVICE_INTERFACE_ATTR));
    }

    update(element, bdd, XmlNames.METHOD_ATTR, "method");
    update(element, bdd, XmlNames.PUBLIC_ATTR, "publicContent");
    update(element, bdd, XmlNames.PRIVATE_ATTR, "privateContent");
    update(element, bdd, XmlNames.NO_CACHE_ATTR, "noCache");
    update(element, bdd, XmlNames.NO_STORE_ATTR, "noStore");
    update(element, bdd, XmlNames.NO_TRANSFORM_ATTR, "noTransform");
    update(element, bdd, XmlNames.MUST_REVALIDATE_ATTR, "mustRevalidate");
    update(element, bdd, XmlNames.PROXY_REVALIDATE_ATTR, "proxyRevalidate");
    update(element, bdd, XmlNames.MAX_AGE_ATTR, "maxAge");
    update(element, bdd, XmlNames.S_MAXAGE_ATTR, "sharedMaxage");
    update(element, bdd, XmlNames.EXPIRES_ATTR, "expires");
    update(element, bdd, XmlNames.PRAGMA_NO_CACHE_ATTR, "pragmaNoCache");

    return bdd.getBeanDefinition();
}

From source file:com.google.api.ads.adwords.awreporting.util.MediaReplacedElementFactory.java

/**
 * @see org.xhtmlrenderer.extend.ReplacedElementFactory
 *      #createReplacedElement(org.xhtmlrenderer.layout.LayoutContext,
 *      org.xhtmlrenderer.render.BlockBox, org.xhtmlrenderer.extend.UserAgentCallback, int, int)
 *///from w  ww . j ava  2 s . c  o m
@Override
public ReplacedElement createReplacedElement(LayoutContext layoutContext, BlockBox blockBox,
        UserAgentCallback userAgentCallback, int cssWidth, int cssHeight) {
    Element element = blockBox.getElement();
    if (element == null) {
        return null;
    }
    String nodeName = element.getNodeName();
    String className = element.getAttribute("class");

    // Replace any <div class="media" data-src="image.png" /> with the
    // binary data of `image.png` into the PDF.
    if ("div".equals(nodeName) && className.startsWith("media")) {
        if (!element.hasAttribute("data-src")) {
            throw new RuntimeException("An element with class `media` is missing a `data-src` "
                    + "attribute indicating the media file.");
        }

        InputStream input = null;
        String dataSrc = element.getAttribute("data-src");
        try {

            if (dataSrc.startsWith("http")) {
                input = new URL(dataSrc).openStream();
            } else if (dataSrc.startsWith("data:image") && dataSrc.contains("base64")) {

                byte[] image = Base64.decode(dataSrc.split(",")[1]);
                input = new ByteArrayInputStream(image);

            } else {
                input = new FileInputStream(dataSrc);
            }

            final byte[] bytes = IOUtils.toByteArray(input);
            final Image image = Image.getInstance(bytes);
            final FSImage fsImage = new ITextFSImage(image);
            if (fsImage != null) {
                if ((cssWidth != -1) || (cssHeight != -1)) {
                    fsImage.scale(cssWidth, cssHeight);
                }
                return new ITextImageElement(fsImage);
            }
        } catch (Exception e) {
            throw new RuntimeException("There was a problem trying to read a template embedded graphic.", e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }
    return this.superFactory.createReplacedElement(layoutContext, blockBox, userAgentCallback, cssWidth,
            cssHeight);
}

From source file:com.interface21.beans.factory.xml.XmlBeanFactory.java

/**
 * Parse a standard bean definition./*from  www .jav  a 2s  .  com*/
 */
private AbstractBeanDefinition parseBeanDefinition(Element el, String beanName, PropertyValues pvs) {
    String classname = null;
    boolean singleton = true;
    if (el.hasAttribute(SINGLETON_ATTRIBUTE)) {
        // Default is singleton
        // Can override by making non-singleton if desired
        singleton = TRUE_ATTRIBUTE_VALUE.equals(el.getAttribute(SINGLETON_ATTRIBUTE));
    }
    try {
        if (el.hasAttribute(CLASS_ATTRIBUTE))
            classname = el.getAttribute(CLASS_ATTRIBUTE);
        String parent = null;
        if (el.hasAttribute(PARENT_ATTRIBUTE))
            parent = el.getAttribute(PARENT_ATTRIBUTE);
        if (classname == null && parent == null)
            throw new FatalBeanException("No classname or parent in bean definition [" + beanName + "]", null);
        if (classname != null) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            String initMethodName = el.getAttribute(INIT_METHOD_ATTRIBUTE);
            if (initMethodName.equals(""))
                initMethodName = null;
            return new RootBeanDefinition(Class.forName(classname, true, cl), pvs, singleton, initMethodName);
        } else {
            return new ChildBeanDefinition(parent, pvs, singleton);
        }
    } catch (ClassNotFoundException ex) {
        throw new FatalBeanException(
                "Error creating bean with name [" + beanName + "]: class '" + classname + "' not found", ex);
    }
}