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(OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

From source file:com.globalsight.everest.workflow.WorkflowNodeParameter.java

License:Apache License

/**
  * Restores the <code>Element</code> to the original string.
  * // ww  w  .j  a va 2 s  .  co  m
  * @param element
  *            The Element.
  * @return The original string.
  */
public String restore(Element element) {
    StringWriter s = new StringWriter();
    XMLWriter reader = new XMLWriter(s);
    try {
        reader.write(element);
    } catch (IOException e) {
        c_category.error("Error occured when write the element, the element is " + element.toString());
        c_category.error("The stack of the error when write the element is ", e);
    }
    return s.toString().replaceAll(XML_ROOT_PRE, StringUtil.EMPTY_STRING).replaceAll(XML_ROOT_SUF,
            StringUtil.EMPTY_STRING);
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase02PreProcess.java

License:Apache License

/**
 * Convert csv/txt file to xml file//w  w w . j ava 2  s  . c  o  m
 * 
 * @param format
 * @param originFile
 * @return
 */
private String convertToXML(String format, File originFile) {
    String fileName = originFile.getName();
    // Save the converted file to temp directory
    String xmlFilePath = jobInfo.getTempFile() + File.separator
            + fileName.substring(0, fileName.lastIndexOf(".")) + ".xml";
    File xmlFile = new File(xmlFilePath);
    FileReader fr = null;
    FileInputStream fis = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    XMLWriter output = null;
    try {
        String encoding = FileUtil.guessEncoding(originFile);

        Document document = DocumentHelper.createDocument();
        Element aElement = document.addElement("root");
        aElement.addAttribute("BomInfo", encoding == null ? "" : encoding);

        if (encoding == null) {
            fr = new FileReader(originFile);
            br = new BufferedReader(fr);
        } else {
            fis = new FileInputStream(originFile);
            isr = new InputStreamReader(fis, encoding);
            br = new BufferedReader(isr);
        }

        String str;
        if ("csv".equals(format)) {
            while ((str = br.readLine()) != null) {
                String[] values = str.split("\",\"");
                values[0] = values[0].substring(1);
                values[10] = values[10].substring(0, values[10].length() - 1);
                writeRow(aElement, values);
            }
        } else {
            while ((str = br.readLine()) != null) {
                str = str + "*";
                String[] values = str.split("\\|");
                values[10] = values[10].substring(0, values[10].lastIndexOf("*"));
                writeRow(aElement, values);
            }
        }

        output = new XMLWriter(new FileOutputStream(xmlFile));
        output.write(document);
    } catch (Exception e) {
        String message = "Failed to convert to XML, File Name: " + originFile.getName();
        LogUtil.fail(message, e);
        return null;
    } finally {
        try {
            if (output != null) {
                output.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (fr != null) {
                fr.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return xmlFile.getPath();
}

From source file:com.gote.pojo.Tournament.java

License:Apache License

/**
 * Transform Tournament in a formatted XML
 * //from w  w w .j a  va2 s .  c o m
 * @return XML to write as a String
 */
public String toXML() {
    // Create document
    Document doc = DocumentHelper.createDocument();

    // Create tournament element
    Element root = doc.addElement(TournamentGOTEUtil.TAG_TOURNAMENT);
    // Add attributes
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_NAME, getTitle());
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_SERVER, getServerType());
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_DATESTART, getStartDate().toString());
    root.addAttribute(TournamentGOTEUtil.ATT_TOURNAMENT_DATEEND, getEndDate().toString());

    // Add rules
    getTournamentRules().toXML(root);

    // Add players
    Element players = root.addElement(TournamentGOTEUtil.TAG_PLAYERS);
    for (Player player : getParticipantsList()) {
        player.toXML(players);
    }
    // Add rounds
    Element rounds = root.addElement(TournamentGOTEUtil.TAG_ROUNDS);
    for (Round round : getRounds()) {
        round.toXML(rounds);
    }

    StringWriter out = new StringWriter(1024);
    XMLWriter writer;
    try {
        writer = new XMLWriter(OutputFormat.createPrettyPrint());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
    writer.setWriter(out);
    try {
        writer.write(doc);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Return the friendly XML
    return out.toString();
}

From source file:com.hazzard.gui.PiNet.java

public void sendCommand(String command, String data) throws Exception {
    Document document;/*www  . j a  v  a2  s. c o m*/
    document = DocumentHelper.createDocument();
    Element root = document.addElement("commands");
    Element commandElem = root.addElement("command");
    commandElem.setText(command);

    commandElem.addAttribute("data", data);

    final Writer writer = new StringWriter();
    new XMLWriter(writer).write(root);
    String text = writer.toString().trim();

    DatagramPacket pack = new DatagramPacket(text.getBytes(), text.length(), InetAddress.getByName(group),
            port);
    sock_send.send(pack);
}

From source file:com.headstrong.fusion.services.message.processor.fixml.impl.FixmlFormatterServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public void process(MessageExchange exchange, ServiceConfig config) throws FusionException {
    ErrorHandler errorHandler = config.getErrorHandler();
    Object message = exchange.getIn().getBody();
    if (message == null) {
        // Ignoring the empty message
        logger.error("Empty message payload for process " + config.getProcessId() + " service "
                + config.getServiceId());
        return;//w ww.  j  a  v a  2s  .com
    }
    logger.debug("Message Received by the Fixml Formatter : " + message);
    Object fixmlMessage = null;

    // It is assumed here that if a splitter is connected before fixml
    // formatter, it would provide a list with single JavaBO, if the batch
    // size is configured to be 1
    if (message instanceof List) {
        logger.debug("Message is an instance of List ");
        if ((((List) message).size() != 0)) {
            Object javabo = (Object) ((List) message).get(0);
            if (javabo instanceof JavaBusinessObject) {
                logger.debug("Message in the list is an instance of JavaBusinessObject");
                fixmlMessage = ((JavaBusinessObject) javabo).getObject();
            }

        } else {
            // throw an error as invalid message is passed to this component

            // Bugchase 234 ErrorMonitoring # Exception is thrown if message
            // passed is an instance of list with zero size
            logger.error("Message passed is an instance of list with zero size" + " For Process '"
                    + config.getProcessId() + "', Service '" + config.getServiceId() + "', Message= "
                    + message);
            super.handleError(errorHandler, config.getProcessId(), config.getServiceId(), ERROR_TYPE_BUSINESS,
                    config.getServiceType(),
                    new FusionException("Message passed is an instance of list with zero size"), message, null);
            return;
        }
    }
    if (message instanceof JavaBusinessObject) {
        logger.debug("Message is an instance of JavaBusinessObject");
        fixmlMessage = ((JavaBusinessObject) message).getObject();
    }

    if (fixmlMessage == null) {
        // throw an error as invalid message is passed to this component
        // Bugchase 234 ErrorMonitoring # Invalid message passed to this component
        logger.error("Invalid message passed to this component" + " For Process '" + config.getProcessId()
                + "', Service '" + config.getServiceId() + "', Message= " + message);
        super.handleError(errorHandler, config.getProcessId(), config.getServiceId(), ERROR_TYPE_BUSINESS,
                config.getServiceType(), new FusionException("Invalid message passed to this component"),
                message, null);
        return;
    }

    // Marshal the fixml message to create the required XML string
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        // get the fixml marshaller.
        // get the namespace from the config.
        Object ns = config.getProperty(FIXML_SCHEMA);
        String namespace = ns == null ? DEFAULT_SCHEMA : ns.toString();
        FixmlContext context = FixmlContextFactory.getFixmlContext(FixmlNamespace.valueOf(namespace));

        Marshaller marshaller = context.getMarshaller();

        Boolean nsReqrd = Boolean.valueOf(config.getProperty(NAMESPACE_REQD, "TRUE").toString());

        synchronized (marshaller) {
            if (!nsReqrd) {
                NamespaceFilter outFilter = new NamespaceFilter(null, false);
                // Create a new org.dom4j.io.XMLWriter that will serve as
                // the ContentHandler for our filter.
                XMLWriter writer = null;
                try {
                    writer = new XMLWriter(os);
                } catch (UnsupportedEncodingException e) {
                    // Bugchase 234 ErrorMonitoring # Unsupported Encoding exception
                    logger.error("Error while creating xml writer while removing namespace" + " For Process '"
                            + config.getProcessId() + "', Service '" + config.getServiceId() + "', Message= "
                            + ((JavaBusinessObject) fixmlMessage).toXml(), e);
                    super.handleError(errorHandler, config.getProcessId(), config.getServiceId(),
                            ERROR_TYPE_SYSTEM, config.getServiceType(), e, message, null, true);
                }
                // Attach the writer to the filter
                outFilter.setContentHandler(writer);
                // marshal the fixml message
                marshaller.marshal(fixmlMessage, outFilter);
            } else {
                // marshal the fixml message
                marshaller.marshal(fixmlMessage, os);
            }
        }

    } catch (JAXBException e) {
        // Bugchase 234 ErrorMonitoring # Error marshalling the given
        // message into FIXML
        logger.error("Error marshalling the given message into FIXML.For Process " + config.getProcessId()
                + ", service id " + config.getServiceId() + "', Message= "
                + ((JavaBusinessObject) fixmlMessage).toXml(), e);
        super.handleError(errorHandler, config.getProcessId(), config.getServiceId(), ERROR_TYPE_BUSINESS,
                config.getServiceType(), e, message, "Error while Marshalling");
        return;

    }
    exchange.getIn().setBody(os.toString());
}

From source file:com.laudandjolynn.mytv.MyTvData.java

License:Apache License

public void writeData(String parent, String tag, String value) {
    logger.debug("write data to my tv data file: " + Constant.MY_TV_DATA_FILE_PATH);
    File file = new File(Constant.MY_TV_DATA_FILE_PATH);
    if (!file.exists()) {
        Document doc = DocumentHelper.createDocument();
        doc.addElement(Constant.APP_NAME);
        try {//from  w w w . j  a  v  a2 s  . c o  m
            FileUtils.writeWithNIO(doc.asXML().getBytes(), Constant.MY_TV_DATA_FILE_PATH);
        } catch (IOException e) {
            throw new MyTvException(
                    "error occur while write data to file. -- " + Constant.MY_TV_DATA_FILE_PATH);
        }
    }
    SAXReader reader = new SAXReader();
    try {
        Document xmlDoc = reader.read(file);
        Element parentElement = xmlDoc.getRootElement();
        if (parent != null) {
            List<?> nodes = xmlDoc.selectNodes("//" + parent);
            if (nodes != null && nodes.size() > 0) {
                parentElement = (Element) nodes.get(0);
            }
        }
        parentElement.addElement(tag).setText(value);
        try {
            XMLWriter writer = new XMLWriter(new FileWriter(file));
            writer.write(xmlDoc);
            writer.close();
        } catch (IOException e) {
            throw new MyTvException(
                    "error occur while write data to file. -- " + Constant.MY_TV_DATA_FILE_PATH);
        }
    } catch (DocumentException e) {
        String msg = "can't parse xml file. -- " + Constant.MY_TV_DATA_FILE_PATH;
        throw new MyTvException(msg);
    }
}

From source file:com.maomao.framework.utils.XmlUtils.java

License:Apache License

public String Dom2String(Document doc) {

    XMLWriter writer = null;/*from w w w . ja v a  2 s .co  m*/
    try {
        StringWriter sw = new StringWriter();
        writer = new XMLWriter(sw);
        writer.write(doc);
        return sw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != writer)
            try {
                writer.close();
            } catch (Exception ie) {
            }
    }
    return null;
}

From source file:com.maomao.framework.utils.XmlUtils.java

License:Apache License

public void saveXml2File(Document doc, File file) {
    XMLWriter writer = null;/*from w  w  w . j a v  a  2  s  . c  o m*/
    try {
        FileWriter fw = new FileWriter(file);
        writer = new XMLWriter(fw);
        writer.write(doc);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != writer)
            try {
                writer.close();
            } catch (Exception ie) {
            }
    }
}

From source file:com.mor.blogengine.xml.io.XmlDataSourceProvider.java

License:Open Source License

/**
 * writes in a file//from www.  j a  v  a  2s .c  o  m
 *
 * @param document DOM model to write in
 * @param pOutputFile output file
 * @throws java.io.IOException
 * @param pDocument
 */
boolean write(Document pDocument) throws MissingPropertyException, IncorrectPropertyValueException {
    boolean ret = false;
    try {
        OutputFormat format = new OutputFormat();
        format.setEncoding(getFileEncoding());
        XMLWriter writer;
        writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xml.getFile()),
                Charset.forName(getFileEncoding())));

        writer.write(pDocument);
        writer.close();
        ret = true;

    } catch (IOException ex) {
        trace("Error saving file..." + ex);

    }
    return ret;

}

From source file:com.npower.dm.hibernate.management.ModelManagementBeanImpl.java

License:Open Source License

/**
 * /*from ww w  .  ja  va2s  .c o m*/
 * <pre>
 * Export the TAC form database by Model.
 * &lt;pre&gt;
 * 
 * @param model
 * @return
 * @throws DMException
 * 
 */
public void exportModelTAC(Model model, String outFile) throws DMException {

    Document document = org.dom4j.DocumentHelper.createDocument();
    Element rootElement = document.addElement("Manufacturers");
    Element manElement = rootElement.addElement("Manufacturer");
    Element manNameElement = manElement.addElement("Name");
    manNameElement.setText(model.getManufacturer().getName());
    Element manexterIDElement = manElement.addElement("ExternalID");
    manexterIDElement.setText(model.getManufacturer().getExternalId());
    Element modelElement = manElement.addElement("Model");
    Element modelNameElement = modelElement.addElement("Name");
    modelNameElement.setText(model.getName());
    Element modelexterIDElement = modelElement.addElement("ExternalID");
    modelexterIDElement.setText(model.getManufacturerModelId());
    Element TACSElement = modelElement.addElement("TACS");

    Set<String> tacSet = model.getModelTAC();
    for (String tac : tacSet) {
        Element TACElement = TACSElement.addElement("TAC");
        TACElement.setText(tac);
    }

    try {
        XMLWriter writer = new XMLWriter(new FileWriter(new File(outFile)));
        writer.write(document);
        writer.close();
        this.formatXMLFile(outFile);
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

}