Example usage for org.dom4j.io XMLWriter XMLWriter

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

Introduction

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

Prototype

public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

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

License:Open Source License

/**
 * /*  ww  w. j  a  v  a 2  s.  co  m*/
 * 
 * @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  .  j  a v  a2 s .  co  m
        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 www .ja v a2  s  .c om*/
        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.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   ww w .  j a v a 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 . jav a2 s.  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();
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

/**
 * Writes the document to the location specified by the URL,
 * using the default XML writer!/* w  w w  . j a va2  s . c  om*/
 *
 * @param document the dom4j document.
 * @param url the URL of the document.
 */
public static synchronized void write(XDocument document, URL url) throws IOException {
    if (DEBUG)
        System.out.println("XMLUtilities.write( " + document + ", " + url + ")");

    File documentFile = null;

    documentFile = new File(url.getFile());

    if (documentFile != null) {
        FileOutputStream out = new FileOutputStream(documentFile);

        //      XMLWriter writer = new XMLWriter( out, format);
        XMLWriter writer = new XMLWriter(out,
                new OutputFormat(TextPreferences.getTabString(), true, document.getEncoding()));
        writer.write(document);
        writer.flush();

        out.flush();
        out.close();

    } else {
        throw new IOException(url.toExternalForm() + " (The system cannot find the path specified)");
    }
}

From source file:com.controlj.addon.weather.util.Logging.java

License:Open Source License

private static String toXMLString(String reason, Document document) throws IOException {
    StringWriter stringWriter = new StringWriter();
    PrintWriter pw = new PrintWriter(stringWriter);
    pw.println(reason);/*from w w  w .ja va 2  s  . c  om*/
    pw.flush();

    XMLWriter writer = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
    writer.write(document);
    return stringWriter.toString();
}

From source file:com.davis.bluefolder.BlueUtils.java

public String formatXML(String input) {
    try {/*from w w  w  .  j a  va  2  s.  c om*/
        org.dom4j.Document doc = DocumentHelper.parseText(input);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        format.setIndentSize(3);
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);

        return sw.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return input;
    }
}

From source file:com.dockingsoftware.dockingpreference.PreferenceProcessor.java

License:Apache License

/**
 * Store user preference information to a specified file.
 * /* w w w .  j av a  2  s. co m*/
 * @param obj 
 * @param fullPath Specified the full path of the configuration file.
 */
public void store(Object obj, String fullPath) {
    try {
        FileWriter out;
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement(getName(obj.getClass()));
        root.addAttribute(GlobalConstant.CLASS, obj.getClass().getName());

        List<Field> pFields = getPreferenceFieldList(obj.getClass());
        for (int i = 0; i < pFields.size(); i++) {
            store(obj, pFields.get(i), root);
        }

        OutputFormat format = new OutputFormat("  ", true);
        out = new FileWriter(new File(fullPath));
        XMLWriter w = new XMLWriter(out, format);
        w.write(document);
        w.close();
        out.close();

    } catch (IOException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.doculibre.constellio.izpack.PersistenceXMLUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void run(AbstractUIProcessHandler handler, String[] args) {
    if (args.length != 5) {
        System.out.println("persistence_mysqlPath defaultPersistencePath server login password");
        return;/*from  w w w.j  av a 2 s  .c o m*/
    }

    String persistence_mysqlPath = args[0];
    String defaultPersistencePath = args[1];
    String server = args[2];
    String login = args[3];
    String password = args[4];

    Document xmlDocument;
    try {
        xmlDocument = new SAXReader().read(persistence_mysqlPath);
        Element root = xmlDocument.getRootElement();
        Iterator<Element> it = root.elementIterator("persistence-unit");
        if (!it.hasNext()) {
            System.out.println("Corrupt persistence file :" + persistence_mysqlPath);
            return;
        }
        it = it.next().elementIterator("properties");
        if (!it.hasNext()) {
            System.out.println("Corrupt persistence file :" + persistence_mysqlPath);
            return;
        }
        Element properties = it.next();
        for (it = properties.elementIterator("property"); it.hasNext();) {
            Element property = it.next();
            String id = property.attributeValue("name");
            if (id.equals(SERVER_ELEMENT_ID)) {
                Attribute att = property.attribute("value");
                att.setText(BEFORE_SERVER_NAME + server + AFTER_SERVER_NAME);
            } else {
                if (id.equals(LOGIN_ELEMENT_ID)) {
                    Attribute att = property.attribute("value");
                    att.setText(login);
                } else {
                    if (id.equals(PASSWORD_ELEMENT_ID)) {
                        Attribute att = property.attribute("value");
                        att.setText(password);
                    }
                }
            }

        }

        OutputFormat format = OutputFormat.createPrettyPrint();

        File xmlFile = new File(persistence_mysqlPath);
        XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format);

        writer2.write(xmlDocument);
        writer2.close();
        // copier au fichier de persistence par dfaut:
        xmlFile = new File(defaultPersistencePath);
        writer2 = new XMLWriter(new FileOutputStream(xmlFile), format);

        writer2.write(xmlDocument);
        writer2.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}