Example usage for org.jdom2 Element getNamespace

List of usage examples for org.jdom2 Element getNamespace

Introduction

In this page you can find the example usage for org.jdom2 Element getNamespace.

Prototype

public Namespace getNamespace() 

Source Link

Document

Returns the element's Namespace .

Usage

From source file:org.mycore.frontend.support.MCRAutoDeploy.java

License:Open Source License

private void registerWebFragment(final ServletContext servletContext, final MCRComponent comp) {
    try {/*from   www.  ja v  a  2 s .  c  o m*/
        final JarFile jar = new JarFile(comp.getJarFile());

        Collections.list(jar.entries()).stream().filter(file -> file.getName().equals(WEB_FRAGMENT)).findFirst()
                .ifPresent(file -> {
                    final SAXBuilder builder = new SAXBuilder();
                    try {
                        final InputStream is = jar.getInputStream(file);
                        final Document doc = builder.build(is);

                        final Element root = doc.getRootElement();
                        final Namespace ns = root.getNamespace();

                        final List<Element> filters = root.getChildren("filter", ns);
                        final List<Element> fmaps = root.getChildren("filter-mapping", ns);

                        filters.forEach(filter -> {
                            final String name = filter.getChildText("filter-name", ns);
                            final String className = filter.getChildText("filter-class", ns);

                            fmaps.stream()
                                    .filter(mapping -> mapping.getChildText("filter-name", ns).equals(name))
                                    .findFirst().ifPresent(mapping -> {
                                        LOGGER.info("Register Filter " + name + " (" + className + ")...");
                                        Optional.ofNullable(servletContext.addFilter(name, className))
                                                .<Runnable>map(fr -> () -> {
                                                    final List<Element> dispatchers = mapping
                                                            .getChildren("dispatcher", ns);

                                                    final EnumSet<DispatcherType> eDT = dispatchers.isEmpty()
                                                            ? null
                                                            : dispatchers.stream()
                                                                    .map(d -> DispatcherType
                                                                            .valueOf(d.getTextTrim()))
                                                                    .collect(Collectors
                                                                            .toCollection(() -> EnumSet.noneOf(
                                                                                    DispatcherType.class)));

                                                    final List<Element> servletNames = mapping
                                                            .getChildren("servlet-name", ns);

                                                    if (!servletNames.isEmpty()) {
                                                        fr.addMappingForServletNames(eDT, false,
                                                                servletNames.stream().map(sn -> {
                                                                    LOGGER.info("...add servlet mapping: "
                                                                            + sn.getTextTrim());
                                                                    return sn.getTextTrim();
                                                                }).toArray(String[]::new));
                                                    }

                                                    final List<Element> urlPattern = mapping
                                                            .getChildren("url-pattern", ns);

                                                    if (!urlPattern.isEmpty()) {
                                                        fr.addMappingForUrlPatterns(eDT, false,
                                                                urlPattern.stream().map(url -> {
                                                                    LOGGER.info("...add url mapping: "
                                                                            + url.getTextTrim());
                                                                    return url.getTextTrim();
                                                                }).toArray(String[]::new));
                                                    }
                                                }).orElse(() -> LOGGER
                                                        .warn("Filter " + name + " already registered!"))
                                                .run();
                                    });
                        });

                        final List<Element> servlets = root.getChildren("servlet", ns);
                        final List<Element> smaps = root.getChildren("servlet-mapping", ns);

                        servlets.forEach(servlet -> {
                            final String name = servlet.getChildText("servlet-name", ns);
                            final String className = servlet.getChildText("servlet-class", ns);

                            smaps.stream()
                                    .filter(mapping -> mapping.getChildText("servlet-name", ns).equals(name))
                                    .findFirst().ifPresent(mapping -> {
                                        LOGGER.info("Register Servlet " + name + " (" + className + ")...");
                                        Optional.ofNullable(servletContext.addServlet(name, className))
                                                .<Runnable>map(sr -> () -> {
                                                    mapping.getChildren("url-pattern", ns).stream()
                                                            .forEach(url -> {
                                                                LOGGER.info("...add url mapping: "
                                                                        + url.getTextTrim());
                                                                sr.addMapping(url.getTextTrim());
                                                            });
                                                })
                                                .orElse(() -> LOGGER
                                                        .error("Servlet" + name + " already registered!"))
                                                .run();
                                    });
                        });
                    } catch (IOException | JDOMException e) {
                        LOGGER.error("Couldn't parse " + WEB_FRAGMENT, e);
                    }
                });

        jar.close();
    } catch (final IOException e) {
        LOGGER.error("Couldn't parse JAR!", e);
    }
}

From source file:org.mycore.frontend.xeditor.MCREditorSession.java

License:Open Source License

private void addNamespacesFrom(Element element) {
    MCRConstants.registerNamespace(element.getNamespace());
    for (Namespace ns : element.getAdditionalNamespaces()) {
        MCRConstants.registerNamespace(ns);
    }/*from w w w .  j av a 2 s  .  c  o  m*/
    for (Element child : element.getChildren())
        addNamespacesFrom(child);
}

From source file:org.mycore.mods.MCRMODSCommands.java

License:Open Source License

@MCRCommand(syntax = "load mods document from file {0} for project {1}", help = "Load MODS document {0} as MyCoRe Object for project {1}", order = 20)
public static void loadFromFile(String modsFileName, String projectID) throws JDOMException, IOException,
        MCRActiveLinkException, SAXException, MCRPersistenceException, MCRAccessException {
    File modsFile = new File(modsFileName);
    if (!modsFile.isFile()) {
        throw new MCRException(MessageFormat.format("File {0} is not a file.", modsFile.getAbsolutePath()));
    }/*w w w. j  a  v  a2 s.  co  m*/
    SAXBuilder s = new SAXBuilder(XMLReaders.NONVALIDATING, null, null);
    Document modsDoc = s.build(modsFile);
    //force validation against MODS XSD
    MCRXMLHelper.validate(modsDoc, MODS_V3_XSD_URI);
    Element modsRoot = modsDoc.getRootElement();
    if (!modsRoot.getNamespace().equals(MCRConstants.MODS_NAMESPACE)) {
        throw new MCRException(
                MessageFormat.format("File {0} is not a MODS document.", modsFile.getAbsolutePath()));
    }
    if (modsRoot.getName().equals("modsCollection")) {
        List<Element> modsElements = modsRoot.getChildren("mods", MCRConstants.MODS_NAMESPACE);
        for (Element mods : modsElements) {
            saveAsMyCoReObject(projectID, mods);
        }
    } else {
        saveAsMyCoReObject(projectID, modsRoot);
    }
}

From source file:org.mycore.mods.MCRMODSWrapper.java

License:Open Source License

public void addElement(Element element) {
    if (!element.getNamespace().equals(MCRConstants.MODS_NAMESPACE))
        throw new IllegalArgumentException("given element is no mods element");

    insertTopLevelElement(element);//from w w  w.ja  va 2s  . co  m
}

From source file:org.openconcerto.xml.JDOM2Utils.java

License:Open Source License

/**
 * Test if two elements have the same namespace and name.
 * //  w ww  .j a  va2 s  .c  o  m
 * @param elem1 an element, can be <code>null</code>.
 * @param elem2 an element, can be <code>null</code>.
 * @return <code>true</code> if both elements have the same name and namespace, or if both are
 *         <code>null</code>.
 */
public static boolean equals(Element elem1, Element elem2) {
    if (elem1 == elem2 || elem1 == null && elem2 == null)
        return true;
    else if (elem1 == null || elem2 == null)
        return false;
    else
        return elem1.getName().equals(elem2.getName()) && elem1.getNamespace().equals(elem2.getNamespace());
}

From source file:org.opengroup.archimate.xmlexchange.XMLModelExporter.java

License:Open Source License

/**
 * @param doc/*from   ww w . j a  v  a  2  s.c o  m*/
 * @return The Root JDOM Element
 */
Element createRootElement(Document doc) {
    Element rootElement = new Element(ELEMENT_MODEL, OPEN_GROUP_NAMESPACE);
    doc.setRootElement(rootElement);

    rootElement.addNamespaceDeclaration(JDOMUtils.XSI_Namespace);
    // rootElement.addNamespaceDeclaration(OPEN_GROUP_NAMESPACE_EMBEDDED); // Don't include this

    // DC Namespace
    if (hasMetadata()) {
        rootElement.addNamespaceDeclaration(DC_NAMESPACE);
    }

    /* 
     * Add Schema Location Attribute which is constructed from Target Namespaces and file names of Schemas
     */
    StringBuffer schemaLocationURI = new StringBuffer();

    // Open Group Schema Location
    schemaLocationURI.append(rootElement.getNamespace().getURI());
    schemaLocationURI.append(" "); //$NON-NLS-1$
    schemaLocationURI.append(OPEN_GROUP_SCHEMA_LOCATION);

    // DC Schema Location
    if (hasMetadata()) {
        schemaLocationURI.append(" "); //$NON-NLS-1$
        schemaLocationURI.append(DC_NAMESPACE.getURI());
        schemaLocationURI.append(" "); //$NON-NLS-1$
        schemaLocationURI.append(DC_SCHEMA_LOCATION);
    }

    rootElement.setAttribute(JDOMUtils.XSI_SchemaLocation, schemaLocationURI.toString(),
            JDOMUtils.XSI_Namespace);

    return rootElement;
}

From source file:org.rascalmpl.library.lang.xml.DOM.java

License:Open Source License

private IConstructor convertElement(Element e, boolean trim) {
    IListWriter kids = vf.listWriter(Factory.Node);
    for (Object o : e.getAttributes()) {
        Attribute attr = (Attribute) o;
        IString key = vf.string(attr.getName());
        IString val = vf.string(attr.getValue());

        kids.insert(vf.constructor(Factory.Node_attribute, convertNamespace(attr.getNamespace()), key, val));
    }/*from   w  ww .jav  a2s .c  om*/

    int len = e.getContentSize();
    for (int i = 0; i < len; i++) {
        try {
            kids.append(convertContent(e.getContent(i), trim));
        } catch (Skip c) { // Ugh, terrible, but I'm in hurry
            continue;
        }
    }

    IString name = vf.string(e.getName());
    return vf.constructor(Factory.Node_element, convertNamespace(e.getNamespace()), name, kids.done());
}

From source file:org.rometools.feed.module.base.io.CustomTagParser.java

License:Open Source License

public Module parse(Element element) {
    CustomTags module = new CustomTagsImpl();
    ArrayList tags = new ArrayList();
    List elements = element.getChildren();
    Iterator it = elements.iterator();
    while (it.hasNext()) {
        Element child = (Element) it.next();
        if (child.getNamespace().equals(NS)) {
            String type = child.getAttributeValue("type");
            try {
                if (type == null) {
                    continue;
                } else if (type.equals("string")) {
                    tags.add(new CustomTagImpl(child.getName(), child.getText()));
                } else if (type.equals("int")) {
                    tags.add(new CustomTagImpl(child.getName(), new Integer(child.getTextTrim())));
                } else if (type.equals("float")) {
                    tags.add(new CustomTagImpl(child.getName(), new Float(child.getTextTrim())));
                } else if (type.equals("intUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new IntUnit(child.getTextTrim())));
                } else if (type.equals("floatUnit")) {
                    tags.add(new CustomTagImpl(child.getName(), new FloatUnit(child.getTextTrim())));
                } else if (type.equals("date")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new ShortDate(GoogleBaseParser.SHORT_DT_FMT.parse(child.getTextTrim()))));
                    } catch (ParseException e) {
                        log.log(Level.WARNING, "Unable to parse date type on " + child.getName(), e);
                    }/*w  w w .  j  ava 2 s  .c  o m*/
                } else if (type.equals("dateTime")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                GoogleBaseParser.LONG_DT_FMT.parse(child.getTextTrim())));
                    } catch (ParseException e) {
                        log.log(Level.WARNING, "Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("dateTimeRange")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(),
                                new DateTimeRange(
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("start", CustomTagParser.NS).getText().trim()),
                                        GoogleBaseParser.LONG_DT_FMT.parse(
                                                child.getChild("end", CustomTagParser.NS).getText().trim()))));
                    } catch (Exception e) {
                        log.log(Level.WARNING, "Unable to parse date type on " + child.getName(), e);
                    }
                } else if (type.equals("url")) {
                    try {
                        tags.add(new CustomTagImpl(child.getName(), new URL(child.getTextTrim())));
                    } catch (MalformedURLException e) {
                        log.log(Level.WARNING, "Unable to parse URL type on " + child.getName(), e);
                    }
                } else if (type.equals("boolean")) {
                    tags.add(
                            new CustomTagImpl(child.getName(), new Boolean(child.getTextTrim().toLowerCase())));
                } else if (type.equals("location")) {
                    tags.add(new CustomTagImpl(child.getName(), new CustomTagImpl.Location(child.getText())));
                } else {
                    throw new Exception("Unknown type: " + type);
                }
            } catch (Exception e) {
                log.log(Level.WARNING, "Unable to parse type on " + child.getName(), e);
            }
        }
    }
    module.setValues(tags);
    return module;
}

From source file:org.rometools.feed.module.base.io.GoogleBaseParser.java

License:Open Source License

public Module parse(Element element) {
    HashMap tag2pd = new HashMap();
    GoogleBaseImpl module = new GoogleBaseImpl();

    try {/*from  w  w  w . ja v  a 2  s. c o  m*/
        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            String tagName = GoogleBaseParser.PROPS2TAGS.getProperty(pd.getName());

            if (tagName == null) {
                log.log(Level.FINE, "Property: " + pd.getName() + " doesn't have a tag mapping. ");
            } else {
                tag2pd.put(tagName, pd);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Exception building tag to property mapping. ", e);
    }

    List children = element.getChildren();
    Iterator it = children.iterator();

    while (it.hasNext()) {
        Element child = (Element) it.next();

        if (child.getNamespace().equals(GoogleBaseParser.NS)) {
            PropertyDescriptor pd = (PropertyDescriptor) tag2pd.get(child.getName());

            if (pd != null) {
                try {
                    this.handleTag(child, pd, module);
                } catch (Exception e) {
                    log.log(Level.WARNING, "Unable to handle tag: " + child.getName(), e);
                    e.printStackTrace();
                }
            }
        }
    }

    return module;
}

From source file:org.rometools.feed.module.cc.io.CCModuleGenerator.java

License:Open Source License

public void generate(Module module, Element element) {
    Element root = element;
    while (root.getParentElement() != null) {
        root = root.getParentElement();//from   w ww.  j  av  a 2  s  .co  m
    }
    if (root.getNamespace().equals(RDF) || root.getNamespace().equals(RSS)) {
        generateRSS1((CreativeCommons) module, element);
    } else {
        generateRSS2((CreativeCommons) module, element);
    }
}