Example usage for java.beans XMLDecoder XMLDecoder

List of usage examples for java.beans XMLDecoder XMLDecoder

Introduction

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

Prototype

public XMLDecoder(InputSource is) 

Source Link

Document

Creates a new decoder to parse XML archives created by the XMLEncoder class.

Usage

From source file:jeplus.JEPlusProject.java

/**
 * Read a project from an XML file. The members of this project are not updated.
 * @param fn The File object associated with the file
 * @return a new project instance from the file
 *//*from   w  w  w. j  av a  2  s.co m*/
public static JEPlusProject loadAsXML(File fn) {
    JEPlusProject proj;
    try (XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(fn)))) {
        proj = ((JEPlusProject) decoder.readObject());
    } catch (Exception ex) {
        logger.error("Error loading project from file " + fn, ex);
        return null;
    }
    String dir = fn.getAbsoluteFile().getParent();
    dir = dir.concat(dir.endsWith(File.separator) ? "" : File.separator);
    // proj.updateBaseDir(dir);
    proj.setBaseDir(dir);
    if (proj.ParamFile != null) {
        // Load parameters from text file
        proj.importParameterTableFile(new File(RelativeDirUtil.checkAbsolutePath(proj.ParamFile, dir)));
    } else {
        // Reassign reference to project in all parameters
        if (proj.getParamTree() != null) {
            Enumeration params = proj.getParamTree().breadthFirstEnumeration();
            while (params.hasMoreElements()) {
                ((ParameterItem) ((DefaultMutableTreeNode) params.nextElement()).getUserObject())
                        .setProject(proj);
            }
        }
    }
    // Assign the first branch to the Parameters list
    DefaultMutableTreeNode thisleaf = proj.getParamTree().getFirstLeaf();
    Object[] path = thisleaf.getUserObjectPath();
    proj.setParameters(new ArrayList<ParameterItem>());
    for (Object item : path) {
        proj.getParameters().add((ParameterItem) item);
    }
    // Load Rvx if a RVX file is available
    try {
        proj.Rvx = RVX.getRVX(proj.resolveRVIDir() + proj.getRVIFile());
    } catch (IOException ioe) {
        logger.error("Cannot read the project's RVX file", ioe);
    }

    // done            
    return proj;
}

From source file:org.scantegrity.scanner.Scanner.java

/**
 * Get and set up the configuration file data.
 * /*from  w w w  .ja va  2 s.c o  m*/
 * This file configures the election.
 * 
 * @param p_configPath - The path. 
 * @return
 */
private static ScannerConfig getConfiguration(String p_configPath) {
    ScannerConfig l_config = new ScannerConfig();

    File c_loc = null;

    try {
        if (p_configPath == null) {
            c_loc = new FindFile(ScannerConstants.DEFAULT_CONFIG_NAME).find();
        } else {
            c_loc = new File(p_configPath);
        }

        if (!c_loc.isFile()) {
            c_loc = new FindFile(ScannerConstants.DEFAULT_CONFIG_NAME).find();
            System.err.println("Could not open file.");
        }
    } catch (NullPointerException e_npe) {
        System.err.println("Could not open file. File does not exist.");
        e_npe.printStackTrace();
        criticalExit(5);
    }

    //TODO: make sure the file is found and is readable
    if (c_loc == null) {
        System.err.println("Critical Error: Could not open configuration " + "file. System Exiting.");
        criticalExit(10);
    }

    XMLDecoder e;
    try {
        e = new XMLDecoder(new BufferedInputStream(new FileInputStream(c_loc)));
        l_config = (ScannerConfig) e.readObject();
        e.close();
    } catch (Exception e_e) {
        System.err.println("Could not parse Configuration File!");
        e_e.printStackTrace();
        criticalExit(20);
    }

    return l_config;
}

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];/*  w w  w  . j a  v a 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.jk.util.JKObjectUtil.java

/**
 * To object./*from  w  ww . jav a2  s  .  c  om*/
 *
 * @param xml
 *            the xml
 * @return the object
 */
public static Object toObject(final String xml) {
    // XStream x = createXStream();
    // return x.fromXML(xml);
    // try {
    final ByteArrayInputStream out = new ByteArrayInputStream(xml.getBytes());
    final XMLDecoder encoder = new XMLDecoder(out);
    final Object object = encoder.readObject();
    //
    encoder.close();
    return object;
    // } catch (Exception e) {
    // System.err.println("Failed to decode object : \n" + xml);
    // return null;
    // }
    // return null;
}

From source file:com.snp.site.init.SystemInit.java

public static void initUrlmap() {
    XMLDecoder xmlDecoder;//from   www .  j a v a 2 s.c o  m
    try {
        xmlDecoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(getUrlmapConfigpath())));
        UrlConfig urlconfig = (UrlConfig) xmlDecoder.readObject();
        urlmap = urlconfig.getUrlmap();

    } catch (Exception e) {
        log.debug("email urlmap config file doest not exit!");

    }
}

From source file:psidev.psi.mi.filemakers.xmlFlattener.XmlFlattenerGui.java

public void load() {
    try {//from   w w w.  ja  v a2 s.  c  o m
        String directory = Utils.lastVisitedMappingDirectory;
        if (directory == null)
            directory = Utils.lastVisitedDirectory;

        JFileChooser fc = new JFileChooser(directory);

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

        Utils.lastVisitedDirectory = fc.getSelectedFile().getPath();
        Utils.lastVisitedMappingDirectory = fc.getSelectedFile().getPath();

        try {
            FileInputStream fin = new FileInputStream(fc.getSelectedFile());

            JAXBContext jaxbContext = JAXBContext.newInstance(TreeMapping.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            TreeMapping treeMapping = (TreeMapping) jaxbUnmarshaller.unmarshal(fin);
            ((XsdTreeStructImpl) treePanel.xsdTree).loadMapping(treeMapping);
            fin.close();
        } catch (JAXBException jbe) {
            System.out.println("Not a JAXB file, try with old format");
            FileInputStream fin = new FileInputStream(fc.getSelectedFile());
            // Create XML encoder.
            XMLDecoder xdec = new XMLDecoder(fin);
            /* get mapping */
            TreeMapping treeMapping = (TreeMapping) xdec.readObject();
            ((XsdTreeStructImpl) treePanel.xsdTree).loadMapping(treeMapping);
            xdec.close();
            fin.close();
        }

        /* tree */

        treePanel.updatePreview();

        treePanel.setTreeSelectionListener();
        treePanel.setCellRenderer();
        treePanel.xsdTree.check();
        treePanel.reload();
    } catch (FileNotFoundException fe) {
        treePanel.xsdTree.getMessageManager().sendMessage("unable to load mapping file (file not found)",
                MessageManagerInt.errorMessage);
        log.error("unable to load mapping file", fe);
    } catch (IOException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (unable to read the file, IO exception)",
                MessageManagerInt.errorMessage);
        log.error("unable to load mapping file", ex);
    } catch (SAXException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (problem for parsing the XML file)",
                MessageManagerInt.errorMessage);
        log.error("xml problem", ex);
    } catch (NoSuchElementException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (an element is missing in the mapping file, maybe this file is too old and not compatible anymore)",
                MessageManagerInt.errorMessage);
        log.error("xml problem", ex);
    } catch (ClassCastException ex) {
        treePanel.xsdTree.getMessageManager().sendMessage(
                "unable to load mapping file (it doesn't seem to be a mapping file)",
                MessageManagerInt.errorMessage);
        log.error("xml problem", ex);
    }
}

From source file:com.snp.site.init.SystemInit.java

/** demo? ??????? */
static public DataBaseConfig getObjectDemo(String xmlObjectString) throws FileNotFoundException, IOException {

    // ??//from  w  ww .  ja  va 2  s .com
    // 1.?
    XMLDecoder xmlDecoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(xmlObjectString)));
    DataBaseConfig objectDemo = (DataBaseConfig) xmlDecoder.readObject();
    xmlDecoder.close();
    /*
     * 2.???,?????????
     * ?DEMO??XML??DEMO??
     */
    return objectDemo;
}

From source file:com.snp.site.init.SystemInit.java

/**
 * XML?? ?//w  ww.  j a  v  a  2  s  . c o m
 * 
 */
static public LanmuConfig getLanmuObjectFromXml(String xmlObjectString) throws Exception {
    try {

        XMLDecoder xmlDecoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(xmlObjectString)));
        LanmuConfig lanmuObject = (LanmuConfig) xmlDecoder.readObject();
        xmlDecoder.close();
        if (lanmuObject == null)
            throw new Exception();
        return lanmuObject;
    } catch (Exception e) {
        throw e;
    }
}

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

public static Object getObjectFromXML(final InputStream inStream) {
    final XMLDecoder d = new XMLDecoder(new BufferedInputStream(inStream));

    final Object result = d.readObject();
    d.close();//  w w  w.ja v  a 2 s  . c  o  m
    return result;
}

From source file:org.dawnsci.common.richbeans.beans.BeanUI.java

/**
 * Bean from string using standard java serialization, useful for tables of beans with serialized strings. Used
 * externally to the GDA./*  w  w  w  .  j a v a2 s.  c om*/
 * 
 * @param xml
 * @return the bean
 */
public static Object getBean(final String xml, final ClassLoader loader) throws Exception {

    final ClassLoader original = Thread.currentThread().getContextClassLoader();
    final ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    try {
        Thread.currentThread().setContextClassLoader(loader);
        XMLDecoder d = new XMLDecoder(new BufferedInputStream(stream));
        final Object bean = d.readObject();
        d.close();
        return bean;
    } finally {
        Thread.currentThread().setContextClassLoader(original);
        stream.close();
    }
}