Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:com.bstek.dorado.idesupport.output.RuleSetOutputter.java

License:Open Source License

protected void outputProperty(XMLWriter xmlWriter, PropertyTemplate property, OutputContext context)
        throws Exception {
    Element element = DocumentHelper.createElement("Prop");
    setElementAttributes(element, property,
            "name,defaultValue,highlight,fixed,enumValues,editor,clientTypes,deprecated,reserve");
    if (!property.isVisible()) {
        element.addAttribute("visible", "false");
    }// www .  j  a  v a2s  . c o m

    if (StringUtils.isNotEmpty(property.getType())) {
        try {
            Class<?> type = ClassUtils.forName(property.getType());
            if (!String.class.equals(type) && !type.isEnum()) {
                element.addAttribute("type", type.getName());
            }
        } catch (ClassNotFoundException e) {
            // do nothing
        }
    }

    CompositeType compositeType = property.getCompositeType();
    if (compositeType != CompositeType.Unsupport) {
        element.addAttribute("compositeType", compositeType.toString());
    }

    ReferenceTemplate reference = property.getReference();
    if (reference != null) {
        String referenceText = reference.getRuleTemplate().getName();
        if (StringUtils.isNotEmpty(reference.getProperty())) {
            referenceText += ':' + reference.getProperty();
        }
        element.addAttribute("reference", referenceText);
    }

    if (compositeType == CompositeType.Fixed || compositeType == CompositeType.Open) {
        xmlWriter.writeOpen(element);
        for (PropertyTemplate subProperty : property.getProperties().values()) {
            outputProperty(xmlWriter, subProperty, context);
        }
        xmlWriter.writeClose(element);
    } else {
        xmlWriter.write(element);
    }
}

From source file:com.bstek.dorado.idesupport.output.RuleSetOutputter.java

License:Open Source License

protected void outputClientEvent(XMLWriter xmlWriter, ClientEvent clientEvent, OutputContext context)
        throws Exception {
    Element element = DocumentHelper.createElement("ClientEvent");
    setElementAttributes(element, clientEvent, "name,parameters,clientTypes,deprecated,reserve");
    xmlWriter.write(element);
}

From source file:com.bullx.demo.xml.XMLParser.java

License:Open Source License

public static void bookListToXML(List<Book> books) {
    Document document = DocumentHelper.createDocument();
    // XMLbooks// ww  w.ja  v  a  2 s. c  om
    Element booksElement = document.addElement("books");
    //  
    booksElement.addComment("This is a test for dom4j, liubida, 2012.8.11");

    for (Book book : books) {
        // 
        Element bookElement = booksElement.addElement("book");
        // : show
        bookElement.addAttribute("show", book.getShow() ? "yes" : "no");
        // title
        bookElement.addElement("title").setText(book.getTitle());
        // express
        bookElement.addElement("express").setText(book.getExpress());
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    StringWriter out = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(out, format);
    try {
        xmlWriter.write(document);
        xmlWriter.flush();
        String s = out.toString();
        System.out.println(s);
        Log.info("xml done!");
    } catch (Exception e) {
        Log.error("xml error!");
    } finally {
        try {
            if (null != xmlWriter) {
                xmlWriter.close();
            }
            if (null != out) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.bullx.utils.I2Util.java

License:Open Source License

public static String prettyXML(Document document) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    StringWriter out = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(out, format);
    try {/*from w  w w.  jav  a 2  s  . c  o m*/
        xmlWriter.write(document);
        xmlWriter.flush();
        return out.toString();
    } catch (Exception e) {
        Log.error(e.getMessage());
    } finally {
        try {
            if (null != xmlWriter) {
                xmlWriter.close();
            }
            if (null != out) {
                out.close();
            }
        } catch (IOException e) {
            Log.error(e.getMessage());
        }
    }
    return null;
}

From source file:com.cc.framework.util.SettingUtils.java

License:Open Source License

/**
 * /*from ww w. j  a v a2  s. com*/
 * 
 * @param setting
 *            
 */
public static void set(Setting setting) {
    try {
        File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile();
        Document document = new SAXReader().read(shopxxXmlFile);
        List<Element> elements = document.selectNodes("/shopxx/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(shopxxXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.chingo247.structureapi.plan.document.AbstractDocumentManager.java

protected void save(K key, final V document) {
    documentPool.execute(key, new Runnable() {

        @Override//from w  ww. jav a  2  s  . c om
        public void run() {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setExpandEmptyElements(true);
            XMLWriter writer = null;
            try {
                writer = new XMLWriter(new FileWriter(document.documentFile), format);
                writer.write(document.document);
            } catch (IOException ex) {
                Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException ex) {
                        Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    });
}

From source file:com.chingo247.structureapi.plan.document.AbstractDocumentManager.java

protected void save(K key, final DocumentPluginElement element) {
    documentPool.execute(key, new Runnable() {

        @Override//from  w w  w  .  java  2 s . com
        public void run() {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setExpandEmptyElements(true);
            XMLWriter writer = null;
            try {
                File d = element.root.documentFile;
                writer = new XMLWriter(new FileWriter(d), format);
                writer.write(element.pluginElement.getDocument());
            } catch (IOException ex) {
                Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException ex) {
                        Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    });
}

From source file:com.chingo247.structureapi.plan.document.PlanDocumentGenerator.java

License:Open Source License

public void generate(File targetFolder) {
    // Scan the folder called 'SchematicToPlan' for schematic files
    Iterator<File> it = FileUtils.iterateFiles(targetFolder, new String[] { "schematic" }, true);
    System.out.println("Files: " + targetFolder.listFiles().length);

    int count = 0;
    long start = System.currentTimeMillis();

    // Generate Plans
    while (it.hasNext()) {
        File schematic = it.next();

        Document d = DocumentHelper.createDocument();
        d.addElement(Elements.ROOT).addElement(Elements.SETTLERCRAFT).addElement(Elements.SCHEMATIC)
                .setText(schematic.getName());

        File plan = new File(schematic.getParent(), FilenameUtils.getBaseName(schematic.getName()) + ".xml");

        try {// ww  w.  j  a va  2  s  . c  om

            XMLWriter writer = new XMLWriter(new FileWriter(plan));
            writer.write(d);
            writer.close();

            StructurePlan sp = new StructurePlan();
            PlanDocument pd = new PlanDocument(structureAPI.getPlanDocumentManager(), plan);
            pd.putPluginElement("SettlerCraft", new PlanDocumentPluginElement("SettlerCraft", pd,
                    (Element) d.selectSingleNode("StructurePlan/SettlerCraft")));
            sp.load(pd);

            if (sp.getCategory().equals("Default")
                    && !schematic.getParentFile().getName().equals(targetFolder.getName())) {
                sp.setCategory(schematic.getParentFile().getName());
            }

            sp.save();

        } catch (DocumentException ex) {
            Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | StructureDataException ex) {
            Logger.getLogger(StructurePlanManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        count++;
    }
    if (count > 0) {
        StructureAPI.print("Generated " + count + " plans in " + (System.currentTimeMillis() - start) + "ms");
    }
}

From source file:com.chingo247.structureapi.plan.io.export.StructurePlanExporter.java

License:Open Source License

public void export(IStructurePlan plan, File destinationDirectory, String fileName, boolean prettyPrint)
        throws IOException, UnsupportedPlacementException {
    Preconditions.checkArgument(destinationDirectory.isDirectory());

    IPlacement placement = plan.getPlacement();
    if (!(placement instanceof IExportablePlacement)) {
        throw new UnsupportedPlacementException("Placement does not implement IWriteablePlacement");
    }//from www  .  j  a va  2  s.c  o m

    Document d = DocumentHelper.createDocument();

    Element root = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_ROOT_ELEMENT);
    d.add(root);

    Element nameElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_NAME_ELEMENT);
    nameElement.setText(plan.getName());
    root.add(nameElement);

    Element priceElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PRICE_ELEMENT);
    priceElement.setText(String.valueOf(plan.getPrice()));
    root.add(priceElement);

    Element categoryElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_CATEGORY_ELEMENT);
    categoryElement.setText(plan.getCategory() == null ? "None" : plan.getCategory());
    root.add(categoryElement);

    Element descriptionElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_DESCRIPTION_ELEMENT);
    descriptionElement.setText(plan.getDescription() == null ? "None" : plan.getDescription());
    root.add(descriptionElement);

    Element placementElement = PlacementAPI.getInstance().handle((IExportablePlacement) plan.getPlacement());
    root.add(placementElement);

    //        if (plan instanceof SubStructuresPlan) {
    //            SubStructuresPlan ssp = (SubStructuresPlan) plan;
    //            
    //            Element substructuresElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURES);
    //            root.add(substructuresElement);
    //            
    //            for(Placement p : ssp.getSubPlacements()) {
    //                try {
    //                    Element e = PlacementAPI.getInstance().handle(p);
    //                    e.setName(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE);
    //                    substructuresElement.add(e);
    //                } catch (PlacementException ex) {
    //                    System.err.println(ex.getMessage());
    //                }
    //            }
    //            
    //            int index = 0;
    //            for(StructurePlan p : ssp.getSubStructurePlans()) {
    //                File exportPlan = new File(destinationDirectory, p.getFile().getName() + "-" + index);
    //                
    //                try {
    //                    export(plan, destinationDirectory, exportPlan.getName(), prettyPrint);
    //                } catch (Exception e){
    //                    continue;
    //                }
    //                
    //                Element substructureElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_SUBSTRUCTURE);
    //                
    //                // TODO add position + direction
    //                
    //                Element typeElement = new BaseElement(PlacementXMLConstants.PLACEMENT_TYPE_ELEMENT);
    //                typeElement.setText(PlacementTypes.EMBEDDED);
    //                substructureElement.add(typeElement);
    //                
    //                Element pathElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_RELATIVE_PATH_ELEMENT);
    //                pathElement.setText(exportPlan.getName());
    //                substructureElement.add(pathElement);
    //                
    //                substructuresElement.add(substructureElement);
    //                
    //            }
    //            
    //        }

    OutputFormat format;
    if (prettyPrint) {
        format = OutputFormat.createPrettyPrint();
    } else {
        format = OutputFormat.createCompactFormat();
    }
    XMLWriter writer = new XMLWriter(new FileWriter(new File(destinationDirectory, fileName)), format);
    writer.write(d);
    writer.close();

}

From source file:com.chingo247.structureapi.plan.PlanGenerator.java

License:Open Source License

private static void generatePlanFromSchematic(File file, File rootDirectory) throws IOException {
    String name = FilenameUtils.getBaseName(file.getName());
    File directory = file.getParentFile();

    Document d = DocumentHelper.createDocument();
    Element root = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_ROOT_ELEMENT);
    d.add(root);/* w ww. j a v a  2s .  c o m*/

    Element nameElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_NAME_ELEMENT);
    nameElement.setText(name);
    root.add(nameElement);

    Element priceElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PRICE_ELEMENT);
    priceElement.setText("0");
    root.add(priceElement);

    Element description = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_DESCRIPTION_ELEMENT);
    description.setText("None");
    root.add(description);

    Element categoryElement = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_CATEGORY_ELEMENT);
    String category = rootDirectory.getName().equals(directory.getName()) ? "Default" : directory.getName();
    categoryElement.setText(category);
    root.add(categoryElement);

    Element placementElment = new BaseElement(StructurePlanXMLConstants.STRUCTURE_PLAN_PLACEMENT);

    Element typeElement = new BaseElement(PlacementXMLConstants.TYPE_ELEMENT);
    typeElement.setText(PlacementTypes.SCHEMATIC);

    Element schematicElement = new BaseElement(PlacementXMLConstants.SCHEMATIC_ELEMENT);
    schematicElement.setText(file.getName());

    placementElment.add(typeElement);
    placementElment.add(schematicElement);

    root.add(placementElment);

    File planFile = new File(directory, name + ".xml");
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(planFile), format);
    writer.write(d);
    writer.close();
}