Example usage for org.jdom2 Text Text

List of usage examples for org.jdom2 Text Text

Introduction

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

Prototype

public Text(String str) 

Source Link

Document

This constructor creates a new Text node, with the supplied string value as its character content.

Usage

From source file:com.cybernostics.jsp2thymeleaf.JSP2Thymeleaf.java

private List<Content> rootContentFor(JspTree jspTree) {
    List<Content> contents = new ArrayList<>();
    if (showBanner) {
        contents.add(new Comment("Created with JSP2Thymeleaf"));
        contents.add(new Text(NEWLINE));
    }//from   www.ja  v  a 2  s . c  o  m
    contents.addAll(contentFor(jspTree, this));

    final Optional<Content> foundHtmlElement = contents.stream().filter(JSP2Thymeleaf::isHtmlElement)
            .findFirst();

    if (foundHtmlElement.isPresent()) {
        final Element htmlElement = (Element) foundHtmlElement.get();
        contents.remove(htmlElement);
        trimTrailingWhitespace(contents);
        htmlElement.addContent(contents);
        htmlElement.setNamespace(xmlns);
        ActiveNamespaces.get().forEach(ns -> htmlElement.addNamespaceDeclaration(ns));
        return Arrays.asList(new DocType("html", THYMELEAF_DTD), htmlElement);
    } else {
        Element thFragment = createFragmentDef(contents);
        return Arrays.asList(new DocType("html", THYMELEAF_DTD), thFragment);
    }

}

From source file:com.cybernostics.jsp2thymeleaf.JSP2Thymeleaf.java

public List<Content> contentFor(JspTree jspTree, JspTreeConverterContext context) {
    List<Content> contents = new ArrayList<>();
    logger.fine(nameOrNone(jspTree));/*from   ww  w.  j ava 2 s . co m*/
    boolean traversedChildren = false;
    int type = jspTree.getType();
    switch (type) {
    case ELEMENT:
        contents.addAll(getConverter(jspTree).processElement(jspTree, this));
        traversedChildren = true;
        break;
    case JSP_DIRECTIVE:
        contents.addAll(getConverter(jspTree).processElement(jspTree, this));
        //logger.info("Dropping jsp directive:" + jspTree.toStringTree());
        traversedChildren = true;
        break;
    case PCDATA:
        contents.add(new Text(jspTree.getText()));
        traversedChildren = true;
        break;
    case WHITESPACE:
        contents.add(new Text(jspTree.getText()));
        traversedChildren = true;
        break;
    //            case DOCTYPE_DEFINITION:
    //                break;
    //            case EL_EXPR:
    //                break;
    //            case COMMENT:
    //                break;
    //            case JSP_EXPRESSION:
    //                break;
    //            case WHITESPACE:
    //                break;
    //            case JSP_SCRIPTLET:
    //                break;
    //            case JSP_COMMENT:
    //                break;
    default:
        logger.fine(String.format("No action for: %d %s", jspTree.getType(), jspTree.toString()));
    }

    if (!traversedChildren) {
        doWithChildren(jspTree, (i, eachChild) -> contents.addAll(contentFor(eachChild, this)));
    }
    return contents;
}

From source file:com.novell.ldapchai.cr.ChaiResponseSet.java

License:Open Source License

private static Element challengeToXml(final Challenge loopChallenge, final Answer answer,
        final String elementName) throws ChaiOperationException {
    final Element responseElement = new Element(elementName);
    responseElement//  w  ww.ja  va 2s .  co  m
            .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;
}

From source file:de.mud.flash.FlashTerminal.java

License:Open Source License

/**
 * Redraw a sinle line by looking at chunks and formatting them.
 * /* ww  w  . ja  v a 2  s. com*/
 * @param l
 *            the current line
 * @param base
 *            the "window"-base within the buffer
 * @return an element with the formatted line
 */
private Element redrawLine(int l, int base) {
    Element line = new Element("line");
    line.setAttribute("row", "" + l);

    // determine the maximum of characters we can print in one go
    for (int c = 0; c < buffer.width; c++) {
        int addr = 0;
        int currAttr = buffer.charAttributes[base + l][c];

        while ((c + addr < buffer.width) && ((buffer.charArray[base + l][c + addr] < ' ')
                || (buffer.charAttributes[base + l][c + addr] == currAttr))) {
            if (buffer.charArray[base + l][c + addr] < ' ') {
                buffer.charArray[base + l][c + addr] = ' ';
                buffer.charAttributes[base + l][c + addr] = 0;
                continue;
            }
            addr++;
        }

        if (addr > 0) {
            String tmp = new String(buffer.charArray[base + l], c, addr);
            // create new text node and make sure we insert &nbsp; (160)
            Text text = new Text(tmp.replace(' ', (char) 160));
            Element chunk = null;
            if ((currAttr & 0xfff) != 0) {
                if ((currAttr & VDUBuffer.BOLD) != 0) {
                    chunk = addChunk(new Element("B"), chunk, text);
                }
                if ((currAttr & VDUBuffer.UNDERLINE) != 0) {
                    chunk = addChunk(new Element("U"), chunk, text);
                }
                if ((currAttr & VDUBuffer.INVERT) != 0) {
                    chunk = addChunk(new Element("I"), chunk, text);
                }
                if ((currAttr & VDUBuffer.COLOR_FG) != 0) {
                    String fg = color[((currAttr & VDUBuffer.COLOR_FG) >> 4) - 1];
                    Element font = new Element("FONT").setAttribute("COLOR", fg);
                    chunk = addChunk(font, chunk, text);
                }
                /*
                 * if ((currAttr & buffer.COLOR_BG) != 0) { Color bg =
                 * color[((currAttr & buffer.COLOR_BG) >> 8) - 1]; }
                 */
            }
            if (chunk == null) {
                line.addContent(text);
            } else {
                line.addContent(chunk);
            }
        }
        c += addr - 1;
    }
    return line;
}

From source file:io.wcm.handler.commons.dom.Script.java

License:Apache License

/**
 * {@inheritDoc} Overrides standard setText method to add special xHTML conformant CDATA block
 * as workaround for browsers that does not interpret XHTML-encoded script blocks correctly.
 */// ww w  . j  a  v a  2s.c  o m
@Override
public Element setText(String script) {
    if (StringUtils.isEmpty(script)) {
        super.setText(script);
    } else {
        this.addContent(new Text("\n//"));

        // encapsulate script block in CDATA block
        this.addContent(new CDATA("\n" + script + "\n//"));

        this.addContent("\n");
    }
    return this;
}

From source file:io.wcm.handler.richtext.impl.RichTextHandlerImpl.java

License:Apache License

private List<Content> processPlainText(String text) {
    if (StringUtils.isBlank(text)) {
        return ImmutableList.of();
    }//from   w ww . ja  va2 s  .co  m

    List<Content> content = new ArrayList<>();
    String[] lines = StringUtils.splitByWholeSeparatorPreserveAllTokens(text, "\n");
    for (int i = 0; i < lines.length; i++) {
        if (i > 0) {
            content.add(new Element("br"));
        }
        content.add(new Text(lines[i]));
    }

    return ImmutableList.copyOf(content);
}

From source file:org.artifactory.version.converter.v160.MavenIndexerConverter.java

License:Open Source License

private void replaceExcludedWithIncluded(Element rootElement, Namespace namespace, Element indexer,
        Element excludedRepositories) {
    List<String> excluded = excludedRepositories.getChildren().stream().map(Element::getText)
            .collect(Collectors.toList());

    if (StringUtils.equals(indexer.getChildText("enabled", namespace), "true")) {
        Element includedRepositories = new Element("includedRepositories", namespace);
        collectRepositories(rootElement, namespace).stream().filter(repo -> !excluded.contains(repo))
                .forEach(repo -> {//w  w  w.  j  a v  a  2 s  . c o  m
                    Element repositoryRef = new Element("repositoryRef", namespace);
                    repositoryRef.setText(repo);
                    includedRepositories.addContent(repositoryRef);
                });
        indexer.addContent(new Text("\n        "));
        indexer.addContent(includedRepositories);
    }

    indexer.removeContent(excludedRepositories);
}

From source file:org.artifactory.version.converter.v160.SingleRepoTypeConverter.java

License:Open Source License

private void convertToSingleRepoType(Element repo, String repoKey, List<RepoType> repoTypes,
        boolean virtualRepo) {
    if (repoTypes.size() >= 1) {
        repoTypes.stream().skip(1) // First one is used as the final repository type
                .forEach(repoType -> log.error(
                        "Disabling package '{}' for repo '{}' " + "since only one packaging type is allowed!",
                        repoType, repoKey));
    } else {/*from  w  w w  . j a v  a  2s. co  m*/
        String layoutRef = repo.getChildText("repoLayoutRef", repo.getNamespace());
        if (StringUtils.equals(layoutRef, "ivy-default")) {
            repoTypes.add(RepoType.Ivy);
        } else if (StringUtils.equals(layoutRef, "gradle-default")) {
            repoTypes.add(RepoType.Gradle);
        } else {
            repoTypes.add(RepoType.Maven);
        }
    }

    // Set the final decided repo type
    RepoType repoType = repoTypes.get(0);
    log.info("Setting repository '{}' to type {}", repoKey, repoType);
    Element typeElement = new Element("type", repo.getNamespace());
    typeElement.setText(String.valueOf(repoType).toLowerCase());
    repo.addContent(2, new Text("\n            "));
    repo.addContent(3, typeElement); // add the type after the key property
    removeEnabledFieldsFromRepo(repo, virtualRepo);
}

From source file:org.crazyt.xgogdownloader.Util.java

License:Open Source License

public final int createXML(String filepath, int chunk_size, String xml_dir) {
    int res = 0;//from   w w  w. j  a  v a  2s.com
    File infile;
    int filesize;
    int size;
    int chunks;
    int i;
    if (xml_dir == "") {
        xml_dir = ".cache/xgogdownloader/xml";
    } // end of if
    File path = Factory.newFile(xml_dir);
    if (!path.exists()) {
        if (!path.mkdirs()) {
            System.out.println("Failed to create directory: " + path);
        }
    }

    infile = Factory.newFile(filepath);
    // RandomAccessFile file = new RandomAccessFile("file.txt", "rw");?
    // fseek/seek ftell/getFilePointer rewind/seek(0)
    if (infile.exists()) {
        filesize = (int) infile.length();
    } else {
        System.out.println(filepath + " doesn't exist");
        return res;
    } // end of if-else

    // Get filename
    String filename = FilenameUtils.removeExtension(infile.getName());
    String filenameXML = xml_dir + "/" + filename + ".xml";

    System.out.println(filename);
    // Determine number of chunks
    int remaining = filesize % chunk_size;
    chunks = (remaining == 0) ? filesize / chunk_size : (filesize / chunk_size) + 1;
    System.out.println("Filesize: " + filesize + " bytes");
    System.out.println("Chunks: " + chunks);
    System.out.println("Chunk size: " + (chunk_size / Math.pow(2.0, 20.0)) + " MB");
    Util util_md5 = new Util();
    String file_md5 = util_md5.getFileHash(filepath);
    System.out.println("MD5: " + file_md5);

    Element fileElem = new Element("file");
    fileElem.setAttribute(new Attribute("name", filename));
    fileElem.setAttribute(new Attribute("md5", file_md5));
    fileElem.setAttribute(new Attribute("chunks", String.valueOf(chunks)));
    fileElem.setAttribute(new Attribute("total_size", String.valueOf(filesize)));

    System.out.println("Getting MD5 for chunks");
    for (i = 0; i < chunks; i++) {
        int range_begin = i * chunk_size;
        // fseek(infile, range_begin, SEEK_SET);
        if ((i == chunks - 1) && (remaining != 0)) {
            chunk_size = remaining;
        }
        int range_end = range_begin + chunk_size - 1;
        String chunk = String.valueOf(chunk_size * 4);

        String hash = util_md5.getChunkHash(chunk); // calculates hash of
        // chunk string?
        Element chunkElem = new Element("chunk");
        chunkElem.setAttribute(new Attribute("id", String.valueOf(i)));
        chunkElem.setAttribute(new Attribute("from", String.valueOf(range_begin)));
        chunkElem.setAttribute(new Attribute("to", String.valueOf(range_begin)));
        chunkElem.setAttribute(new Attribute("method", "md5"));
        chunkElem.addContent(new Text(hash));
        fileElem.addContent(chunkElem);

        System.out.println("Chunks hashed " + (i + 1) + " / " + chunks + "\r");
    }
    Document doc = new Document(fileElem);

    System.out.println("Writing XML: " + filenameXML);
    try {
        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, Factory.newFileWriter(filenameXML));
        res = 1;
    } catch (IOException e) {
        System.out.println("Can't create " + filenameXML);
        return res;
    }
    return res;
}

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

License:Open Source License

/**
 * Get the filtered content of an element, optionnaly merging adjacent {@link Text}. Adjacent
 * text can only happen programmatically.
 * /*from   ww  w  .j  a  v a  2 s . c om*/
 * @param elem the parent.
 * @param pred which content to return.
 * @param mergeText <code>true</code> if adjacent Text should be merged into one,
 *        <code>false</code> to leave the list as it is.
 * @return the filtered content (not supportting {@link Iterator#remove()}).
 */
public static Iterator<Content> getContent(final Element elem, final IPredicate<? super Content> pred,
        final boolean mergeText) {
    final Iterator<Content> iter = (Iterator<Content>) elem.getContent(new AbstractFilter<Content>() {
        @Override
        public Content filter(Object obj) {
            final Content c = (Content) obj;
            return pred.evaluateChecked(c) ? c : null;
        }
    }).iterator();
    if (!mergeText)
        return iter;

    return new Iterator<Content>() {

        private Content next = null;

        @Override
        public boolean hasNext() {
            return this.next != null || iter.hasNext();
        }

        @Override
        public Content next() {
            if (this.next != null) {
                final Content res = this.next;
                this.next = null;
                return res;
            }

            Content res = iter.next();
            assert res != null;
            if (res instanceof Text && iter.hasNext()) {
                this.next = iter.next();
                Text concatText = null;
                while (this.next instanceof Text) {
                    if (concatText == null) {
                        concatText = new Text(res.getValue());
                    }
                    concatText.append((Text) this.next);
                    this.next = iter.hasNext() ? iter.next() : null;
                }
                assert this.next != null;
                if (concatText != null)
                    res = concatText;
            }

            return res;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}