Example usage for java.util.prefs Preferences exportSubtree

List of usage examples for java.util.prefs Preferences exportSubtree

Introduction

In this page you can find the example usage for java.util.prefs Preferences exportSubtree.

Prototype

public abstract void exportSubtree(OutputStream os) throws IOException, BackingStoreException;

Source Link

Document

Emits an XML document representing all of the preferences contained in this node and all of its descendants.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");

    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");

    FileOutputStream fos = new FileOutputStream("prefs.xml");

    myPrefs.exportSubtree(fos);
    fos.close();//from  ww  w . j a  v  a 2  s.co m

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(String.class);

    // Save some values
    prefs.put("myString", "a string"); // String
    prefs.putBoolean("myBoolean", true); // boolean
    prefs.putInt("myInt", 123); // int
    prefs.putLong("myLong", 123L); // long

    // Save some values in the parent node
    prefs = prefs.parent();//  w w  w .jav  a 2 s  . c  om
    prefs.putFloat("myFloat", 12.3F); // float
    prefs.putDouble("myDouble", 12.3); // double
    byte[] bytes = new byte[10];
    prefs.putByteArray("myByteArray", bytes); // byte[]

    prefs.exportSubtree(new FileOutputStream("output.xml"));
}

From source file:PreferenceExample.java

public void exportToFile(Preferences p, String fileName) throws BackingStoreException {
    try {/*from w ww  . j  a  v  a2 s  .  c  om*/
        FileOutputStream fos = new FileOutputStream(fileName);

        p.exportSubtree(fos);
        fos.close();
    } catch (IOException ioe) {
        System.out.println("IOException in exportToFile\n" + ioe);
        ioe.printStackTrace();
    }
}

From source file:PreferencesTest.java

public PreferencesFrame() {
    // get position, size, title from preferences

    Preferences root = Preferences.userRoot();
    final Preferences node = root.node("/com/horstmann/corejava");
    int left = node.getInt("left", 0);
    int top = node.getInt("top", 0);
    int width = node.getInt("width", DEFAULT_WIDTH);
    int height = node.getInt("height", DEFAULT_HEIGHT);
    setBounds(left, top, width, height);

    // if no title given, ask user

    String title = node.get("title", "");
    if (title.equals(""))
        title = JOptionPane.showInputDialog("Please supply a frame title:");
    if (title == null)
        title = "";
    setTitle(title);//from ww  w .  ja  va 2  s. co m

    // set up file chooser that shows XML files

    final JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    // accept all files ending with .xml
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
        }

        public String getDescription() {
            return "XML files";
        }
    });

    // set up menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem exportItem = new JMenuItem("Export preferences");
    menu.add(exportItem);
    exportItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    OutputStream out = new FileOutputStream(chooser.getSelectedFile());
                    node.exportSubtree(out);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem importItem = new JMenuItem("Import preferences");
    menu.add(importItem);
    importItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    InputStream in = new FileInputStream(chooser.getSelectedFile());
                    Preferences.importPreferences(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            node.putInt("left", getX());
            node.putInt("top", getY());
            node.putInt("width", getWidth());
            node.putInt("height", getHeight());
            node.put("title", getTitle());
            System.exit(0);
        }
    });
}

From source file:org.rhq.enterprise.server.agent.EmbeddedAgentBootstrapService.java

/**
 * Loads the {@link #getConfigurationFile() configuration file}. The file location will first be checked for
 * existence on the file system and then as a URL. If it cannot be found, it will be assumed the file location
 * specifies the file as found in the current class loader and the file will be searched there. An exception is
 * thrown if the file cannot be found anywhere.
 *
 * @return the configuration that was loaded
 *
 * @throws IOException                       if failed to load the configuration file
 * @throws InvalidPreferencesFormatException if the configuration file had an invalid format
 * @throws BackingStoreException             if failed to access the preferences persistence store
 * @throws Exception                         on other failures
 *//*from w w  w .  j a va  2 s .co m*/
private AgentConfiguration loadConfigurationFile() throws Exception {
    String file_name = getConfigurationFile();
    String preferences_node_name = getPreferencesNodeName();
    InputStream config_file_input_stream = null;

    // first see if the file was specified as a path on the local file system
    try {
        File config_file = new File(file_name);

        if (config_file.exists()) {
            config_file_input_stream = new FileInputStream(config_file);
        }
    } catch (Exception e) {
        // isn't really an error - this just isn't a file on the local file system
    }

    // see if the file was specified as a URL
    if (config_file_input_stream == null) {
        try {
            URL config_file = new URL(file_name);

            config_file_input_stream = config_file.openStream();
        } catch (Exception e) {
            // isn't really an error - this just isn't a URL
        }
    }

    // if neither a file path or URL, assume the config file can be found in the classloader
    if (config_file_input_stream == null) {
        config_file_input_stream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(file_name);
    }

    if (config_file_input_stream == null) {
        throw new IOException("Bad config file: " + file_name);
    }

    // We need to clear out any previous configuration in case the current config file doesn't specify a preference
    // that already exists in the preferences node.  In this case, the configuration file wants to fall back on the
    // default value and if we don't clear the preferences, we aren't guaranteed the value stored in the backing
    // store is the default value.
    // But first we need to backup these original preferences in case the config file fails to load -
    // we'll restore the original values in that case.

    Preferences preferences_node = getPreferencesNode();
    ByteArrayOutputStream backup = new ByteArrayOutputStream();
    preferences_node.exportSubtree(backup);
    preferences_node.clear();

    // now load in the preferences
    try {
        ByteArrayOutputStream raw_config_file = new ByteArrayOutputStream();
        StreamUtil.copy(config_file_input_stream, raw_config_file, true);
        String new_config = StringPropertyReplacer.replaceProperties(raw_config_file.toString());
        ByteArrayInputStream new_config_input_stream = new ByteArrayInputStream(new_config.getBytes());
        Preferences.importPreferences(new_config_input_stream);

        if (new AgentConfiguration(preferences_node).getAgentConfigurationVersion() == 0) {
            throw new IllegalArgumentException("Bad node name: " + preferences_node_name);
        }
    } catch (Exception e) {
        // a problem occurred importing the config file; let's restore our original values
        try {
            Preferences.importPreferences(new ByteArrayInputStream(backup.toByteArray()));
        } catch (Exception e1) {
            // its conceivable the same problem occurred here as with the original exception (backing store problem?)
            // let's throw the original exception, not this one
        }

        throw e;
    }

    AgentConfiguration agent_configuration = new AgentConfiguration(preferences_node);

    return agent_configuration;
}