Example usage for org.jdom2.output Format getPrettyFormat

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

Introduction

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

Prototype

public static Format getPrettyFormat() 

Source Link

Document

Returns a new Format object that performs whitespace beautification with 2-space indents, 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:org.apache.marmotta.maven.plugins.refpack.RefPackMojo.java

License:Apache License

private void writeModuleXML(Artifact module, OutputStream out) throws IOException {
    Element installation = new Element("installation");
    installation.setAttribute("version", "1.0");

    Element packs = new Element("packs");
    installation.addContent(packs);/*from   w w w .j a v  a2s  . co m*/

    Element pack = new Element("pack");
    packs.addContent(pack);

    // get the model for the artifact, we read name and description from it

    Model pom = getArtifactModel(module);

    // set name of pack from artifact
    if (pom != null && pom.getName() != null) {
        pack.setAttribute("name", pom.getName());
    } else {
        pack.setAttribute("name", module.getArtifactId());
    }

    if (pom != null && pom.getDescription() != null) {
        Element description = new Element("description");
        description.setText(Text.normalizeString(pom.getDescription()));
        pack.addContent(description);
    }

    // add a file entry for the module itself
    if (!module.getExtension().equals("war")) {
        Element mainFile = new Element("file");
        pack.addContent(mainFile);
        mainFile.setAttribute("src", module.getFile().getAbsolutePath());
        mainFile.setAttribute("targetdir",
                "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/webapps/marmotta/WEB-INF/lib");
    }

    // add a file entry for each library of the artifact
    for (Artifact library : moduleLibraries.get(module)) {
        Element file = new Element("file");
        pack.addContent(file);
        file.setAttribute("src", library.getFile().getAbsolutePath());
        file.setAttribute("targetdir",
                "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/webapps/marmotta/WEB-INF/lib");
    }

    // add a depends name for each module the current one depends on  (in case the project is not the webapp)
    if (!module.getExtension().equals("war")) {
        if (requiredModules.contains(module.getArtifactId())) {
            pack.setAttribute("required", "yes");
        } else {
            pack.setAttribute("required", "no");
        }

        for (Artifact dependency : moduleDependencies.get(module)) {
            Element depends = new Element("depends");
            pack.addContent(depends);

            // get the model for the artifact, we read name and description from it
            Model pom2 = getArtifactModel(dependency);

            // set name of pack from artifact
            if (pom2 != null && pom2.getName() != null) {
                depends.setAttribute("packname", pom2.getName());
            } else {
                depends.setAttribute("packname", module.getArtifactId());
            }
        }
    } else {
        pack.setAttribute("required", "yes");

        // add webapp directory from installer configuration
        Element appDir = new Element("fileset");
        appDir.setAttribute("dir", outputDirectory + "/../webapp/");
        appDir.setAttribute("targetdir", "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/webapps/marmotta/");
        appDir.setAttribute("includes", "**");

        pack.addContent(appDir);

        Element logDir = new Element("fileset");
        logDir.setAttribute("dir", outputDirectory + "/../log/");

        logDir.setAttribute("targetdir", "$INSTALL_PATH/apache-tomcat-$TOMCAT_VERSION/logs/");
        logDir.setAttribute("includes", "**");

        pack.addContent(logDir);
    }

    XMLOutputter writer = new XMLOutputter(Format.getPrettyFormat());
    writer.output(installation, out);

}

From source file:org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLBooleanHTMLWriter.java

License:Apache License

@Override
public void handleBoolean(boolean value) throws QueryResultHandlerException {
    try {//from   w  w w  .ja  v  a 2  s .  co m
        // Create a SPARQL/XML representation that will be transformed to HTML using a stylesheet
        ByteArrayOutputStream xmlOut = new ByteArrayOutputStream();
        QueryResultIO.writeBoolean(value, BooleanQueryResultFormat.SPARQL, xmlOut);
        byte[] queryResult = xmlOut.toByteArray();

        // get server uri
        String server_uri = CDIContext.getInstance(ConfigurationService.class).getServerUri();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

        Source input = new StreamSource(new ByteArrayInputStream(queryResult));

        Source s_stylesheet = new StreamSource(SPARQLBooleanHTMLWriter.class.getResourceAsStream("style.xsl"));
        Templates stylesheet = TransformerFactory.newInstance().newTemplates(s_stylesheet);
        Transformer transformer = stylesheet.newTransformer();
        transformer.setParameter("serverurl", server_uri);

        JDOMResult result = new JDOMResult();
        transformer.transform(input, result);
        Document output = result.getDocument();

        XMLOutputter printer = new XMLOutputter(Format.getPrettyFormat());
        printer.output(output, writer);
        writer.flush();
    } catch (TransformerConfigurationException e) {
        log.error("could not compile stylesheet for rendering SPARQL results; result display not available!");
        throw new QueryResultHandlerException(
                "could not compile stylesheet for rendering SPARQL results; result display not available!", e);
    } catch (Exception ex) {
        throw new QueryResultHandlerException("error while transforming XML results to HTML", ex);
    } finally {
        // writer.close();
    }
}

From source file:org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLResultsHTMLWriterXSL.java

License:Apache License

/**
 * Indicates the end of a sequence of solutions.
 *//* w ww .j a  va  2s. c o m*/
@Override
public void endQueryResult() throws TupleQueryResultHandlerException {
    writer.endQueryResult();

    // get server uri
    String server_uri = CDIContext.getInstance(ConfigurationService.class).getServerUri();

    byte[] queryResult = xmlOut.toByteArray();

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
    try {
        Source input = new StreamSource(new ByteArrayInputStream(queryResult));

        Transformer transformer = stylesheet.newTransformer();
        transformer.setParameter("serverurl", server_uri);

        JDOMResult result = new JDOMResult();
        transformer.transform(input, result);
        Document output = result.getDocument();

        XMLOutputter printer = new XMLOutputter(Format.getPrettyFormat());
        printer.output(output, writer);
        writer.flush();

    } catch (Exception ex) {
        throw new TupleQueryResultHandlerException("error while transforming XML results to HTML", ex);
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
        }
    }

}

From source file:org.apache.wiki.util.XhtmlUtil.java

License:Apache License

/**
 *  Serializes the Element to a String. If <tt>pretty</tt> is true,
 *  uses a pretty whitespace format, otherwise a compact format.
 *  // ww w.  j  a  v  a 2  s  .  c  om
 * @param element  the element to serialize.
 * @param pretty   if true, use a pretty whitespace format.
 * @return the serialized Element.
 */
public static String serialize(Element element, boolean pretty) {
    return serialize(element, pretty ? Format.getPrettyFormat() : Format.getCompactFormat());
}

From source file:org.artifactory.webapp.wicket.page.home.settings.ivy.IvySettingsPanel.java

License:Open Source License

@Override
public String generateSettings() {
    Document document = new Document();
    Element rootNode = new Element("ivy-settings");

    Element settingsElement = new Element("settings");
    settingsElement.setAttribute("defaultResolver", "main");
    rootNode.addContent(settingsElement);

    if (!authorizationService.isAnonymous() || !authorizationService.isAnonAccessEnabled()) {
        rootNode.addContent(/*from   www  .j ava  2 s. c o  m*/
                new Comment("Authentication required for publishing (deployment). 'Artifactory Realm' is "
                        + "the realm used by Artifactory so don't change it."));

        Element credentialsElement = new Element("credentials");
        try {
            credentialsElement.setAttribute("host", new URL(servletContextUrl).getHost());
        } catch (MalformedURLException e) {
            String errorMessage = "An error occurred while decoding the servlet context URL for the credentials host attribute: ";
            error(errorMessage + e.getMessage());
            log.error(errorMessage, e);
        }
        credentialsElement.setAttribute("realm", "Artifactory Realm");

        FilteredResourcesWebAddon filteredResourcesWebAddon = addonsManager
                .addonByType(FilteredResourcesWebAddon.class);

        credentialsElement.setAttribute("username",
                filteredResourcesWebAddon.getGeneratedSettingsUsernameTemplate());

        credentialsElement.setAttribute("passwd", "@PASS_ATTR_PLACEHOLDER@");

        rootNode.addContent(credentialsElement);
    }

    Element resolversElement = new Element("resolvers");

    Element chainElement = new Element("chain");
    chainElement.setAttribute("name", "main");

    String resolverName = resolverPanel.getResolverName();
    resolverName = StringUtils.isNotBlank(resolverName) ? resolverName : "public";

    if (resolverPanel.useIbiblioResolver()) {

        Element ibiblioElement = new Element("ibiblio");
        ibiblioElement.setAttribute("name", resolverName);
        ibiblioElement.setAttribute("m2compatible", Boolean.TRUE.toString());
        ibiblioElement.setAttribute("root", resolverPanel.getFullRepositoryUrl());
        chainElement.addContent(ibiblioElement);
    } else {

        Element urlElement = new Element("url");
        urlElement.setAttribute("name", resolverName);

        urlElement.setAttribute("m2compatible", Boolean.toString(resolverPanel.isM2Compatible()));

        Element artifactPatternElement = new Element("artifact");
        artifactPatternElement.setAttribute("pattern", resolverPanel.getFullArtifactPattern());
        urlElement.addContent(artifactPatternElement);

        Element ivyPatternElement = new Element("ivy");
        ivyPatternElement.setAttribute("pattern", resolverPanel.getFullDescriptorPattern());
        urlElement.addContent(ivyPatternElement);

        chainElement.addContent(urlElement);
    }

    resolversElement.addContent(chainElement);

    rootNode.addContent(resolversElement);

    document.setRootElement(rootNode);

    String result = new XMLOutputter(Format.getPrettyFormat()).outputString(document);
    // after the xml is generated replace the password placeholder with the template placeholder (otherwise jdom
    // escapes this string)
    FilteredResourcesWebAddon filteredResourcesWebAddon = addonsManager
            .addonByType(FilteredResourcesWebAddon.class);
    return result.replace("@PASS_ATTR_PLACEHOLDER@",
            filteredResourcesWebAddon.getGeneratedSettingsUserCredentialsTemplate(false));
}

From source file:org.blip.workflowengine.configuration.XmlConfigWrite.java

License:Apache License

default void write(final Microservice microservice, final File file) throws IOException {
    Objects.requireNonNull(microservice, "microservice argument is null");
    Objects.requireNonNull(file, "file argument is null");

    if (!file.isFile()) {
        throw new IllegalArgumentException("Not a file");
    } else if (!file.canWrite()) {
        throw new IllegalArgumentException("Can't write to file");
    }//from  ww w .j a  va 2 s. co m

    final XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    final Document document = new Document(microserviceToXml().apply(microservice));
    out.output(document, new FileOutputStream(file));
}

From source file:org.blip.workflowengine.functions.PropertyNodeXmlFunctions.java

License:Apache License

default Function<Element, Value> xmlToValue() {
    return element -> {
        Objects.requireNonNull(element, "element is null");

        final String name = element.getName();

        if (name.contentEquals("null")) {
            return ImmutableValue.of(null);
        } else if (name.contentEquals("boolean")) {
            return ImmutableValue.of(Boolean.valueOf(element.getValue()));
        } else if (name.contentEquals("instant")) {
            return ImmutableValue.of(Instant.parse(element.getValue()));
        } else if (name.contentEquals(("byte-array"))) {
            final String base64Encoded = element.getValue();
            final byte[] binary = Base64.getDecoder().decode(base64Encoded.getBytes(Charset.forName("UTF-8")));
            return ImmutableValue.of(binary);
        } else if (name.contentEquals("string")) {
            return ImmutableValue.of(element.getValue());
        } else if (name.contentEquals("byte")) {
            return ImmutableValue.of(Byte.valueOf(element.getValue()));
        } else if (name.contentEquals("short")) {
            return ImmutableValue.of(Short.valueOf(element.getValue()));
        } else if (name.contentEquals("integer")) {
            return ImmutableValue.of(Integer.valueOf(element.getValue()));
        } else if (name.contentEquals("long")) {
            return ImmutableValue.of(Long.valueOf(element.getValue()));
        } else if (name.contentEquals("float")) {
            return ImmutableValue.of(Float.valueOf(element.getValue()));
        } else if (name.contentEquals("double")) {
            return ImmutableValue.of(Double.valueOf(element.getValue()));
        } else if (name.contentEquals("collection")) {
            final ImmutableList.Builder<Object> objectBuilder = ImmutableList.builder();
            for (final Element element1 : element.getChildren()) {
                if (element1.getName().contentEquals("entry")) {
                    final List<Element> children = element1.getChildren();
                    if (children.size() == 2) {
                        final Element keyElement = children.get(0);
                        final Element valueElement = children.get(1);

                        final Value key = xmlToValue().apply(keyElement);
                        final Value value = xmlToValue().apply(valueElement);
                        final Map.Entry entry = new AbstractMap.SimpleEntry(key.value(), value.value());
                        objectBuilder.add(entry);
                    }/*w  w  w . j  a va2  s .c om*/
                } else {
                    final Object rawValue = xmlToValue().apply(element1).value();
                    if (Objects.nonNull(rawValue)) {
                        objectBuilder.add(rawValue);
                    }
                }
            }

            return ImmutableValue.of(objectBuilder.build());
        } else if (name.contentEquals("property-node")) {
            return ImmutableValue.of((xmlToPropertyNode().apply(element)));
        } else {
            throw new IllegalArgumentException(
                    new XMLOutputter(Format.getPrettyFormat()).outputString(element));
        }
    };
}

From source file:org.blip.workflowengine.functions.PropertyNodeXmlFunctions.java

License:Apache License

default Element xpath(final PropertyNode propertyNode, final String expression) throws XPathException {
    Objects.requireNonNull(propertyNode, "propertyNode is null");
    Objects.requireNonNull(expression, "XPath expression is null");
    if (expression.trim().isEmpty()) {
        throw new IllegalArgumentException("XPath expression is empty");
    }/*from  w w w  .  j av  a2s.c om*/

    try {
        final Processor processor = new Processor(false);
        final DocumentBuilder builder = processor.newDocumentBuilder();
        final XPathCompiler xpc = processor.newXPathCompiler();

        final XPathSelector selector = xpc.compile(expression).load();
        final Element element = propertyNodeToXml().apply(propertyNode);
        final XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        xmlOutputter.output(element, baos);
        final Reader reader = new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()),
                String.valueOf(Charset.forName("UTF-8")));
        final InputSource inputSource = new InputSource(reader);
        inputSource.setEncoding(String.valueOf(Charset.forName("UTF-8")));

        selector.setContextItem(builder.build(new SAXSource(inputSource)));
        final XdmValue xdmValue = selector.evaluate();

        final String content = String.format("<%s>%s</%s>", "XPathResult", xdmValue.toString(), "XPathResult");
        final Document doc = new SAXBuilder().build(new StringReader(content));

        return doc.getRootElement();

    } catch (Exception exception) {
        throw new XPathException(exception);
    }

}

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 a2  s.  c om*/
    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.educautecisystems.core.Sistema.java

License:Open Source License

public static void guardarConfPrincipal() {
    File archivoConfPrincipal = new File(pathGeneralConf);

    if (archivoConfPrincipal.exists()) {
        archivoConfPrincipal.delete();//from w  w  w . java 2s . c  o  m
    }

    Document documento = new Document();

    Namespace baseNamespace = Namespace.getNamespace("eus", "http://educautecisystems.org/");
    Element root = new Element("config", baseNamespace);
    documento.setRootElement(root);

    Element eBaseDeDatos = new Element("database", baseNamespace);
    eBaseDeDatos.addContent(new Element("host").setText(confBaseDeDatos.getHost()));
    eBaseDeDatos.addContent(new Element("port").setText(confBaseDeDatos.getPort()));
    eBaseDeDatos.addContent(new Element("user").setText(confBaseDeDatos.getUser()));
    eBaseDeDatos.addContent(new Element("password").setText(confBaseDeDatos.getPassword()));
    eBaseDeDatos.addContent(new Element("esquema").setText(confBaseDeDatos.getEsquema()));
    root.addContent(eBaseDeDatos);

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());

    try {
        FileOutputStream fis = new FileOutputStream(archivoConfPrincipal);
        outputter.output(documento, fis);
        fis.close();
    } catch (IOException ioe) {
        System.err.println("No se pudo escribor configuracin principal.");
    }
}