Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:com.orange.atk.atkUI.coregui.PhoneConfigurationWizard.java

License:Apache License

/**
 * call when user has changed configuration in interface
 *//*from  w  w w  .j av a  2  s. c o m*/
private void saveconfig() {
    //build xml
    Logger.getLogger(this.getClass()).debug("save config");
    Document configxml = DocumentHelper.createDocument();
    Element root = configxml.addElement("confile");

    Element graphlist = root.addElement("graphlist");

    //global graph
    for (int i = 0; i < graphs.getSize(); i++) {
        graphlist.addElement("graph").addAttribute("name", graphs.getName(i))
                .addAttribute("color", graphs.getColor(i)).addAttribute("xcomment", graphs.getcommentX(i))
                .addAttribute("ycomment", graphs.getcommentY(i)).addAttribute("unit", graphs.getunit(i))
                .addAttribute("scale", graphs.getscale(i)).addAttribute("sampled", graphs.getsampled(i));
    }

    //table Graph
    if (tablemodel != null)
        for (int i = 0; i < tablemodel.getRowCount(); i++) {
            //don't save non-fill row
            String processname = (String) tablemodel.getValueAt(i, 0);
            String type = (String) tablemodel.getValueAt(i, 1);
            String color = (String) tablemodel.getValueAt(i, 2);

            if ("process".equals(processname) || "color".equals(color) || "Cpu or Mem".equals(type)) {
                JOptionPane.showMessageDialog(null,
                        "You must select the process, the color AND the type! \nThe line will be ignored.");
                continue;
            }

            String unit = "";
            String scale = "1";
            if (type.equals("Cpu"))
                unit = "%";
            else if (type.equals("Memory")) {
                unit = "KBytes";
            } else if (type.equals("Data sent")) {
                unit = "KBytes";
                scale = "1000";
            } else if (type.equals("Data received")) {
                unit = "KBytes";
                scale = "1000";
            }
            graphlist.addElement("graph").addAttribute("name", type + "_" + processname)
                    .addAttribute("color", color).addAttribute("xcomment", "time (min)")
                    .addAttribute("ycomment", type + " " + processname).addAttribute("unit", unit)
                    .addAttribute("scale", scale).addAttribute("sampled", "true");
        }

    //marker
    Element markerlist = root.addElement("markerlist");
    for (int i = 0; i < events.getSize(); i++)
        markerlist.addElement("marker").addAttribute("name", events.getName(i)).addAttribute("color", "gray")
                .addAttribute("position", events.getPosition(i).toString());

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(configpath), format);
        writer.write(configxml);

        //
        //            XMLWriter out = new XMLWriter(System.out,format);
        //            out.write(configxml);

    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (writer != null)
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

}

From source file:com.orange.atk.phone.android.wizard.AndroidWizard.java

License:Apache License

public void printReport() {
    String configXmlFileName = configFileName + ".xml";

    Document configxml = DocumentHelper.createDocument();

    configxml.addComment("  " + phone.getName() + " configuration file   ");
    configxml.addComment("   Screen resolution " + screenWidth + "x" + screenHeight + "   ");

    Element root = configxml.addElement("Android-config");

    Element canalPattern = root.addElement("CanalPattern");

    //keyboards//www  .  ja v a 2  s  .  c  o  m
    if (!keyboard.equals(""))
        printKeyMapping("keyboard", keyboard, canalPattern, root);
    if (!keyboard2.equals(""))
        printKeyMapping("keyboard2", keyboard2, canalPattern, root);
    if (!keyboard3.equals(""))
        printKeyMapping("keyboard3", keyboard3, canalPattern, root);

    Set<String> softKeySet = softKeyMap.keySet();

    Element keyMapping = root.addElement("SoftKeyMapping");
    for (String key : softKeySet) {
        keyMapping.addElement("Key").addAttribute("name", key)
                .addAttribute("avgX", "" + softKeyMap.get(key).getX())
                .addAttribute("avgY", "" + softKeyMap.get(key).getY());
    }

    //touchscreen
    if (!touchscreen.equals("")) {
        canalPattern.addElement("Pattern").addAttribute("canal", "touchscreen").addAttribute("value",
                touchscreen.replace("\"", ""));
        Element Touchscreen = root.addElement("Touchscreen");

        Touchscreen.addComment("!!! THIS IS JUST TOUCHSCREEN Elements TEMPLATE !!!");
        Touchscreen
                .addComment("!!! SEE ATK User Guide - Configuration section - and UPDATE following values !!!");
        if (codeX != -1 && codeY != -1) {
            Touchscreen.addComment("!!! Please check following X Y ratioX and ratioY patterns");
            Touchscreen.addElement("Pattern").addAttribute("name", "X").addAttribute("value",
                    "3 " + codeX + " ");
            Touchscreen.addElement("Pattern").addAttribute("name", "Y").addAttribute("value",
                    "3 " + codeY + " ");
            long ratio = maxX * 100 / screenWidth;
            Touchscreen.addElement("Pattern").addAttribute("name", "ratioX").addAttribute("value",
                    String.valueOf((double) ratio / 100.0));
            ratio = maxY * 100 / screenHeight;
            Touchscreen.addElement("Pattern").addAttribute("name", "ratioY").addAttribute("value",
                    String.valueOf((double) ratio / 100.0));
            Touchscreen.addComment("!!! Please update following patterns");
        } else {
            Touchscreen.addElement("Pattern").addAttribute("name", "X").addAttribute("value", "0 0 ");
            Touchscreen.addElement("Pattern").addAttribute("name", "Y").addAttribute("value", "0 0 ");
            Touchscreen.addElement("Pattern").addAttribute("name", "ratioX").addAttribute("value", "1.0");
            Touchscreen.addElement("Pattern").addAttribute("name", "ratioY").addAttribute("value", "1.0");
        }
        Touchscreen.addElement("Pattern").addAttribute("name", "down").addAttribute("value", "0 0 0");
        Touchscreen.addElement("Pattern").addAttribute("name", "downmax").addAttribute("value", "0 0 0");
        Touchscreen.addElement("Pattern").addAttribute("name", "up").addAttribute("value", "0 0 0");
        Touchscreen.addElement("Pattern").addAttribute("name", "flush").addAttribute("value", "0 0 0");
        Touchscreen.addElement("Pattern").addAttribute("name", "flush2").addAttribute("value", "0 2 0");
        Touchscreen.addElement("Threshold").addAttribute("name", "move").addAttribute("value", "15");
        Touchscreen.addElement("Option").addAttribute("name", "sendMouseDownForMove").addAttribute("value",
                "true");
        Touchscreen.addElement("Option").addAttribute("name", "sendMouseEventFirst").addAttribute("value",
                "true");
        Touchscreen.addElement("Option").addAttribute("name", "useMonkeyForPress").addAttribute("value",
                "true");
    }

    //Write the file.
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(configXmlFileName), format);
        writer.write(configxml);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //Show a confirm dialog and exit the wizard
    JOptionPane.showConfirmDialog(this,
            "A template of the config file has been created under \n" + configXmlFileName + "\n"
                    + "See ATK User guide to configure the Touchscreen section of this template\n",
            "Success", JOptionPane.CLOSED_OPTION);
    exit(true);

}

From source file:com.ostrichemulators.semtool.ui.components.playsheets.BrowserPlaySheet2.java

License:Open Source License

protected BufferedImage getExportImageFromSVGBlock() throws IOException {
    log.debug("Using SVG block to save image.");
    DOMReader rdr = new DOMReader();
    Document doc = rdr.read(engine.getDocument());
    Document svgdoc = null;/*  w w  w  . j ava2  s.  c o  m*/
    File svgfile = null;
    try {
        Map<String, String> namespaceUris = new HashMap<>();
        namespaceUris.put("svg", "http://www.w3.org/2000/svg");
        namespaceUris.put("xhtml", "http://www.w3.org/1999/xhtml");

        XPath xp = DocumentHelper.createXPath("//svg:svg");
        xp.setNamespaceURIs(namespaceUris);
        // don't forget about the styles
        XPath stylexp = DocumentHelper.createXPath("//xhtml:style");
        stylexp.setNamespaceURIs(namespaceUris);

        svgdoc = DocumentHelper.createDocument();
        Element svg = null;
        List<?> theSVGElements = xp.selectNodes(doc);
        if (theSVGElements.size() == 1) {
            svg = Element.class.cast(theSVGElements.get(0)).createCopy();
        } else {
            int currentTop = 0;
            int biggestSize = 0;
            for (int i = 0; i < theSVGElements.size(); i++) {
                Element thisElement = Element.class.cast(theSVGElements.get(i)).createCopy();
                int thisSize = thisElement.asXML().length();
                if (thisSize > biggestSize) {
                    currentTop = i;
                    biggestSize = thisSize;
                }
            }
            svg = Element.class.cast(theSVGElements.get(currentTop)).createCopy();
        }

        svgdoc.setRootElement(svg);

        Element oldstyle = Element.class.cast(stylexp.selectSingleNode(doc));
        if (null != oldstyle) {
            Element defs = svg.addElement("defs");
            Element style = defs.addElement("style");
            style.addAttribute("type", "text/css");
            String styledata = oldstyle.getTextTrim();
            style.addCDATA(styledata);
            // put the stylesheet definitions first
            List l = svg.elements();
            l.remove(defs);
            l.add(0, defs);
        }

        // clean up the SVG a little...
        // d3 comes up with coords like
        // M360,27475.063247863247C450,27475.063247863247 450,27269.907692307694 540,27269.907692307694
        XPath cleanxp1 = DocumentHelper.createXPath("//svg:path");
        Pattern pat = Pattern.compile(",([0-9]+)\\.([0-9]{1,2})[0-9]+");
        cleanxp1.setNamespaceURIs(namespaceUris);
        List<?> cleanups = cleanxp1.selectNodes(svgdoc);
        for (Object n : cleanups) {
            Element e = Element.class.cast(n);
            String dstr = e.attributeValue("d");
            Matcher m = pat.matcher(dstr);
            dstr = m.replaceAll(",$1.$2 ");
            e.addAttribute("d", dstr.replaceAll("([0-9])C([0-9])", "$1 C$2").trim());
        }
        XPath cleanxp2 = DocumentHelper.createXPath("//svg:g[@class='node']");
        cleanxp2.setNamespaceURIs(namespaceUris);
        cleanups = cleanxp2.selectNodes(svgdoc);
        for (Object n : cleanups) {
            Element e = Element.class.cast(n);
            String dstr = e.attributeValue("transform");
            Matcher m = pat.matcher(dstr);
            dstr = m.replaceAll(",$1.$2");
            e.addAttribute("transform", dstr.trim());
        }

        svgfile = File.createTempFile("graphviz-", ".svg");
        try (Writer svgw = new BufferedWriter(new FileWriter(svgfile))) {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlw = new XMLWriter(svgw, format);
            xmlw.write(svgdoc);
            xmlw.close();

            if (log.isDebugEnabled()) {
                FileUtils.copyFile(svgfile, new File(FileUtils.getTempDirectory(), "graphvisualization.svg"));
            }
        }

        try (Reader svgr = new BufferedReader(new FileReader(svgfile))) {
            TranscoderInput inputSvg = new TranscoderInput(svgr);

            ByteArrayOutputStream baos = new ByteArrayOutputStream((int) svgfile.length());
            TranscoderOutput outputPng = new TranscoderOutput(baos);

            try {
                PNGTranscoder transcoder = new PNGTranscoder();
                transcoder.addTranscodingHint(PNGTranscoder.KEY_INDEXED, 256);
                transcoder.addTranscodingHint(ImageTranscoder.KEY_BACKGROUND_COLOR, Color.WHITE);
                transcoder.transcode(inputSvg, outputPng);
            } catch (Throwable t) {
                log.error(t, t);
            }
            baos.flush();
            baos.close();

            return ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
        }
    } catch (InvalidXPathException e) {
        log.error(e);
        String msg = "Problem creating image";
        if (null != svgdoc) {
            try {
                File errsvg = new File(FileUtils.getTempDirectory(), "graphvisualization.svg");
                FileUtils.write(errsvg, svgdoc.asXML(), Charset.defaultCharset());
                msg = "Could not create the image. SVG data store here: " + errsvg.getAbsolutePath();
            } catch (IOException ex) {
                // don't care
            }
        }
        throw new IOException(msg, e);
    } finally {
        if (null != svgfile) {
            FileUtils.deleteQuietly(svgfile);
        }
    }
}

From source file:com.oubeichen.gefexp.ShapesEditor.java

License:Open Source License

private void createRawOutput(ByteArrayOutputStream out) throws IOException {
    /*StringBuffer sb = new StringBuffer();
    Iterator it = getModel().getChildren()
    .iterator(), conit;/*  ww  w . ja va 2 s. com*/
    HashSet<Connection> hs = new HashSet<Connection>();
    sb.append("Shapes:\n"
    + getModel().getChildren()
          .size() + "\n");// shape
    while (it.hasNext()) {
       Shape sp = (Shape) it.next();
       sb.append(sp.toString() + "\n");
       sb.append("height:\n"
       + sp.getSize().height
       + "\nwidth:\n"
       + sp.getSize().width + "\n");
       sb.append("location:\n"
       + sp.getLocation().x + " "
       + sp.getLocation().y + "\n");
       conit = sp.getSourceConnections()
       .iterator();
       while (conit.hasNext()) {
    hs.add((Connection) conit.next());
       }
       conit = sp.getTargetConnections()
       .iterator();
       while (conit.hasNext()) {
    hs.add((Connection) conit.next());
       }
       sb.append("\n");// ?
    }
            
    sb.append("Connections:\n" + hs.size()
    + "\n");
    it = hs.iterator();
    while (it.hasNext()) {
       Connection con = (Connection) it
       .next();
       sb.append(con.getSource()
       .toString() + "\n");
       sb.append(con.getTarget()
       .toString() + "\n");
       sb.append("\n");// ?
    }
    out.write(sb.toString().getBytes());*/

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("diagram");// 
    Element shaperoot = root.addElement("shapes");
    Iterator it = getModel().getChildren().iterator(), conit;
    HashSet<Connection> hs = new HashSet<Connection>();
    while (it.hasNext()) {//shape
        Shape sp = (Shape) it.next();
        Element shapeElm = shaperoot.addElement("shape");
        shapeElm.addElement("name").addText(sp.toString());
        shapeElm.addElement("height").addText(String.valueOf(sp.getSize().height));
        shapeElm.addElement("width").addText(String.valueOf(sp.getSize().width));
        shapeElm.addElement("locx").addText(String.valueOf(sp.getLocation().x));
        shapeElm.addElement("locy").addText(String.valueOf(sp.getLocation().y));
        conit = sp.getSourceConnections().iterator();
        while (conit.hasNext()) {
            hs.add((Connection) conit.next());
        }
        conit = sp.getTargetConnections().iterator();
        while (conit.hasNext()) {
            hs.add((Connection) conit.next());
        }
    }
    Element connroot = root.addElement("connections");
    it = hs.iterator();
    while (it.hasNext()) {
        Element connElm = connroot.addElement("connection");
        Connection con = (Connection) it.next();
        connElm.addElement("source").addText(con.getSource().toString());
        connElm.addElement("target").addText(con.getTarget().toString());
    }
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8"); // XML?        
    XMLWriter writer;
    try {
        writer = new XMLWriter(out, format);
        writer.write(document);
        writer.close();
    } catch (IOException ex) {
        System.err.println("Cannot create output file!");
        ex.printStackTrace();
    }
    out.close();
}

From source file:com.pactera.edg.am.metamanager.extractor.util.Dom4jWriter.java

License:Open Source License

/**
 * XML/*ww w . jav a  2 s. c om*/
 * 
 * @param document
 * @param file
 */
public static void writeDocument(Document document, File file) {
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        writer.write(document);
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.partycommittee.service.PcLicenseService.java

public PcLicenseVo setLicenseInfo(String enstr, String tips) {
    if (enstr == null || enstr.equals(""))
        return null;
    if (tips == null || tips.equals(""))
        return null;
    PcLicenseVo licensevo = new PcLicenseVo();
    Des des = new Des();
    try {// w ww.  j a  v a2 s.c o  m

        String xml = des.DecryPwdStr(enstr, "hrpweb30");// String 
        System.out.println("xml ==============" + xml);
        if (xml == "" || xml.equals("")) {
            return null;
        }

        if (xml.indexOf("locknodw") <= 0) {
            return null;
        }

        if (xml.indexOf("locknozb") <= 0) {
            return null;
        }

        if (xml.indexOf("root") <= 0) {
            xml = "<root>" + xml + "</root>";
        }
        System.out.println("xml +++++++++++++++++" + xml);
        licensevo = setLicenseVo(xml, tips);

        SAXReader saxReader = new SAXReader();
        Document document = null;
        File file = new File(
                PcLicenseService.class.getClassLoader().getResource("/").getPath() + "license.xml");

        document = saxReader.read(file);
        Element root = document.getRootElement();

        Element license_element = root.element("license");

        license_element.setText(enstr);

        Element tips_element = root.element("tips");

        tips_element.setText(tips);

        String path = PcLicenseService.class.getClassLoader().getResource("/").getPath();
        OutputFormat format = OutputFormat.createPrettyPrint();
        // ??  
        format.setEncoding("UTF8");
        FileOutputStream output = new FileOutputStream(new File(path + "license.xml"));
        XMLWriter writer = new XMLWriter(output, format);
        writer.write(document);
        writer.flush();
        writer.close();

    } catch (Exception e) {
        //e.printStackTrace();
        return null;
    }

    return licensevo;
}

From source file:com.petpet.c3po.analysis.ProfileGenerator.java

License:Apache License

/**
 * Writes the given document to the given path.
 *
 * @param doc/*from  www . j a  va 2s  .com*/
 *          the document to write.
 * @param path
 *          the path to write to.
 */
public void write(final Document doc, final String path) {
    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final File file = new File(path);

        LOG.info("Will create profile in {}", file.getAbsolutePath());

        if (file.getParentFile() != null && !file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        file.createNewFile();

        final XMLWriter writer = new XMLWriter(new FileWriter(path), format);
        writer.write(doc);
        writer.close();

    } catch (final IOException e) {
        e.printStackTrace();
    }
}

From source file:com.poka.util.XmlSax.java

public boolean writeToXml(Document doc, String file) {
    try {//from w w w .j ava  2s .c  o  m
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encodingType);
        XMLWriter writer = new XMLWriter(new FileWriter(file), format);
        writer.write(doc);
        writer.flush();
        writer.close();

    } catch (IOException ex) {
        Logger.getLogger(XmlSax.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:com.poka.util.XmlSax.java

public int updateOrAddMachineInfo(MachinesCfg cfg) {
    Document doc = load(bankFile, false);
    Element rootElm = doc.getRootElement();
    Element root1Elm = rootElm.element("machines");
    if (root1Elm == null) {
        root1Elm = rootElm.addElement("machines");
    }/*ww  w.j a va2s . c o  m*/
    List nodes = root1Elm.elements("machine");
    boolean flag = false;
    for (Iterator it = nodes.iterator(); it.hasNext();) {
        Element elm = (Element) it.next();
        if (elm.attributeValue("ip").trim().equals(cfg.getIp().trim())
                && elm.attributeValue("type").trim().equals("" + cfg.getType())) {
            elm.setAttributeValue("machineType", cfg.getMachineType().trim());
            elm.setAttributeValue("machineNum", "" + cfg.getMachineNum());
            elm.setAttributeValue("user1", cfg.getUser1().trim());
            elm.setAttributeValue("user2", cfg.getUser2().trim());
            elm.setAttributeValue("type", "" + cfg.getType());
            flag = true;
            break;
        }
    }
    if (!flag) {
        Element tem = root1Elm.addElement("machine");
        tem.addAttribute("machineType", cfg.getMachineType().trim());
        tem.setAttributeValue("machineNum", "" + cfg.getMachineNum());
        tem.addAttribute("ip", cfg.getIp().trim());
        tem.addAttribute("user1", cfg.getUser1().trim());
        tem.addAttribute("user2", cfg.getUser2().trim());
        tem.addAttribute("type", "" + cfg.getType());
    }
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        // format.setEncoding("UTF-8");
        format.setEncoding(encodingType);
        XMLWriter writer = new XMLWriter(new FileWriter(bankFile), format);
        writer.write(doc);
        writer.flush();
        writer.close();
        if (flag) {//
            return 0;
        } else {//
            return 1;
        }
        //  return true;
    } catch (IOException ex) {
        Logger.getLogger(XmlSax.class.getName()).log(Level.SEVERE, null, ex);
    }
    return -1;
}

From source file:com.processpuzzle.application.domain.ApplicationRepository.java

License:Open Source License

private void writeXmlDocument() throws IOException {
    OutputFormat outputFormat = OutputFormat.createPrettyPrint();
    outputFormat.setEncoding(xmlDocument.getXMLEncoding());
    OutputStream output = new FileOutputStream(xmlResource.getFile());
    XMLWriter writer = new XMLWriter(output, outputFormat);

    writer.write(xmlDocument);/*w w w  .  ja va 2 s. c om*/
    writer.close();
}