Example usage for java.beans XMLEncoder writeObject

List of usage examples for java.beans XMLEncoder writeObject

Introduction

In this page you can find the example usage for java.beans XMLEncoder writeObject.

Prototype

public void writeObject(Object o) 

Source Link

Document

Write an XML representation of the specified object to the output.

Usage

From source file:org.settings4j.objectresolver.JavaXMLBeansObjectResolverTest.java

private byte[] objectToContent(final Object value) {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    final XMLEncoder encoder = new XMLEncoder(byteArrayOutputStream);
    encoder.setExceptionListener(new LogEncoderExceptionListener(value));

    LOG.debug("START Writing Object {} with XMLEncoder", value.getClass().getName());
    encoder.writeObject(value);
    LOG.debug("FINISH Writing Object {} with XMLEncoder", value.getClass().getName());

    encoder.flush();/* ww  w  . j a va  2  s .c o m*/
    encoder.close();
    return byteArrayOutputStream.toByteArray();
}

From source file:org.shaman.database.Benchmark.java

private void printSaveLoadTimes(Record... roots) throws IOException, ClassNotFoundException {
    //result array
    final int subpassCount = 5;
    long[][] saveTimes = new long[4][roots.length * subpassCount];
    long[][] loadTimes = new long[4][roots.length * subpassCount];

    DecimalFormat format = new DecimalFormat("0000");
    System.out.println("\ntime to save / load  (ms):");
    System.out.println("passes     database     serial    compressed     xml");
    System.out.println("           save\\load   save\\load   save\\load   save\\load");

    //for every data graph
    for (int i = 0; i < roots.length; i++) {
        File f1 = File.createTempFile("benchmark1", ".db");
        File f2 = File.createTempFile("benchmark2", ".serial");
        File f3 = File.createTempFile("benchmark3", ".serial");
        File f4 = File.createTempFile("benchmark4", ".xml");
        Record root = roots[i];//from  ww w.j a va  2  s .c o  m

        //save it multiple times
        for (int j = 0; j < subpassCount; j++) {
            int index = i * subpassCount + j;
            //delete files from previous pass
            f1.delete();
            f2.delete();
            f3.delete();
            f4.delete();

            long time1, time2;

            //database
            Database db = new Database(root);
            time1 = getTime();
            db.save(f1, FailOnErrorHandler.INSTANCE);
            time2 = getTime();
            saveTimes[0][index] = time2 - time1;

            //memory database
            //            time1 = getTime();
            //            ArrayOutput outp = new ArrayOutput();
            //            db.save(outp, FailOnErrorHandler.INSTANCE);
            //            outp.writeTo(f1b);
            //            time2 = getTime();
            //            saveTimes[0][index] = time2-time1;

            //uncompressed serialization
            time1 = getTime();
            OutputStream out = new BufferedOutputStream(new FileOutputStream(f2));
            ObjectOutputStream dos = new ObjectOutputStream(out);
            dos.writeObject(root);
            dos.close();
            time2 = getTime();
            saveTimes[1][index] = time2 - time1;

            //compressed serialization
            time1 = getTime();
            out = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(f3)));
            dos = new ObjectOutputStream(out);
            dos.writeObject(root);
            dos.close();
            time2 = getTime();
            saveTimes[2][index] = time2 - time1;

            //xml
            time1 = getTime();
            out = new BufferedOutputStream(new FileOutputStream(f4));
            XMLEncoder xml = new XMLEncoder(out);
            xml.writeObject(root);
            xml.close();
            time2 = getTime();
            saveTimes[3][index] = time2 - time1;
        }

        //load it multiple times
        for (int j = 0; j < subpassCount; j++) {
            int index = i * subpassCount + j;
            long time1, time2;

            //database
            time1 = getTime();
            Database db = new Database(f1, FailOnErrorHandler.INSTANCE);
            time2 = getTime();
            if (j == 0) {
                assertEquals(root, db.getRoot());
            }
            loadTimes[0][index] = time2 - time1;

            //memory database
            //            time1 = getTime();
            //            db = new Database(new StreamInput(f1b), FailOnErrorHandler.INSTANCE);
            //            time2 = getTime();
            //            if (j==0) {
            //               assertEquals(root, db.getRoot());
            //            }
            //            loadTimes[1][index] = time2-time1;

            //uncompressed serialization
            time1 = getTime();
            InputStream in = new BufferedInputStream(new FileInputStream(f2));
            ObjectInputStream dis = new ObjectInputStream(in);
            Object o = dis.readObject();
            dis.close();
            time2 = getTime();
            if (j == 0) {
                if (o instanceof SerializableStringMap) {
                    ((SerializableStringMap) o).postLoad();
                }
                assertEquals(root, o);
            }
            loadTimes[1][index] = time2 - time1;

            //compressed serialization
            time1 = getTime();
            in = new GZIPInputStream(new BufferedInputStream(new FileInputStream(f3)));
            dis = new ObjectInputStream(in);
            o = dis.readObject();
            dis.close();
            time2 = getTime();
            if (j == 0) {
                if (o instanceof SerializableStringMap) {
                    ((SerializableStringMap) o).postLoad();
                }
                assertEquals(root, o);
            }
            loadTimes[2][index] = time2 - time1;

            //xml
            time1 = getTime();
            in = new BufferedInputStream(new FileInputStream(f4));
            XMLDecoder xml = new XMLDecoder(in);
            o = xml.readObject();
            in.close();
            time2 = getTime();
            if (j == 0) {
                if (o instanceof SerializableStringMap) {
                    ((SerializableStringMap) o).postLoad();
                }
                assertEquals(root, o);
            }
            loadTimes[3][index] = time2 - time1;
        }
        //delete files
        f1.delete();
        f2.delete();
        f3.delete();
        f4.delete();

        //print this pass
        for (int j = 0; j < subpassCount; j++) {
            int index = i * subpassCount + j;
            System.out.print("pass " + (i + 1) + '\\' + (j + 1) + "   ");
            for (int h = 0; h < 4; h++) {
                //System.out.printf(format4, saveTimes[h][index]*getTimeMultiplicator());
                System.out.print(format.format(saveTimes[h][index] * getTimeMultiplicator()));
                System.out.print('\\');
                //System.out.printf(format4, loadTimes[h][index]*getTimeMultiplicator());
                System.out.print(format.format(loadTimes[h][index] * getTimeMultiplicator()));
                System.out.print("   ");
            }
            System.out.println();
        }
    }

}

From source file:com.swingtech.commons.util.ClassUtil.java

/**
 * NOTE: When using this to print an object it will not display the
 * primitive type boolean. Must use the wrapper class. All other primitives
 * work fine.//  www  . j  a  v a 2 s  . co m
 *
 * NOTE: If an int value has a 0 it won't display.
 *
 * NOTE: Object must have a public constructor.
 *
 * @param object
 * @return
 */
public static String getXMLForObject(final Object object) {
    ByteArrayOutputStream baos = null;
    XMLEncoder e = null;

    baos = new ByteArrayOutputStream();
    e = new XMLEncoder(new BufferedOutputStream(baos));

    e.setPersistenceDelegate(Date.class, new PersistenceDelegate() {
        @Override
        protected Expression instantiate(final Object oldInstance, final Encoder out) {
            final Date date = (Date) oldInstance;
            final Long time = new Long(date.getTime());
            return new Expression(date, date.getClass(), "new", new Object[] { time });
        }
    });

    e.setPersistenceDelegate(BigDecimal.class, new PersistenceDelegate() {
        @Override
        protected Expression instantiate(final Object oldInstance, final Encoder out) {
            final BigDecimal bigDec = (BigDecimal) oldInstance;
            final double doubleVal = bigDec.doubleValue();
            return new Expression(bigDec, bigDec.getClass(), "new", new Object[] { new Double(doubleVal) });
        }
    });

    e.writeObject(object);
    e.close();

    return baos.toString();
}

From source file:edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty.java

/** for debugging */
public void xmlToSysOut() {
    XMLEncoder e = new XMLEncoder(System.out);
    e.writeObject(this);
}

From source file:com.jk.framework.util.FakeRunnable.java

/**
 * To xml.//from  www.j  a  v  a  2 s  .c o  m
 *
 * @param obj
 *            the obj
 * @return the string
 */
// ////////////////////////////////////////////////////////////////////
public static String toXml(final Object obj) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    // XStream x = createXStream();
    // String xml = x.toXML(obj);
    // return xml;
    final XMLEncoder e = new XMLEncoder(out);
    e.setExceptionListener(new XmlEncoderExceptionListener());
    // e.setPersistenceDelegate(Object.class, new MyPersistenceDelegate());
    e.writeObject(obj);
    e.close();
    return out.toString();
    // return null;
}

From source file:org.latticesoft.util.common.FileUtil.java

/**
 * Write an object into the xmlfile/* w ww .ja v  a2  s.  co  m*/
 * @param filename the name of the file to output to
 * @param o the object to be serialized
 */
public static void writeToXmlFile(String filename, Object o) {
    if (o == null || filename == null) {
        return;
    }
    XMLEncoder encoder = null;
    try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(filename)));
        encoder.writeObject(o);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        try {
            encoder.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.amitycoin.enterprisetool.diagramInputServlet.java

@Override
@SuppressWarnings({ "null", "ValueOfIncrementOrDecrementUsed", "UnusedAssignment" })
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String filePath;/*from  w w  w.j  a v a 2s . co  m*/
    String docids;
    String userid;
    String a[][];
    a = new String[200][200];
    // database connection settings
    String dbURL = "jdbc:mysql://localhost:3306/enterprisedb";
    String dbUser = "root";
    String dbPass = "sandy";

    @SuppressWarnings("UnusedAssignment")
    Connection conn = null; // connection to the database
    userid = (String) request.getAttribute("uidM");
    String fname = (String) request.getAttribute("fnameM");
    int docid = (Integer) request.getAttribute("docidM");

    docids = "" + docid;
    String pathToWeb;
    pathToWeb = getServletContext().getRealPath(File.separator);
    System.out.println("pathtoweb:\t" + pathToWeb);
    filePath = pathToWeb + "readFiles\\";
    filePath = filePath + docids + userid + fname; //+.xls
    File myFile = new File(filePath);

    //boolean newExcel;
    //boolean oldExcel;
    String ext = FilenameUtils.getExtension(filePath);
    System.out.println("Extension: " + ext);

    FileInputStream fis = new FileInputStream(myFile);
    Workbook wb = null;
    if ("xls".equals(ext)) {
        // Finds the workbook instance for the file
        wb = new HSSFWorkbook(fis);

    } else if ("xlsx".equals(ext)) {
        wb = new XSSFWorkbook(fis);

    }

    @SuppressWarnings("null")
    Sheet mySheet;
    mySheet = wb.getSheetAt(0);

    // Get iterator to all the rows in current sheet
    Iterator<Row> rowIterator = mySheet.iterator();

    @SuppressWarnings("UnusedAssignment")
    int rowct = 0, colct = 0, colit = 0, ci = 0, ri = 0;

    // Traversing over each row of XLSX file
    while (rowIterator.hasNext()) {
        ri++;
        System.out.println("\nRi:\t" + ri);
        //Iterate over Rows
        Row row = rowIterator.next();

        if (1 == rowct) {
            colct = colit;
        }
        // For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        ci = 0;
        while (cellIterator.hasNext()) {

            ci++;

            System.out.println("\nCi:\t" + ci);
            //Iterate over Columns
            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                a[ri][ci] = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                double temp = cell.getNumericCellValue();
                String dblValue = "" + temp;
                a[ri][ci] = dblValue;
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(cell.getBooleanCellValue() + "\t");
                String tmp = "" + cell.getBooleanCellValue();
                a[ri][ci] = tmp;
                break;
            default:

            }
            colit++;

        }
        //rowit++;
        rowct++;
        //increase row count
    }

    System.out.println("Row Count:\t" + rowct);
    System.out.println("Column Count:\t" + colct);
    for (int i = 1; i <= rowct; i++) {
        for (int j = 1; j <= colct; j++) {
            System.out.println("a[" + i + "][" + j + "]=" + a[i][j] + "\n");
        }
    }
    try {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
        String append = "?, ?";
        String quest = ", ?";

        for (int j = 1; j <= colct; j++) {
            append += quest;
        }

        String crsql;
        String cappend = "`uid`,`doc_id`";
        for (int j = 1; j <= colct; j++) {
            cappend = cappend + ",`" + j + "`";
        }
        crsql = "CREATE TABLE IF NOT EXISTS `data" + userid + docid + "` (\n"
                + "`row_id` INT(11) NOT NULL AUTO_INCREMENT,\n" + "`uid` VARCHAR(50) NOT NULL,\n"
                + "`doc_id` INT(11) NOT NULL";
        System.out.println(crsql);

        for (int j = 1; j <= colct; j++) {
            System.out.println("j:\t" + (j));
            crsql = crsql + ",\n`" + (j) + "` VARCHAR(50)";
        }
        crsql += ",\nPRIMARY KEY (`row_id`)\n)";

        System.out.println(crsql);

        PreparedStatement cstmt = conn.prepareStatement(crsql);
        int c = cstmt.executeUpdate();

        String sql = "INSERT INTO data" + userid + docid + "(" + cappend + ")" + " values (" + append + ")";
        System.out.println("Append=\t" + append);
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, userid);
        statement.setInt(2, docid);
        for (int i = 1; i <= rowct; i++) {
            for (int j = 1; j <= (colct); j++) {
                statement.setString(j + 2, a[i][j]);
                System.out.println("j=" + (j) + "\ta[" + i + "][" + (j) + "]=" + a[i][j] + "\n");
            }
            System.out.println("\n");
            System.out.println("\nstatement:\t" + statement);
            int res = statement.executeUpdate();
        }
    } catch (SQLException ex) {
        Logger.getLogger(diagramInputServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    for (int i = 1; i <= rowct; i++) {
        for (int j = 1; j <= colct; j++) {
            System.out.println("a[" + i + "][" + j + "]=" + a[i][j] + "\n");
        }
    }
    System.out.println("Rowct:\t" + rowct + "\nColct:\t" + colct);
    @SuppressWarnings("UseOfObsoleteCollectionType")
    Hashtable<String, Object> style = new Hashtable<String, Object>();
    style.put(mxConstants.STYLE_FILLCOLOR, mxUtils.getHexColorString(Color.WHITE));
    style.put(mxConstants.STYLE_STROKEWIDTH, 1.5);
    style.put(mxConstants.STYLE_STROKECOLOR, mxUtils.getHexColorString(new Color(0, 0, 170)));
    style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_ELLIPSE);
    style.put(mxConstants.STYLE_PERIMETER, mxConstants.PERIMETER_ELLIPSE);

    graph = new mxGraph();

    mxStylesheet stylesheet = graph.getStylesheet();
    stylesheet.putCellStyle("process", createProcessStyle());
    stylesheet.putCellStyle("object", createObjectStyle());
    stylesheet.putCellStyle("state", createStateStyle());
    stylesheet.putCellStyle("agent", createAgentLinkStyle());
    fr = new JFrame("Enterprise Architecture Diagram");

    fr.setSize(2000, 2000);
    graph.setMinimumGraphSize(new mxRectangle(0, 0, 1000, 1500));
    graph.setMaximumGraphBounds(new mxRectangle(0, 0, 2000, 2000));
    graph.setMinimumGraphSize(new mxRectangle(0, 0, 1000, 1000));

    double rech1 = 200;
    double rech2 = 200;
    double rech3 = 170;
    double rech3e = 180;
    double rech4 = 120;
    Object defaultParent = graph.getDefaultParent();

    graph.setConstrainChildren(true);
    graph.setExtendParents(true);
    graph.setExtendParentsOnAdd(true);
    graph.setDefaultOverlap(0);
    graph.setCellsMovable(true); // Moving cells in the graph. Note that an edge is also a cell.
    graph.setCellsEditable(true);
    graph.setCellsResizable(true); // Inhibit cell re-sizing.

    graph.getModel().beginUpdate();

    Object[] obj = new Object[100];
    int k = 1;
    for (int i = 2; i <= rowct; i++) {
        for (int j = 1; j <= 2; j++) {
            obj[k] = a[i][j];
            k++;
        }

    }

    //print debug info
    for (int l = 1; l <= (rowct * 2) - 2; l++) {
        System.out.println("obj[" + l + "]:\t" + obj[l]);
    }

    List<Object> list = new ArrayList<Object>();
    for (Object val : obj) {
        if (!list.contains(val)) {
            list.add(val);
        }
    }

    list.remove(null);
    list.toArray(new Object[0]);
    System.out.println("list:" + list);

    Object[] array = new Object[list.size()];
    list.toArray(array); // fill the array
    System.out.println("Array:\t" + Arrays.toString(array));

    Object[] gArray = new Object[array.length];
    String[] sArray = new String[array.length];

    for (int i = 0; i < array.length; i++) {
        sArray[i] = array[i].toString();
        if (sArray[i].contains("Database") || sArray[i].contains("Server") || sArray[i].contains("DATABASE")
                || sArray[i].contains("SERVER") || sArray[i].contains("DB")) {
            System.out.println("Object type");
            gArray[i] = graph.insertVertex(defaultParent, null, sArray[i], rech1, rech2, rech3, rech4,
                    "object");

        } else {
            System.out.println("Process type");
            gArray[i] = graph.insertVertex(defaultParent, null, sArray[i], rech1, rech2, rech3e, rech4,
                    "process");
        }
        rech1 += 100;
        rech2 += 100;
    }

    for (int i = 2; i <= rowct; i++) {

        if (a[i][3].equals("Two Way") || a[i][3].equals("TWO WAY") || a[i][3].equals("TwoWay")
                || a[i][3].equals("TWOWAY") || a[i][3].equals("2 Way") || a[i][3].equals("Two way")) {
            System.out.println("Double Edges");
            int l1 = 0, l2 = 0;
            for (int l = 1; l < gArray.length; l++) {
                System.out.println("gArray.toString=\t" + sArray[l]);
                System.out.println("gArray.length=\t" + sArray.length);
                if (sArray[l].equals(a[i][1])) {
                    l1 = l;
                    System.out.println("l2:\t" + l1);
                }
                if (sArray[l].equals(a[i][2])) {
                    l2 = l;
                    System.out.println("l2:\t" + l2);
                }
            }
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l1], gArray[l2], "agent");
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l2], gArray[l1], "agent");

        } else {
            System.out.println("Single Edges");
            int l1 = 0, l2 = 0;
            for (int l = 1; l < gArray.length; l++) {
                System.out.println("gArray.toString=\t" + sArray[l]);
                System.out.println("gArray.length=\t" + sArray.length);
                if (sArray[l].equals(a[i][1])) {
                    l1 = l;
                    System.out.println("l2:\t" + l2);
                }
                if (sArray[l].equals(a[i][2])) {
                    l2 = l;
                    System.out.println("l2:\t" + l2);
                }
            }
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l1], gArray[l2], "agent");
        }
    }

    graph.setEnabled(true);

    graph.setAutoSizeCells(true);

    graph.getModel().endUpdate();

    graphComponent = new mxGraphComponent(graph);
    mxFastOrganicLayout layout = new mxFastOrganicLayout(graph);
    // define layout

    //set all properties
    layout.setMinDistanceLimit(1);
    //layout.setInitialTemp(5);
    //layout.setInitialTemp(10);
    //layout.setForceConstant(10);
    //layout.setDisableEdgeStyle(true);
    //layout graph
    //layout.execute(graph.getDefaultParent());
    // layout using morphing
    String fileWPath;

    graph.getModel().beginUpdate();
    try {
        layout.execute(graph.getDefaultParent());
    } finally {
        mxMorphing morph = new mxMorphing(graphComponent, 20, 1.2, 20);

        morph.addListener(mxEvent.DONE, new mxIEventListener() {

            @Override
            public void invoke(Object arg0, mxEventObject arg1) {
                graph.getModel().endUpdate();
                // fitViewport();
            }

        });

        BufferedImage image;
        image = mxCellRenderer.createBufferedImage(graph, null, 2, Color.WHITE, true, null);
        Document d = mxCellRenderer.createVmlDocument(graph, null, 1, Color.WHITE, null);
        pathToWeb = getServletContext().getRealPath(File.separator);
        System.out.println("pathtoweb:\t" + pathToWeb);
        fileWPath = pathToWeb + "genImg\\" + userid + docid + ".png";
        System.out.println("filewpath:\t" + fileWPath);
        //System.out.println(pathToWeb + userid + docid + ".svg");
        ImageIO.write(image, "PNG", new File(fileWPath));
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
                new FileOutputStream(new File(pathToWeb + "genXML\\" + userid + docid + ".xml"))));
        encoder.writeObject(graph);
        encoder.close();
        morph.startAnimation();
    }

    graphComponent.setConnectable(false);
    fr.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.WHITE));
    // Inhibit edge creation in the graph.
    fr.getContentPane().add(graphComponent);

    //fr.setVisible(true);

    request.setAttribute("docidM", docid);
    request.setAttribute("useridM", userid);
    request.setAttribute("colCountM", colct);
    request.setAttribute("rowCountM", rowct);
    request.setAttribute("fileLinkM", fileWPath);
    request.setAttribute("pathToWebM", pathToWeb);
    System.out.println("Iteration Complete");

    getServletContext().getRequestDispatcher("/success.jsp").forward(request, response);

}

From source file:com.alvermont.terraj.stargen.ui.StargenFrame.java

private void saveMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveMenuItemActionPerformed
{//GEN-HEADEREND:event_saveMenuItemActionPerformed

    final int choice = this.xmlChooser.showSaveDialog(this);

    if (choice == JFileChooser.APPROVE_OPTION) {
        if (!this.xmlChooser.getSelectedFile().exists() || (JOptionPane.showConfirmDialog(this,
                "This file already exists. Do you want to\n" + "overwrite it?", "Replace File?",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) {
            try {
                final File target = FileUtils.addExtension(this.xmlChooser.getSelectedFile(), ".xml");

                final XMLEncoder enc = new XMLEncoder(new FileOutputStream(target));

                enc.writeObject(this.parameters);

                enc.close();//  w ww .j a  va  2s .c o  m
            } catch (IOException ioe) {
                log.error("Error writing xml file", ioe);

                JOptionPane.showMessageDialog(this,
                        "Error: " + ioe.getMessage() + "\nCheck log file for full details", "Error Saving",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

From source file:psidev.psi.mi.filemakers.xmlMaker.XmlMakerGui.java

public void save() {
    try {//from  ww w  .  j  a  v a2s  . c  om
        JFileChooser fc;
        if (Utils.lastVisitedMappingDirectory != null) {
            fc = new JFileChooser(Utils.lastVisitedMappingDirectory);
        } else
            fc = new JFileChooser(".");

        int returnVal = fc.showSaveDialog(new JFrame());
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }

        FileOutputStream fos = new FileOutputStream(fc.getSelectedFile());

        // Create XML encoder.
        XMLEncoder xenc = new XMLEncoder(fos);

        Mapping mapping = new Mapping();
        mapping.setTree(((XsdTreeStructImpl) treePanel.xsdTree).getMapping());

        /* dictionaries */
        for (int i = 0; i < treePanel.dictionaryPanel.dictionaries.getDictionaries().size(); i++) {
            //            DictionaryMapping dm = ((Dictionary) xsdTree.dictionaries
            //                  .getDictionaries().get(i)).getMapping();
            mapping.dictionaries.add(((Dictionary) xsdTree.dictionaries.getDictionaries().get(i)).getMapping());
        }

        /* flat files */
        for (int i = 0; i < xsdTree.flatFiles.flatFiles.size(); i++) {
            //            FlatFileMapping fm = (xsdTree.flatFiles.getFlatFile(i))
            //                  .getMapping();
            mapping.flatFiles.add((xsdTree.flatFiles.getFlatFile(i)).getMapping());
        }

        xenc.writeObject(mapping);

        xenc.close();
        fos.close();
    } catch (FileNotFoundException fe) {
        JOptionPane.showMessageDialog(new JFrame(), "Unable to write file",
                "[PSI makers: PSI maker] save mapping", JOptionPane.ERROR_MESSAGE);
    } catch (Exception ex) {
        System.out.println("pb: " + ex);
        StackTraceElement[] s = ex.getStackTrace();
        for (int i = 0; i < s.length; i++) {
            System.out.println(s[i]);
        }
    }
}

From source file:jeplus.JEPlusProject.java

/**
 * Save this project to an XML file/*from   w ww.  j  a  v a 2  s . c  o m*/
 * @param fn The File object associated with the file to which the contents will be saved
 * @return Successful or not
 */
public boolean saveAsXML(File fn) {
    boolean success = true;

    // Write project file
    XMLEncoder encoder;
    try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fn)));
        // Clear external parameters and rvx file reference fields before saving the project
        // These files are for importing only
        this.ParamFile = null;
        this.RvxFile = null;
        encoder.writeObject(this);
        encoder.close();
        // get new location of project file
        String dir = fn.getAbsoluteFile().getParent();
        dir = dir.concat(dir.endsWith(File.separator) ? "" : File.separator);
        this.updateBaseDir(dir);
        this.ContentChanged = false;
    } catch (FileNotFoundException ex) {
        logger.error("Failed to create " + fn + " for writing project.", ex);
        success = false;
    }
    return success;
}