Example usage for org.jdom2.output Format getRawFormat

List of usage examples for org.jdom2.output Format getRawFormat

Introduction

In this page you can find the example usage for org.jdom2.output Format getRawFormat.

Prototype

public static Format getRawFormat() 

Source Link

Document

Returns a new Format object that performs no whitespace changes, uses the UTF-8 encoding, doesn't expand empty elements, includes the declaration and encoding, and uses the default entity escape strategy.

Usage

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.FormulaConverter.java

License:Open Source License

/**
 * Replaces all formulas with the html representation of the mapped formula objects
 *
 * @param doc        JDOM Document where to replace the formulas
 * @param formulaMap Map of the indexed Formula Objects
 * @return JDOM Document with replaced formulas
 *//*from  w  w  w  .  j  a v a  2 s .c  o  m*/
public Document replaceFormulas(Document doc, Map<Integer, Formula> formulaMap) {
    List<Element> foundFormulas = xpath.evaluate(doc);

    if (foundFormulas.size() > 0) {
        Map<String, Element> formulaMarkupMap = new HashMap<>();

        // Initialize markup map
        for (Element element : foundFormulas) {
            formulaMarkupMap.put(element.getAttribute("id").getValue(), element);
        }

        // Replace all found formulas
        Iterator<Integer> formulaIterator = formulaMap.keySet().iterator();
        while (formulaIterator.hasNext()) {
            Integer id = formulaIterator.next();

            Element formulaMarkupRoot = formulaMarkupMap.get(FORMULA_ID_PREFIX + id);
            Formula formula = formulaMap.get(id);

            formulaMarkupRoot.removeAttribute("class");
            formulaMarkupRoot.removeContent();
            formulaMarkupRoot.setName("div");

            Element div = (Element) formulaMarkupRoot.getParent();
            div.setName("div");
            div.setAttribute("class", "formula");

            // Potentially there's text inside the paragraph...
            List<Text> texts = div.getContent(Filters.textOnly());
            if (texts.isEmpty() == false) {
                String textString = "";
                for (Text text : texts) {
                    textString += text.getText();
                }
                Element textSpan = new Element("span");
                textSpan.setAttribute("class", "text");
                textSpan.setText(textString);
                div.addContent(textSpan);

                List<Content> content = div.getContent();
                content.removeAll(texts);
            }

            if (generateDebugMarkup) {
                div.setAttribute("style", "border: 1px solid black;");

                // Header
                Element h4 = new Element("h4");
                h4.setText("DEBUG - Formula #" + formula.getId());
                div.addContent(h4);

                // Render LaTeX source
                Element latexPre = new Element("pre");
                latexPre.setAttribute("class", "debug-latex");
                latexPre.setText(formula.getLatexCode());
                div.addContent(latexPre);

                // Render MathML markup
                Element mathmlPre = new Element("pre");
                mathmlPre.setAttribute("class", "debug-mathml");
                mathmlPre.setText(formula.getMathMl());
                div.addContent(mathmlPre);

                // Render HTML Markup
                Element htmlPre = new Element("pre");
                htmlPre.setAttribute("class", "debug-html");
                XMLOutputter xmlOutputter = new XMLOutputter();
                xmlOutputter.setFormat(Format.getRawFormat());
                htmlPre.setText(xmlOutputter.outputString(formula.getHtml()));

                div.addContent(htmlPre);

            }

            // Set formula into
            formulaMarkupRoot.addContent(formula.getHtml());
        }
    }
    return doc;
}

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void createTargetFile(JobBO p_job, String[] p_targetSegments) throws IOException {
    OutputStream writer = null;/*w ww  .  j a  va  2  s .com*/
    File fileStorage = CommonDAO.getFileStorage();
    File srcFile = p_job.getSrcFile();
    Account account = DispatcherDAOFactory.getAccountDAO().getAccount(p_job.getAccountId());
    File trgDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator + p_job.getJobID()
            + File.separator + AppConstants.XLF_TARGET_FOLDER);
    File trgFile = new File(trgDir, srcFile.getName());
    FileUtils.copyFile(srcFile, trgFile);
    String encoding = FileUtil.getEncodingOfXml(trgFile);

    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(p_job.getSrcFile());
        Element root = doc.getRootElement(); // Get root element
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> tuList = expr.evaluate(fileElem.getChild("body", namespace));
        for (int tuIndex = 0, trgIndex = 0; tuIndex < tuList.size()
                && trgIndex < p_targetSegments.length; tuIndex++, trgIndex++) {
            if (p_targetSegments[trgIndex] == null) {
                continue;
            }

            Element elem = (Element) tuList.get(tuIndex);
            Element srcElem = elem.getChild("source", namespace);
            Element trgElem = elem.getChild("target", namespace);
            if (srcElem == null || srcElem.getContentSize() == 0) {
                trgIndex--;
                continue;
            }

            if (trgElem != null) {
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
            } else {
                trgElem = new Element("target", namespace);
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
                elem.addContent(trgElem);
            }

        }

        XMLOutputter xmlOutput = new XMLOutputter();
        Format format = Format.getRawFormat();
        format.setEncoding(encoding);
        writer = new FileOutputStream(trgFile);
        xmlOutput.setFormat(format);
        writeBOM(writer, format.getEncoding());
        xmlOutput.output(doc, writer);
        p_job.setTrgFile(trgFile);
        logger.info("Create Target File: " + trgFile);
    } catch (JDOMException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } catch (IOException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.googlecode.mipnp.mediaserver.cds.DidlLiteDocument.java

License:Open Source License

@Override
public String toString() {
    Format format = Format.getRawFormat();
    format.setOmitDeclaration(true);//www .j  a v a  2s  .  c o  m
    XMLOutputter outputter = new XMLOutputter(format);
    return outputter.outputString(document);
}

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

License:Open Source License

static String rsToChaiXML(final ChaiResponseSet rs) throws ChaiValidationException, ChaiOperationException {
    final Element rootElement = new Element(XML_NODE_ROOT);
    rootElement.setAttribute(XML_ATTRIBUTE_MIN_RANDOM_REQUIRED,
            String.valueOf(rs.getChallengeSet().getMinRandomRequired()));
    rootElement.setAttribute(XML_ATTRIBUTE_LOCALE, rs.getChallengeSet().getLocale().toString());
    rootElement.setAttribute(XML_ATTRIBUTE_VERSION, VALUE_VERSION);
    rootElement.setAttribute(XML_ATTRIBUTE_CHAI_VERSION, ChaiConstant.CHAI_API_VERSION);

    if (rs.caseInsensitive) {
        rootElement.setAttribute(XML_ATTRIBUTE_CASE_INSENSITIVE, "true");
    }//from w ww  .ja va  2s.co m

    if (rs.csIdentifier != null) {
        rootElement.setAttribute(XML_ATTRIBUTE_CHALLENGE_SET_IDENTIFER, rs.csIdentifier);
    }

    if (rs.timestamp != null) {
        rootElement.setAttribute(XML_ATTRIBUTE_TIMESTAMP, DATE_FORMATTER.format(rs.timestamp));
    }

    if (rs.crMap != null) {
        for (final Challenge loopChallenge : rs.crMap.keySet()) {
            final Answer answer = rs.crMap.get(loopChallenge);
            final Element responseElement = challengeToXml(loopChallenge, answer, XML_NODE_RESPONSE);
            rootElement.addContent(responseElement);
        }
    }

    if (rs.helpdeskCrMap != null) {
        for (final Challenge loopChallenge : rs.helpdeskCrMap.keySet()) {
            final Answer answer = rs.helpdeskCrMap.get(loopChallenge);
            final Element responseElement = challengeToXml(loopChallenge, answer, XML_NODE_HELPDESK_RESPONSE);
            rootElement.addContent(responseElement);
        }
    }

    final Document doc = new Document(rootElement);
    final XMLOutputter outputter = new XMLOutputter();
    final Format format = Format.getRawFormat();
    format.setTextMode(Format.TextMode.PRESERVE);
    format.setLineSeparator("");
    outputter.setFormat(format);
    return outputter.outputString(doc);
}

From source file:com.novell.ldapchai.impl.edir.NmasResponseSet.java

License:Open Source License

static String csToNmasXML(final ChallengeSet cs, final String guidValue) {
    final Element rootElement = new Element(NMAS_XML_ROOTNODE);
    rootElement.setAttribute(NMAS_XML_ATTR_RANDOM_COUNT, String.valueOf(cs.getMinRandomRequired()));
    if (guidValue != null) {
        rootElement.setAttribute("GUID", guidValue);
    } else {//from   ww  w. jav a 2  s  .c om
        rootElement.setAttribute("GUID", "0");
    }

    for (final Challenge challenge : cs.getChallenges()) {
        final Element loopElement = new Element(NMAS_XML_NODE_CHALLENGE);
        if (challenge.getChallengeText() != null) {
            loopElement.setText(challenge.getChallengeText());
        }

        if (challenge.isAdminDefined()) {
            loopElement.setAttribute(NMAS_XML_ATTR_DEFINE, "Admin");
        } else {
            loopElement.setAttribute(NMAS_XML_ATTR_DEFINE, "User");
        }

        if (challenge.isRequired()) {
            loopElement.setAttribute(NMAS_XML_ATTR_TYPE, "Required");
        } else {
            loopElement.setAttribute(NMAS_XML_ATTR_TYPE, "Random");
        }

        loopElement.setAttribute(NMAS_XML_ATTR_MIN_LENGTH, String.valueOf(challenge.getMinLength()));
        loopElement.setAttribute(NMAS_XML_ATTR_MAX_LENGTH, String.valueOf(challenge.getMaxLength()));

        rootElement.addContent(loopElement);
    }

    final XMLOutputter outputter = new XMLOutputter();
    final Format format = Format.getRawFormat();
    format.setTextMode(Format.TextMode.PRESERVE);
    format.setLineSeparator("");
    outputter.setFormat(format);
    return outputter.outputString(rootElement);
}

From source file:com.xebialabs.overcast.support.libvirt.JDomUtil.java

License:Apache License

public static String documentToRawString(Document xml) throws IOException {
    return documentToString(xml, Format.getRawFormat().setOmitDeclaration(true)).trim();
}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

public Response execute(RequestBuilder b) {
    try {//from  w w  w.ja  v  a 2  s .c  om

        String method = b.getMethod();
        Preconditions.checkArgument(!Strings.isNullOrEmpty(method), "method argument must be passed");

        String url = null;

        Response resp;
        String format = b.getParams().getOrDefault("format", "xml");
        b = b.param("format", format);
        if (!b.hasBody()) {

            url = formatUrl(b.getParams(), format);
            FormEncodingBuilder fb = new FormEncodingBuilder().add("session_id", getAuthToken());
            for (Map.Entry<String, String> entry : b.getParams().entrySet()) {
                if (!entry.getValue().equals("format")) {
                    fb = fb.add(entry.getKey(), entry.getValue());
                }
            }
            resp = getClient().newCall(new Request.Builder().url(getUrl()).post(fb.build()).build()).execute();
        } else if (b.getXmlBody().isPresent()) {
            b = b.param("format", "xml");
            url = formatUrl(b.getParams(), "xml");
            String bodyAsString = new XMLOutputter(Format.getRawFormat()).outputString(b.getXmlBody().get());
            final MediaType XML = MediaType.parse("text/xml");

            resp = getClient().newCall(new Request.Builder().url(url)
                    .post(RequestBody.create(XML, bodyAsString)).header("Content-Type", "text/xml").build())
                    .execute();
        } else if (b.getJsonBody().isPresent()) {
            b = b.param("format", "json");
            url = formatUrl(b.getParams(), "json");
            String bodyAsString = mapper.writeValueAsString(b.getJsonBody().get());

            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            resp = getClient().newCall(new Request.Builder().url(url).post(

                    RequestBody.create(JSON, bodyAsString)).header("Content-Type", "application/json").build())
                    .execute();
        } else {
            throw new UnsupportedOperationException("body type not supported");
        }
        // the A10 API rather stupidly uses 200 responses even when there is
        // an error
        if (!resp.isSuccessful()) {
            logger.warn("response code={}", resp.code());
        }

        return resp;

    } catch (IOException e) {
        throw new ElbException(e);
    }
}

From source file:jodtemplate.util.JDOMHelper.java

License:Apache License

public String getRawContents(final Document dom) throws IOException {
    final Format format = Format.getRawFormat();
    format.setLineSeparator(LineSeparator.UNIX);
    final XMLOutputter outputter = new XMLOutputter(format, new StandaloneOutputProcessor());
    final Writer writer = new StringWriter();
    outputter.output(dom, writer);/*from   w  w  w .  j  av  a  2  s  .c  o m*/
    return writer.toString();
}

From source file:jodtemplate.util.JDOMHelper.java

License:Apache License

public void write(final Document dom, final OutputStream stream) throws IOException {
    final Format format = Format.getRawFormat();
    format.setLineSeparator(LineSeparator.UNIX);
    final XMLOutputter outputter = new XMLOutputter(format, new StandaloneOutputProcessor());
    outputter.output(dom, stream);//from w w w .  j a  v a  2 s. c  o  m
}

From source file:mx.com.pixup.portal.dao.MunicipioGenerateDaoJdbc.java

public void generateXML(int idMunicipioPasado) {

    //querys/*from   w ww  .  ja v a  2s. c o m*/
    String sql = "SELECT * from municipio WHERE id = ?";

    try {
        //seccion de preparacion de la query
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, idMunicipioPasado);
        ResultSet resultSet = preparedStatement.executeQuery();
        //seccion de nodo raiz

        resultSet.next();
        /*while (resultSet.next()) {
                
        //aqu se hace la magia para el XML
        }*/
        Element municipio = new Element("municipio");
        Attribute id = new Attribute("id", Integer.toString(resultSet.getInt("id")));

        this.xmlLogico.setRootElement(municipio);
        municipio.setAttribute(id);

        //Elementos de 2do nivel
        Element nombre = new Element("nombre");
        nombre.setText(resultSet.getString("nombre"));
        Element id_estado = new Element("id_estado");
        id_estado.setText(Integer.toString(resultSet.getInt("id_estado")));

        municipio.addContent(nombre);
        municipio.addContent(id_estado);

        //se genera el xml fsico
        this.xmlFisico.setFormat(Format.getRawFormat());
        this.xmlFisico.output(this.xmlLogico, this.archivoFisico);
    } catch (Exception e) {
        //*** se quit el return porque el mtodo es void
        System.out.println(e.getMessage());
    }

}