org.jdom2.Text Java Examples

The following examples show how to use org.jdom2.Text. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: N2oStandardControlReaderV1.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
private Map<String, String>[] readOptions(Element options) {
    Map<String, String>[] optionsMap = new HashMap[options.getChildren().size()];
    int i = 0;
    for (Element option : (List<Element>) options.getChildren()) {
        String json = ((Text) option.getContent().get(0)).getValue();
        Map<String, String> map;
        try {
            map = mapper.readValue(json, new TypeReference<Map<String, String>>() {
            });
        } catch (IOException e) {
            throw new N2oException("Can not resolve json", e);
        }
        optionsMap[i] = map;
        i++;
    }

    return optionsMap;
}
 
Example #2
Source File: WildFlyCamelConfigPlugin.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private static void updateSecurityDomain(ConfigContext context, boolean enable) {
    List<Element> profiles = ConfigSupport.findProfileElements(context.getDocument(), NS_DOMAINS);
    for (Element profile : profiles) {
        Element security = profile.getChild("subsystem", NS_SECURITY);
        if (security != null) {
            Element domains = security.getChild("security-domains", NS_SECURITY);
            ConfigSupport.assertExists(domains, "Did not find the <security-domains> element");
            Element domain = ConfigSupport.findElementWithAttributeValue(domains, "security-domain", "name", "hawtio-domain", NS_SECURITY);
            if (enable && domain == null) {
                URL resource = WildFlyCamelConfigPlugin.class.getResource("/hawtio-security-domain.xml");
                domains.addContent(new Text("    "));
                domains.addContent(ConfigSupport.loadElementFrom(resource));
                domains.addContent(new Text("\n            "));
            }
            if (!enable && domain != null) {
                domain.getParentElement().removeContent(domain);
            }
        }
    }
}
 
Example #3
Source File: MCRMetsIIIFModsMetadataExtractor.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<MCRIIIFMetadata> extractModsMetadata(Element xmlData) {
    Map<String, String> elementLabelMap = new HashMap<>();

    elementLabelMap.put("title", "mods:mods/mods:titleInfo/mods:title/text()");
    elementLabelMap.put("genre", "mods:mods/mods:genre/text()");
    // TODO: add some more metadata

    return elementLabelMap.entrySet().stream().map(entry -> {
        XPathExpression<Text> pathExpression = XPathFactory.instance().compile(entry.getValue(), Filters.text(),
            null, MCRConstants.MODS_NAMESPACE);
        List<Text> texts = pathExpression.evaluate(xmlData);
        if (texts.size() == 0) {
            return null;
        }
        return new MCRIIIFMetadata(entry.getKey(),
            texts.stream().map(Text::getText).collect(Collectors.joining(", ")));
    }).filter(Objects::nonNull)
        .collect(Collectors.toList());
}
 
Example #4
Source File: MCRWCMSDefaultSectionProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the content of an element as string. The element itself
 * is ignored.
 * 
 * @param e the element to get the content from
 * @return the content as string
 */
protected String getContent(Element e) throws IOException {
    XMLOutputter out = new XMLOutputter();
    StringWriter writer = new StringWriter();
    for (Content child : e.getContent()) {
        if (child instanceof Element) {
            out.output((Element) child, writer);
        } else if (child instanceof Text) {
            Text t = (Text) child;
            String trimmedText = t.getTextTrim();
            if (!"".equals(trimmedText)) {
                Text newText = new Text(trimmedText);
                out.output(newText, writer);
            }
        }
    }
    return writer.toString();
}
 
Example #5
Source File: MCRXMLHelper.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static boolean equivalentContent(List<Content> l1, List<Content> l2) {
    if (l1.size() != l2.size()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Number of content list elements differ {}!={}", l1.size(), l2.size());
        }
        return false;
    }
    boolean result = true;
    Iterator<Content> i1 = l1.iterator();
    Iterator<Content> i2 = l2.iterator();
    while (result && i1.hasNext() && i2.hasNext()) {
        Object o1 = i1.next();
        Object o2 = i2.next();
        if (o1 instanceof Element && o2 instanceof Element) {
            result = equivalent((Element) o1, (Element) o2);
        } else if (o1 instanceof Text && o2 instanceof Text) {
            result = equivalent((Text) o1, (Text) o2);
        } else if (o1 instanceof Comment && o2 instanceof Comment) {
            result = equivalent((Comment) o1, (Comment) o2);
        } else if (o1 instanceof ProcessingInstruction && o2 instanceof ProcessingInstruction) {
            result = equivalent((ProcessingInstruction) o1, (ProcessingInstruction) o2);
        } else if (o1 instanceof DocType && o2 instanceof DocType) {
            result = equivalent((DocType) o1, (DocType) o2);
        } else {
            result = false;
        }
    }
    return result;
}
 
Example #6
Source File: WildFlyCamelConfigPlugin.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private static void addProperty(Element systemProperties, Map<String, Element> propertiesByName, String name, String value) {
    Namespace namespace = systemProperties.getNamespace();
    if (!propertiesByName.containsKey(name)) {
        systemProperties.addContent(new Text("   "));
        systemProperties.addContent(new Element("property", namespace).setAttribute("name", name).setAttribute("value", value));
        systemProperties.addContent(new Text("\n    "));
    }
}
 
Example #7
Source File: WildFlyCamelConfigPlugin.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private static void updateServergroup(boolean enable, ConfigContext context) {
    Element serverGroups = ConfigSupport.findChildElement(context.getDocument().getRootElement(), "server-groups", NS_DOMAINS);
    Element camel = ConfigSupport.findElementWithAttributeValue(serverGroups, "server-group", "name", "camel-server-group", NS_DOMAINS);
    if (enable && camel == null) {
        URL resource = WildFlyCamelConfigPlugin.class.getResource("/camel-servergroup.xml");
        serverGroups.addContent(new Text("    "));
        serverGroups.addContent(ConfigSupport.loadElementFrom(resource));
        serverGroups.addContent(new Text("\n    "));
    }
    if (!enable && camel != null) {
        camel.getParentElement().removeContent(camel);
    }
}
 
Example #8
Source File: WildFlyCamelConfigPlugin.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private static void updateSubsystem(ConfigContext context, boolean enable) {
    List<Element> profiles = ConfigSupport.findProfileElements(context.getDocument(), NS_DOMAINS);
    for (Element profile : profiles) {
        Element element = profile.getChild("subsystem", NS_CAMEL);
        if (enable && element == null) {
            URL resource = WildFlyCamelConfigPlugin.class.getResource("/camel-subsystem.xml");
            profile.addContent(new Text("    "));
            profile.addContent(ConfigSupport.loadElementFrom(resource));
            profile.addContent(new Text("\n    "));
        }
        if (!enable && element != null) {
            element.getParentElement().removeContent(element);
        }
    }
}
 
Example #9
Source File: WildFlyCamelConfigPlugin.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private static void updateExtension(ConfigContext context, boolean enable) {
    Element extensions = ConfigSupport.findChildElement(context.getDocument().getRootElement(), "extensions", NS_DOMAINS);
    ConfigSupport.assertExists(extensions, "Did not find the <extensions> element");
    Namespace namespace = extensions.getNamespace();

    Element element = ConfigSupport.findElementWithAttributeValue(extensions, "extension", "module", "org.wildfly.extension.camel", NS_DOMAINS);
    if (enable && element == null) {
        extensions.addContent(new Text("    "));
        extensions.addContent(new Element("extension", namespace).setAttribute("module", "org.wildfly.extension.camel"));
        extensions.addContent(new Text("\n    "));
    }
    if (!enable && element != null) {
        element.getParentElement().removeContent(element);
    }
}
 
Example #10
Source File: ElsevierReader.java    From bluima with Apache License 2.0 5 votes vote down vote up
@Override
public Text filter(Object content) {
    if (content instanceof Text) {
        final Text txt = (Text) content;
        final String parentName = ((Element) txt.getParent()).getName();
        if (elementsToFilter.contains(parentName)) {
            return null;
        } else {
            return txt;
        }
    }
    return null;
}
 
Example #11
Source File: ChaiResponseSet.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Element challengeToXml( final Challenge loopChallenge, final Answer answer, final String elementName )
        throws ChaiOperationException
{
    final Element responseElement = new Element( elementName );
    responseElement.addContent( new Element( XML_NODE_CHALLENGE ).addContent( new Text( loopChallenge.getChallengeText() ) ) );
    final Element answerElement = answer.toXml();
    responseElement.addContent( answerElement );
    responseElement.setAttribute( XML_ATTRIBUTE_ADMIN_DEFINED, String.valueOf( loopChallenge.isAdminDefined() ) );
    responseElement.setAttribute( XML_ATTRIBUTE_REQUIRED, String.valueOf( loopChallenge.isRequired() ) );
    responseElement.setAttribute( XNL_ATTRIBUTE_MIN_LENGTH, String.valueOf( loopChallenge.getMinLength() ) );
    responseElement.setAttribute( XNL_ATTRIBUTE_MAX_LENGTH, String.valueOf( loopChallenge.getMaxLength() ) );
    return responseElement;
}
 
Example #12
Source File: MCRMetaNumberTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void xmlRoundrip() throws IOException {
    // test 0.100
    MCRMetaNumber meta_number = new MCRMetaNumber();
    Element imported = new Element("number");
    imported.setAttribute("inherited", "0");
    imported.setAttribute("dimension", "width");
    imported.setAttribute("measurement", "cm");
    imported.addContent(new Text("0.100"));
    meta_number.setFromDOM(imported);
    Element exported = meta_number.createXML();
    print_data(imported, exported);
    check_data(imported, exported);
}
 
Example #13
Source File: MCRXMLHelper.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method is capable of serializing Elements and Text nodes.
 * Return null otherwise.
 *
 * @param content the content to serialize
 * @return the serialized content, or null if the type is not supported
 */
public static JsonElement serialize(Content content) {
    if (content instanceof Element) {
        return serializeElement((Element) content);
    }
    if (content instanceof Text) {
        return serializeText((Text) content);
    }
    return null;
}
 
Example #14
Source File: MCRXMLHelper.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static boolean equivalent(Text t1, Text t2) {
    String v1 = t1.getValue();
    String v2 = t2.getValue();
    boolean equals = v1.equals(v2);
    if (!equals && LOGGER.isDebugEnabled()) {
        LOGGER.debug("Text differs \"{}\"!=\"{}\"", t1, t2);
    }
    return equals;
}
 
Example #15
Source File: MCRXSL2XMLTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private Document getDocument(JDOMResult result) {
    Document resultDoc = result.getDocument();
    if (resultDoc == null) {
        //Sometimes a transformation produces whitespace strings
        //JDOM would produce a empty document if it detects those
        //So we remove them, if they exists.
        List<Content> transformResult = result.getResult();
        int origSize = transformResult.size();
        Iterator<Content> iterator = transformResult.iterator();
        while (iterator.hasNext()) {
            Content content = iterator.next();
            if (content instanceof Text) {
                String trimmedText = ((Text) content).getTextTrim();
                if (trimmedText.length() == 0) {
                    iterator.remove();
                }
            }
        }
        if (transformResult.size() < origSize) {
            JDOMFactory f = result.getFactory();
            if (f == null) {
                f = new DefaultJDOMFactory();
            }
            resultDoc = f.document(null);
            resultDoc.setContent(transformResult);
        }
    }
    return resultDoc;
}
 
Example #16
Source File: MCRTransferPackageUtil.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the list of mycore object identifiers from the given directory.
 * 
 * @param targetDirectory directory where the *.tar was unpacked
 * @return list of object which lies within the directory
 */
public static List<String> getMCRObjects(Path targetDirectory) throws JDOMException, IOException {
    Path importXMLPath = targetDirectory.resolve(MCRTransferPackage.IMPORT_CONFIG_FILENAME);
    Document xml = new SAXBuilder().build(importXMLPath.toFile());
    Element config = xml.getRootElement();
    XPathExpression<Text> exp = MCRConstants.XPATH_FACTORY.compile("order/object/text()", Filters.text());
    return exp.evaluate(config).stream().map(Text::getText).collect(Collectors.toList());
}
 
Example #17
Source File: MCRChangeData.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public ProcessingInstruction getProcessingInstruction() {
    if (pi == null) {
        String data = RAW_OUTPUTTER.outputString(new Text(text));
        this.pi = new ProcessingInstruction(type, data);
    }
    return pi;
}
 
Example #18
Source File: MCRPostProcessorXSL.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public MCRJDOMContent transform(MCRContent source) throws IOException {
    try {
        Element root = source.asXML().getRootElement().clone();
        for (Text text : root.getDescendants(Filters.text())) {
            text.setText(MCRXMLFunctions.normalizeUnicode(text.getText()));
        }
        return new MCRJDOMContent(root);
    } catch (JDOMException | SAXException ex) {
        throw new IOException(ex);
    }
}
 
Example #19
Source File: Version.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Element getVersionElement() {
  Element lib = new Element("lib");
  Element name = new Element("name");
  Element ver = new Element("version");

  name.addContent(new Text("java-opendap"));
  lib.addContent(name);

  ver.addContent(new Text(version));
  lib.addContent(ver);
  return (lib);
}
 
Example #20
Source File: MCRXMLHelper.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
static JsonPrimitive serializeText(Text text) {
    return new JsonPrimitive(text.getText());
}
 
Example #21
Source File: Version.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static Element getVersionElement() {


    Element lib = new Element("lib");
    Element name = new Element("name");
    Element ver = new Element("version");

    name.addContent(new Text("java-opendap"));
    lib.addContent(name);

    ver.addContent(new Text(version));
    lib.addContent(ver);


    return (lib);

  }
 
Example #22
Source File: MCRGenericPIGenerator.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
@Override
public MCRPersistentIdentifier generate(MCRBase mcrBase, String additional)
    throws MCRPersistentIdentifierException {

    String resultingPI = getGeneralPattern();

    if (resultingPI.contains(PLACE_HOLDER_CURRENT_DATE)) {
        resultingPI = resultingPI.replace(PLACE_HOLDER_CURRENT_DATE, getDateFormat().format(new Date()));
    }

    if (resultingPI.contains(PLACE_HOLDER_OBJECT_DATE)) {
        final Date objectCreateDate = mcrBase.getService().getDate(MCRObjectService.DATE_TYPE_CREATEDATE);
        resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_DATE, getDateFormat().format(objectCreateDate));
    }

    if (resultingPI.contains(PLACE_HOLDER_OBJECT_TYPE)) {
        final String mappedObjectType = getMappedType(mcrBase.getId());
        resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_TYPE, mappedObjectType);
    }

    if (resultingPI.contains(PLACE_HOLDER_OBJECT_PROJECT)) {
        final String mappedObjectProject = getMappedProject(mcrBase.getId());
        resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_PROJECT, mappedObjectProject);
    }

    if (resultingPI.contains(PLACE_HOLDER_OBJECT_NUMBER)) {
        resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_NUMBER, mcrBase.getId().getNumberAsString());
    }

    if (XPATH_PATTERN.asPredicate().test(resultingPI)) {
        resultingPI = XPATH_PATTERN.matcher(resultingPI).replaceAll((mr) -> {
            final String xpathNumberString = mr.group(1);
            final int xpathNumber = Integer.parseInt(xpathNumberString, 10)-1;
            if (this.xpath.length <= xpathNumber || xpathNumber < 0) {
                throw new MCRException(
                    "The index of " + xpathNumber + " is out of bounds of xpath array (" + xpath.length + ")");
            }

            final String xpathString = this.xpath[xpathNumber];
            XPathFactory factory = XPathFactory.instance();
            XPathExpression<Object> expr = factory.compile(xpathString, Filters.fpassthrough(), null,
                MCRConstants.getStandardNamespaces());
            final Object content = expr.evaluateFirst(mcrBase.createXML());

            if(content instanceof Text){
                return ((Text) content).getTextNormalize();
            } else if (content instanceof Attribute){
                return ((Attribute) content).getValue();
            } else if (content instanceof Element){
                return ((Element) content).getTextNormalize();
            } else {
                return content.toString();
            }
        });
        System.out.println(resultingPI);
    }

    final MCRPIParser<MCRPersistentIdentifier> parser = MCRPIManager.getInstance()
        .getParserForType(getType());

    String result;

    result = applyCount(resultingPI);

    if (getType().equals("dnbUrn")) {
        result = result + "C"; // will be replaced by the URN-Parser
    }

    String finalResult = result;
    return parser.parse(finalResult)
        .orElseThrow(() -> new MCRPersistentIdentifierException("Could not parse " + finalResult));

}