Example usage for org.jdom2.output XMLOutputter XMLOutputter

List of usage examples for org.jdom2.output XMLOutputter XMLOutputter

Introduction

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

Prototype

public XMLOutputter() 

Source Link

Document

This will create an XMLOutputter with a default Format and XMLOutputProcessor .

Usage

From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java

License:Apache License

/**
 * get the inner XML inside an element as a string. This is done by
 * converting the XML to its string representation, then extracting the
 * subset between beginning and end tags.
 * @param element/*  w  w  w  . j  av  a 2  s.  c o m*/
 * @return textual body of the element, or null for no inner body
 */
public String getInnerXMLString(Element element) {
    String elementString = new XMLOutputter().outputString(element);
    int start, end;
    start = elementString.indexOf(">") + 1;
    end = elementString.lastIndexOf("</");
    if (end > 0) {
        StringBuilder result = new StringBuilder();
        for (String part : elementString.substring(start, end).split("\r|\n")) {
            result.append(part.trim());
        }
        return result.toString();
    } else
        return "";
}

From source file:com.htm.utils.Utilities.java

License:Open Source License

public static String getStringFromXMLDoc(Document doc) {
    XMLOutputter out = new XMLOutputter();
    return out.outputString(doc);
}

From source file:com.iana.dver.pdf.scrapper.DVERScrapperTask.java

/**
 * Step - 2 : Generate XML from Text stripper
 * /*  www .  ja  va2s .  c  o m*/
 * @param tempTextFile
 * @throws IOException
 */
private void generateDverXML(String fileName, PDFTextStripperByArea stripper) throws IOException {

    File outputFile = new File(xmlDir + fileName + ".xml");
    OutputStream fos = new FileOutputStream(outputFile);

    Element dver = new Element("DVER");
    Document doc = new Document(dver);

    // Generate Address Node
    String addressDetail = stripper.getTextForRegion("ADDRESS");
    String[] addressArr = addressDetail.split("\\n");
    Element addressNode = new Element("ADDRESS");
    addressNode.addContent(new Element("ADDRESS_1").setText(addressArr[0] + "\\n" + addressArr[1]));
    addressNode.addContent(new Element("ADDRESS_2").setText(addressArr[2] + "\\n" + addressArr[3]));
    if (addressArr.length > 4) {
        String[] tempContact = addressArr[4].split(" ");
        addressNode.addContent(new Element("PHONE").setText(tempContact[1]));
        addressNode.addContent(new Element("FAX").setText(tempContact[3]));
    } else {
        addressNode.addContent(new Element("PHONE").setText(""));
        addressNode.addContent(new Element("FAX").setText(""));
    }
    doc.getRootElement().addContent(addressNode);

    // Report Information Node
    String reportDetail = stripper.getTextForRegion("REPORT_INFO");
    String[] reportDetailArr = reportDetail.split("\\n");
    Element reportInfoNode = new Element("REPORT_INFO");

    for (int i = 0; i < reportDetailArr.length; i++) {
        if (i == 0) {
            String[] reportInfo = reportDetailArr[i].split(":");
            reportInfoNode.addContent(new Element("REPORT_NUMBER").setText(reportInfo[1]));
        } else if (i == 1) {
            String[] inspDetail = reportDetailArr[i].split(":");
            inspDetail[1] = inspDetail[1].replaceAll("Certification Date", "");
            reportInfoNode.addContent(new Element("INSPECTION_DATE").setText(inspDetail[1]));
            reportInfoNode.addContent(new Element("CERTIFICATION_DATE").setText(inspDetail[2]));
        } else if (i == 2) {
            String timings = reportDetailArr[i];
            timings = timings.replaceAll("Time Started:", "");
            timings = timings.replaceAll("Time Ended:", "");
            String[] timeDetail = timings.split(" ");
            reportInfoNode.addContent(new Element("START_TIME").setText(timeDetail[0]));
            reportInfoNode.addContent(new Element("END_TIME").setText(timeDetail[1]));
        } else if (i == 3) {
            String[] reportInfo = reportDetailArr[i].split(":");
            reportInfoNode.addContent(new Element("INSPECTION_LEVEL").setText(reportInfo[1]));
        } else if (i == 4) {
            String[] reportInfo = reportDetailArr[i].split(":");
            reportInfoNode.addContent(new Element("INSPECTION_TYPE").setText(reportInfo[1]));
        }
    }
    doc.getRootElement().addContent(reportInfoNode);

    // INTERMODAL EQUIPMENT PROVIDER INFORMATION
    String iepDetail = stripper.getTextForRegion("IEP_INFO");
    String[] iepDetailArr = iepDetail.split("\\n");
    Element iepInfoNode = new Element("IEP_INFO");

    for (int j = 0; j < iepDetailArr.length; j++) {
        if (j == 1) {
            iepInfoNode.addContent(new Element("IEP_NAME").setText(iepDetailArr[j]));
        } else if (j == 2) {
            String[] tempIepInfo = iepDetailArr[j].split(" ");
            iepInfoNode.addContent(new Element("US_DOT").setText(tempIepInfo[3]));
            iepInfoNode.addContent(new Element("DATA_SOURCE").setText(tempIepInfo[6]));
        }
    }
    doc.getRootElement().addContent(iepInfoNode);

    // MOTOR CARRIER INFORMATION
    String mcDetail = stripper.getTextForRegion("MC_INFO");
    String[] mcDetailArr = mcDetail.split("\\n");
    Element mcDetailNode = new Element("MC_INFO");

    for (int k = 0; k < mcDetailArr.length; k++) {
        if (k == 1) {
            String mcCompAndDriver = mcDetailArr[k].replaceAll("Driver:", "");
            mcDetailNode.addContent(new Element("MC_NAME").setText(mcCompAndDriver.split(" ")[0]));
            mcDetailNode.addContent(new Element("DRIVER").setText(mcCompAndDriver.split(" ")[1]));
        } else if (k == 2) {
            mcDetailNode.addContent(new Element("MC_ADD_1").setText(mcDetailArr[k]));
        } else if (k == 3) {
            mcDetailNode.addContent(new Element("MC_ADD_2").setText(mcDetailArr[k]));
        } else if (k == 4) {
            String tempStr = mcDetailArr[k];
            tempStr = tempStr.replaceAll("USDOT #:", "");
            tempStr = tempStr.replaceAll("Phone #:", "");
            String[] otherDetails = tempStr.trim().split(" ");
            mcDetailNode
                    .addContent(new Element("US_DOT").setText(otherDetails[0] != null ? otherDetails[0] : ""));
            mcDetailNode
                    .addContent(new Element("PHONE").setText(otherDetails[2] != null ? otherDetails[2] : ""));
        } else if (k == 5) {
            String tempStr = mcDetailArr[k];
            tempStr = tempStr.replaceAll("MC/MX #:", "");
            tempStr = tempStr.replaceAll("Fax #:", "");
            String[] otherDetails = tempStr.trim().split(" ");
            mcDetailNode
                    .addContent(new Element("MC_MX").setText(otherDetails[0] != null ? otherDetails[0] : ""));
            mcDetailNode.addContent(new Element("FAX")
                    .setText(otherDetails.length > 1 && otherDetails[1] != null ? otherDetails[2] : ""));
        } else if (k == 6) {
            mcDetailArr[k] = mcDetailArr[k].replaceAll("State #:", "");
            mcDetailNode.addContent(new Element("STATE").setText(mcDetailArr[k] != null ? mcDetailArr[k] : ""));
        } else if (k == 7) {
            mcDetailArr[k] = mcDetailArr[k].replaceAll("Origin:", "");
            mcDetailArr[k] = mcDetailArr[k].replaceAll("Destination:", "");
            mcDetailNode.addContent(
                    new Element("ORIGIN_DESTINATION").setText(mcDetailArr[k] != null ? mcDetailArr[k] : ""));
        }
    }
    doc.getRootElement().addContent(mcDetailNode);

    // VEHICLE IDENTIFICATION
    String vehicleIdentification = stripper.getTextForRegion("VEHICLE_ID");
    String[] vehicleIdArr = vehicleIdentification.split("\\n");
    Element vehicleIdNode = new Element("VEHICLE_IDENTIFICATION");

    for (int l = 0; l < vehicleIdArr.length; l++) {
        if (l == 2) {
            String[] vehicleDetails = vehicleIdArr[l].trim().split(" ");
            for (int m = 0; m < vehicleDetails.length; m++) {
                if (m == 0) {
                    vehicleIdNode.addContent(
                            new Element("UNIT").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 1) {
                    vehicleIdNode.addContent(
                            new Element("TYPE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 2) {
                    vehicleIdNode.addContent(
                            new Element("MAKE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 3) {
                    vehicleIdNode.addContent(
                            new Element("YEAR").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 4) {
                    vehicleIdNode.addContent(
                            new Element("STATE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 5) {
                    vehicleIdNode.addContent(
                            new Element("LICENSE").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 6) {
                    vehicleIdNode.addContent(new Element("EQUIPMENT_ID")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 7) {
                    vehicleIdNode.addContent(new Element("UNIT_VIN")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 8) {
                    vehicleIdNode.addContent(
                            new Element("GVWR").setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 9) {
                    vehicleIdNode.addContent(new Element("ISSUED_DECAL")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                } else if (m == 10) {
                    vehicleIdNode.addContent(new Element("OOS_STKR")
                            .setText(vehicleDetails[m] != null ? vehicleDetails[m] : ""));
                }
            }

        }
    }
    doc.getRootElement().addContent(vehicleIdNode);

    // Brake Adjustments
    String breakAdjustment = stripper.getTextForRegion("BREAK_ADJ");
    String[] breakAdjustmentArr = breakAdjustment.split("-");
    Element breakAdjustmentNode = new Element("BREAK_ADJUSTMENT");

    for (int n = 0; n < breakAdjustmentArr.length; n++) {
        if (n == 1) {
            breakAdjustmentNode.setText(breakAdjustmentArr[n] != null ? breakAdjustmentArr[n] : "");
        }
    }
    doc.getRootElement().addContent(breakAdjustmentNode);

    // Other Chassis Violation details
    String otherViolationDetail = stripper.getTextForRegion("OTHER_CHASSIS_VIOLATION");
    String[] otherViolationDetailArr = otherViolationDetail.split("\\n");
    Element otherViolationElement = new Element("OTHER_CHASSIS_VIOLATION");

    for (int ocnt = 0; ocnt < (otherViolationDetailArr.length - 1); ocnt++) {
        if (ocnt > 1) {
            String[] tempOtrDetail = otherViolationDetailArr[ocnt].split(" ");
            Element violations = new Element("OTHER_VIOLATIONS");
            for (int temp = 0; temp < tempOtrDetail.length; temp++) {
                if (temp == 0) {
                    violations.addContent(new Element("VIO_CODE").setText(tempOtrDetail[temp]));
                } else if (temp == 1) {
                    violations.addContent(new Element("SECTION").setText(tempOtrDetail[temp]));
                } else if (temp == 2) {
                    violations.addContent(new Element("UNIT").setText(tempOtrDetail[temp]));
                } else if (temp == 3) {
                    violations.addContent(new Element("OOS").setText(tempOtrDetail[temp]));
                } else if (temp == 4) {
                    violations.addContent(new Element("NUMBER").setText(tempOtrDetail[temp]));
                } else if (temp == 5) {
                    violations.addContent(new Element("VERIFY").setText(tempOtrDetail[temp]));
                } else if (temp == 6) {
                    violations.addContent(new Element("CRASH").setText(tempOtrDetail[temp]));
                } else if (temp == 7) {
                    violations.addContent(new Element("VIO_DESC").setText(tempOtrDetail[temp]));
                }
            }
            otherViolationElement.addContent(violations);
        }
    }
    doc.getRootElement().addContent(otherViolationElement);

    String driverNotes = stripper.getTextForRegion("DRIVER_NOTES");
    Element driverNotesNode = new Element("NOTES_TO_DRIVER");
    driverNotesNode.setText(driverNotes);
    doc.getRootElement().addContent(driverNotesNode);

    String iepNotes = stripper.getTextForRegion("IEP_NOTES");
    Element iepNotesNode = new Element("NOTES_TO_IEP");
    iepNotesNode.setText(iepNotes);
    doc.getRootElement().addContent(iepNotesNode);

    String creationNotes = stripper.getTextForRegion("CREATION_NOTES");
    Element creationNotesNode = new Element("CREATED_BY");
    creationNotesNode.setText(creationNotes.split("\\n")[1]);
    doc.getRootElement().addContent(creationNotesNode);

    XMLOutputter xmlOutput = new XMLOutputter();
    // display nice nice
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(doc, fos);
    fos.flush();
    fos.close();

}

From source file:com.init.octo.query.Query.java

License:Open Source License

/**
 * This method initialises the object with a parameters object. This will
 * replace any parameters in the query text with values from the parameters
 * object./*  w ww .j  a v a  2s.co m*/
 * 
 * @param parameters
 *            - an XML structure containing current definitions of
 *            parameters
 * @throws SQLException
 */

public void expandParameters(Document parameters) throws SQLException {
    XMLOutputter xout = new XMLOutputter(); // Format.getPrettyFormat());
    log.debug("parameters XML: " + xout.outputString(parameters));

    expandedQuery = StringUtils.expand(queryText.toString(), parameters.getRootElement());

    log.debug("EXPANDED QUERY [" + expandedQuery + "]");

    /** Close everything down... * */

    // firstFetch = true;
    if (rs != null) {
        rs.close();
        rs = null;
    }
    if (statement != null) {
        statement.close();
        statement = null;
    }

}

From source file:com.jamfsoftware.jss.healthcheck.controller.ConfigurationController.java

License:Open Source License

/**
 * This method updates XML values from the Health Check GUI.
 * Not all items are supported. If it can't find the XML file,
 * it will print the error message. Could cause errors if the structure
 * of the XML file has been modified./*from  ww  w . ja  v a 2 s.c om*/
 */
public void updateXMLValue(String item, String value) {
    if (item.equals("jss_url")) {
        this.root.getChildren().get(0).setText(value);
    } else if (item.equals("jss_username")) {
        this.root.getChildren().get(1).setText(value);
    } else if (item.equals("jss_password")) {
        this.root.getChildren().get(2).setText(value);
    } else if (item.equals("smart_groups")) {
        this.root.getChildren().get(5).getChildren().get(1).setText(value);
    } else if (item.equals("extension_attributes")) {
        this.root.getChildren().get(5).getChildren().get(2).getChildren().get(0).setText(value);
        this.root.getChildren().get(5).getChildren().get(2).getChildren().get(1).setText(value);
    }

    try {
        XMLOutputter o = new XMLOutputter();
        o.setFormat(Format.getPrettyFormat());
        o.output(this.root, new FileWriter(getConfigurationPath()));
    } catch (Exception e) {
        LOGGER.error("Unable to update XML file.", e);
    }

}

From source file:com.js.quickestquail.server.ViewAllMoviesHandler.java

private void buildXML() {
    Element rootElement = new Element("movies");

    for (Entry<File, String> en : DriveManager.get().getSelected().entrySet()) {
        Movie mov = CachedMovieProvider.get().getMovieByID(en.getValue());

        Element movieElement = new Element("movie");

        movieElement.addContent(makeElement("imdbid", mov.getImdbID()));
        movieElement.addContent(makeElement("imdbrating", mov.getImdbRating() + ""));
        movieElement.addContent(makeElement("imdbvotes", mov.getImdbVotes() + ""));

        movieElement.addContent(makeElement("title", mov.getTitle()));
        movieElement.addContent(makeElement("year", mov.getYear() + ""));
        movieElement.addContent(makeElement("countries", "country", mov.getCountry()));
        movieElement.addContent(makeElement("genres", "genre", mov.getGenre()));

        movieElement.addContent(makeElement("writers", "writer", mov.getWriter()));
        movieElement.addContent(makeElement("directors", "director", mov.getDirector()));
        movieElement.addContent(makeElement("actors", "actor", mov.getActors()));

        movieElement.addContent(makeElement("poster", mov.getPoster()));

        movieElement.addContent(makeElement("plot", mov.getPlot()));

        movieElement.addContent(makeElement("file", en.getKey().getAbsolutePath()));

        rootElement.addContent(movieElement);
    }/*  ww  w  .  j  a v  a  2 s.c om*/

    Document doc = new Document();
    doc.setRootElement(rootElement);

    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());

    try {
        if (!rootDir.exists())
            rootDir.mkdirs();
        xmlOutput.output(doc, new FileWriter(xmlSourceFile));
    } catch (IOException ex) {
        Logger.getLogger(ViewAllMoviesHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.js.quickestquail.ui.actions.io.ExportToXMLAction.java

private void writeAll(File outputFile) {

    // progress dialog
    JProgressDialog dialog = new JProgressDialog(UI.get(), false);
    dialog.setMaximum(DriveManager.get().getSelected().size());
    dialog.setTitle(java.util.ResourceBundle.getBundle("i18n/i18n").getString("export.xml"));
    dialog.setVisible(true);//from  w  w  w  .j av  a2  s. c  o m

    // process in new thread
    new Thread() {
        @Override
        public void run() {
            try {
                Element rootElement = new Element("movies");

                List<Entry<File, String>> entries = new ArrayList<>(
                        DriveManager.get().getSelected().entrySet());
                java.util.Collections.sort(entries, new Comparator<Entry<File, String>>() {
                    @Override
                    public int compare(Entry<File, String> o1, Entry<File, String> o2) {
                        Movie mov1 = CachedMovieProvider.get().getMovieByID(o1.getValue());
                        Movie mov2 = CachedMovieProvider.get().getMovieByID(o2.getValue());
                        return mov1.getTitle().compareTo(mov2.getTitle());
                    }
                });

                int nofMovies = 0;
                for (Entry<File, String> en : entries) {
                    Movie mov = CachedMovieProvider.get().getMovieByID(en.getValue());

                    // update progress dialog
                    dialog.setText(mov.getTitle());
                    dialog.setProgress(nofMovies);

                    Element movieElement = new Element("movie");

                    movieElement.addContent(makeElement("imdbid", mov.getImdbID()));
                    movieElement.addContent(makeElement("imdbrating", mov.getImdbRating() + ""));
                    movieElement.addContent(makeElement("imdbvotes", mov.getImdbVotes() + ""));

                    movieElement.addContent(makeElement("title", mov.getTitle()));
                    movieElement.addContent(makeElement("year", mov.getYear() + ""));
                    movieElement.addContent(makeElement("countries", "country", mov.getCountry()));
                    movieElement.addContent(makeElement("genres", "genre", mov.getGenre()));

                    movieElement.addContent(makeElement("writers", "writer", mov.getWriter()));
                    movieElement.addContent(makeElement("directors", "director", mov.getDirector()));
                    movieElement.addContent(makeElement("actors", "actor", mov.getActors()));

                    movieElement.addContent(makeElement("poster", mov.getPoster()));

                    movieElement.addContent(makeElement("plot", mov.getPlot()));

                    movieElement.addContent(makeElement("file", en.getKey().getAbsolutePath()));

                    rootElement.addContent(movieElement);

                    nofMovies++;
                }

                Document doc = new Document();
                doc.setRootElement(rootElement);

                // close IO
                XMLOutputter xmlOutput = new XMLOutputter();
                xmlOutput.setFormat(Format.getPrettyFormat());
                xmlOutput.output(doc, new FileWriter(outputFile));

                // close dialog
                dialog.setVisible(false);

            } catch (Exception ex) {
            }
        }
    }.start();
}

From source file:com.khodev.sc2.quiz.Quiz.java

License:Open Source License

private void writeUserData(OutputStream s) throws IOException {
    Element root = new Element("Catalog");
    Document d = new Document(root);
    Element user = new Element("CUser").setAttribute("id", "QuizDictionary");
    root.addContent(user);//from  ww  w . j a v a  2 s. c om
    user.addContent(new Element("Fields").setAttribute("EditorColumn", "1").setAttribute("Id", "Level")
            .setAttribute("Type", "Int"));
    user.addContent(new Element("Fields").setAttribute("EditorColumn", "2").setAttribute("Id", "Question")
            .setAttribute("Type", "Text"));
    user.addContent(new Element("Fields").setAttribute("EditorColumn", "3").setAttribute("Id", "Answer")
            .setAttribute("Type", "Text"));
    user.addContent(new Element("Instances").setAttribute("Id", "[Default]"));

    int i = 0;
    for (Question question : questions) {
        i++;
        Element instance = new Element("Instances").setAttribute("Id", "" + i);
        user.addContent(instance);
        Element q = new Element("Text").setAttribute("Text", "UserData/QuizDictionary/" + i + "_Question");
        instance.addContent(q);
        q.addContent(new Element("Field").setAttribute("Id", "Question"));
        Element r = new Element("Text").setAttribute("Text", "UserData/QuizDictionary/" + i + "_Answer");
        instance.addContent(r);
        r.addContent(new Element("Field").setAttribute("Id", "Answer"));
    }
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(d, s);
}

From source file:com.kixeye.kixmpp.KixmppCodec.java

License:Apache License

/**
 * @see io.netty.handler.codec.ByteToMessageCodec#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, io.netty.buffer.ByteBuf)
 */// w  w w .jav a 2s.c  o  m
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    if (msg instanceof Element) {
        new XMLOutputter().output((Element) msg, new ByteBufOutputStream(out));
    } else if (msg instanceof KixmppStreamStart) {
        KixmppStreamStart streamStart = (KixmppStreamStart) msg;
        if (streamStart.doesIncludeXmlHeader()) {
            out.writeBytes("<?xml version='1.0' encoding='UTF-8'?>".getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes("<stream:stream ".getBytes(StandardCharsets.UTF_8));
        if (streamStart.getId() != null) {
            out.writeBytes(String.format("id=\"%s\" ", streamStart.getId()).getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getFrom() != null) {
            out.writeBytes(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getTo() != null) {
            out.writeBytes(String.format("to=\"%s\" ", streamStart.getTo().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes(
                "version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">"
                        .getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof KixmppStreamEnd) {
        out.writeBytes("</stream:stream>".getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof String) {
        out.writeBytes(((String) msg).getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;

        out.writeBytes(buf, 0, buf.readableBytes());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Sending: [{}]", out.toString(StandardCharsets.UTF_8));
    }
}

From source file:com.kixeye.kixmpp.KixmppWebSocketCodec.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    WebSocketFrame frame = null;/*from   w  w w.j a v a 2s .c o  m*/

    if (msg instanceof Element) {
        Element element = (Element) msg;

        if (element.getNamespace() == null || element.getNamespace() == Namespace.NO_NAMESPACE) {
            if ("stream".equals(element.getNamespacePrefix())) {
                element.setNamespace(Namespace.getNamespace("http://etherx.jabber.org/streams"));
            } else {
                element.setNamespace(Namespace.getNamespace("jabber:client"));

                IteratorIterable<Content> descendants = element.getDescendants();

                while (descendants.hasNext()) {
                    Content content = descendants.next();

                    if (content instanceof Element) {
                        Element descendantElement = (Element) content;
                        if (descendantElement.getNamespace() == null
                                || descendantElement.getNamespace() == Namespace.NO_NAMESPACE) {
                            descendantElement.setNamespace(element.getNamespace());
                        }
                    }
                }
            }
        }

        ByteBuf binaryData = ctx.alloc().buffer();
        new XMLOutputter().output((Element) msg, new ByteBufOutputStream(binaryData));

        frame = new TextWebSocketFrame(binaryData);
    } else if (msg instanceof KixmppStreamStart) {
        KixmppStreamStart streamStart = (KixmppStreamStart) msg;

        StringWriter writer = new StringWriter();

        if (streamStart.doesIncludeXmlHeader()) {
            writer.append("<?xml version='1.0' encoding='UTF-8'?>");
        }
        writer.append("<stream:stream ");
        if (streamStart.getId() != null) {
            writer.append(String.format("id=\"%s\" ", streamStart.getId()));
        }
        if (streamStart.getFrom() != null) {
            writer.append(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid()));
        }
        if (streamStart.getTo() != null) {
            writer.append(String.format("to=\"%s\" ", streamStart.getTo()));
        }
        writer.append(
                "version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">");

        frame = new TextWebSocketFrame(writer.toString());
    } else if (msg instanceof KixmppStreamEnd) {
        frame = new TextWebSocketFrame("</stream:stream>");
    } else if (msg instanceof String) {
        frame = new TextWebSocketFrame((String) msg);
    } else if (msg instanceof ByteBuf) {
        frame = new TextWebSocketFrame((ByteBuf) msg);
    }

    if (frame != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Sending: [{}]", frame.content().toString(StandardCharsets.UTF_8));
        }

        out.add(frame);
    }
}