Example usage for java.util.prefs Preferences flush

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

Introduction

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

Prototype

public abstract void flush() throws BackingStoreException;

Source Link

Document

Forces any changes in the contents of this preference node and its descendants to the persistent store.

Usage

From source file:org.rhq.server.control.command.AbstractInstall.java

private void clearAgentPreferences() throws Exception {
    log.info("Removing any existing agent preferences from default preference node");

    // remove everything EXCEPT the security token
    Preferences agentPrefs = getAgentPreferences();
    String[] prefKeys = null;// w  ww.j  a v a2 s.  c  o m

    try {
        prefKeys = agentPrefs.keys();
    } catch (Exception e) {
        log.warn("Failed to get agent preferences - cannot clear them: " + e);
    }

    if (prefKeys != null && prefKeys.length > 0) {
        for (String prefKey : prefKeys) {
            if (!prefKey.equals(PREF_RHQ_AGENT_SECURITY_TOKEN)) {
                agentPrefs.remove(prefKey);
            }
        }
        agentPrefs.flush();
        Preferences.userRoot().sync();
    }
}

From source file:com.basho.riak.pbc.RiakClient.java

/**
 * helper method to use a reasonable default client id
 * beware, it caches the client id. If you call it multiple times on the same client
 * you get the *same* id (not good for reusing a client with different ids)
 * //w  w  w  .j ava  2  s .co  m
 * @throws IOException
 */
public void prepareClientID() throws IOException {
    Preferences prefs = Preferences.userNodeForPackage(RiakClient.class);

    String clid = prefs.get("client_id", null);
    if (clid == null) {
        SecureRandom sr;
        try {
            sr = SecureRandom.getInstance("SHA1PRNG");
            // Not totally secure, but doesn't need to be
            // and 100% less prone to 30 second hangs on linux jdk5
            sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] data = new byte[6];
        sr.nextBytes(data);
        clid = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
        prefs.put("client_id", clid);
        try {
            prefs.flush();
        } catch (BackingStoreException e) {
            throw new IOException(e.toString());
        }
    }

    setClientID(clid);
}

From source file:org.kuali.test.creator.TestCreator.java

private void loadPreferences() {
    try {//from  w  w w  .  j av  a  2 s. c  o  m
        Preferences proot = Preferences.userRoot();
        Preferences node = proot.node(Constants.PREFS_ROOT_NODE);
        int left = node.getInt(Constants.PREFS_MAINFRAME_LEFT, Constants.MAINFRAME_DEFAULT_LEFT);
        int top = node.getInt(Constants.PREFS_MAINFRAME_TOP, Constants.MAINFRAME_DEFAULT_TOP);
        int width = node.getInt(Constants.PREFS_MAINFRAME_WIDTH, Constants.MAINFRAME_DEFAULT_WIDTH);
        int height = node.getInt(Constants.PREFS_MAINFRAME_HEIGHT, Constants.MAINFRAME_DEFAULT_HEIGHT);
        setState(node.getInt(Constants.PREFS_MAINFRAME_WINDOW_STATE, Frame.NORMAL));

        setBounds(left, top, width, height);

        node.flush();
    }

    catch (BackingStoreException ex) {
        LOG.error(ex.toString(), ex);
    }
}

From source file:org.kuali.test.creator.TestCreator.java

private void savePreferences() {
    try {//from  www. j av  a  2 s .  c o m
        Preferences proot = Preferences.userRoot();
        Preferences node = proot.node(Constants.PREFS_ROOT_NODE);

        Rectangle rect = getBounds();

        node.putInt(Constants.PREFS_MAINFRAME_LEFT, rect.x);
        node.putInt(Constants.PREFS_MAINFRAME_TOP, rect.y);
        node.putInt(Constants.PREFS_MAINFRAME_WIDTH, rect.width);
        node.putInt(Constants.PREFS_MAINFRAME_HEIGHT, rect.height);
        node.putInt(Constants.PREFS_HORIZONTAL_DIVIDER_LOCATION, hsplitPane.getDividerLocation());
        node.putInt(Constants.PREFS_VERTICAL_DIVIDER_LOCATION, vsplitPane.getDividerLocation());
        node.putInt(Constants.PREFS_MAINFRAME_WINDOW_STATE, getState());

        node.flush();
    }

    catch (BackingStoreException ex) {
        LOG.error(ex.toString(), ex);
    }

}

From source file:verdandi.ui.ProjectViewerPanel.java

private void exportProjects() {
    Preferences prefs = Preferences.userNodeForPackage(getClass());

    File exportDir = new File(prefs.get("export.dir", System.getProperty("user.home")));

    JFileChooser chooser = new JFileChooser(exportDir);
    chooser.setDialogTitle(RB.getString("projectviewer.export.filechooser.title"));
    chooser.setMultiSelectionEnabled(false);

    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
        LOG.debug("User cancelled");
        return;//ww  w .j a  v a 2 s  .co  m
    }

    int[] selectedProjects = projectTable.getSelectedRows();

    if (selectedProjects.length == 0) {
        LOG.debug("NO row selected");
        return;
    }

    List<CostUnit> projectsToExport = new ArrayList<CostUnit>();

    for (int i = 0; i < selectedProjects.length; i++) {
        // int selModel = projectTable.getFilters().convertRowIndexToModel(
        // selectedProjects[i]);
        int selModel = selectedProjects[i];
        CostUnit p = tableModel.getProject(selModel);
        LOG.debug("Adding project to export list: " + p);
        projectsToExport.add(p);
    }

    File exportFile = chooser.getSelectedFile();
    LOG.debug("Exporting projects to " + exportFile.getAbsolutePath());

    ObjectOutputStream listOut = null;
    try {
        listOut = new ObjectOutputStream(new FileOutputStream(exportFile));
        listOut.writeObject(projectsToExport);
    } catch (FileNotFoundException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } finally {
        if (listOut != null) {
            try {
                listOut.close();
            } catch (Throwable t) {
                LOG.error("Cannot close stream: ", t);
            }
        }
    }

    prefs.put("export.dir", exportFile.getParent());
    try {
        prefs.flush();
    } catch (BackingStoreException e) {
        LOG.error("Cannot write export file preference", e);
    }

}

From source file:com.adito.server.DefaultAditoServerFactory.java

public Integer start(String[] args) {
    startupStarted = System.currentTimeMillis();

    // Inform the wrapper the startup process may take a while
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }//  w w w .  j a  va 2s  . c  om

    // Parse the command line
    Integer returnCode = parseCommandLine(args);
    if (returnCode != null) {
        if (returnCode == 999) {
            return null;
        }
        return returnCode;
    }

    // Create the boot progress monitor
    if (gui) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        } catch (UnsupportedLookAndFeelException e) {
        }
        bootProgressMonitor = new SwingBootProgressMonitor();
    } else {
        bootProgressMonitor = new LogBootProgressMonitor();
    }

    //
    resourceCaches = new HashMap<URL, ResourceCache>();
    contextListeners = new ArrayList<ContextListener>();

    loadSystemProperties();
    initialiseLogging();

    /*
     * Migrate preferences.
     */
    File newPrefDir = new File(ContextHolder.getContext().getConfDirectory(), "prefs");
    PREF = PropertyPreferences.SYSTEM_ROOT;
    try {
        if (!newPrefDir.exists() && Preferences.systemRoot().node("/com").nodeExists("adito")) {
            Preferences from = Preferences.systemRoot().node("/com/adito");
            LOG.warn("Migrating preferences");
            try {
                copyNode(from.node("core"), PREF.node("core"));
                from.node("core").removeNode();
                copyNode(from.node("plugin"), PREF.node("plugin"));
                from.node("plugin").removeNode();
                copyNode(from.node("extensions"), PREF.node("extensions"));
                from.node("extensions").removeNode();
                copyNode(from.node("dbupgrader"), PREF.node("dbupgrader"));
                from.node("dbupgrader").removeNode();
            } catch (BackingStoreException e) {
                LOG.error("Failed to migrate preferences.", e);
            }
            try {
                from.flush();
            } catch (BackingStoreException bse) {
                LOG.error("Failed to flush old preferences");
            }
            try {
                PREF.flush();
            } catch (BackingStoreException bse) {
                LOG.error("Failed to flush new preferences");
            }
            if (LOG.isInfoEnabled()) {
                LOG.info("Flushing preferences");
            }

        }
    } catch (BackingStoreException bse) {
        LOG.error("Failed to migrate preferences.", bse);
    }

    // Inform the wrapper the startup process is going ok
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }

    try {
        clearTemp();
        try {
            hostname = Inet4Address.getLocalHost().getCanonicalHostName();
            hostAddress = Inet4Address.getLocalHost().getHostAddress();
        } catch (UnknownHostException ex) {
            // This should be fatal, we now rely on the hostname being
            // available
            throw new Exception("The host name or address on which this service is running could not "
                    + "be determined. Check you network configuration. One possible cause is "
                    + "a misconfigured 'hosts' file (e.g. on UNIX-like systems this would be "
                    + "/etc/hosts, on Windows XP it would be "
                    + "C:\\Windows\\System32\\Drivers\\Etc\\Hosts).");
        }

        PropertyClassManager.getInstance()
                .registerPropertyClass(contextConfiguration = new ContextConfig(getClass().getClassLoader()));

        // Display some information about the system we are running on
        displaySystemInfo();

        // Load the context property definitions
        loadContextProperties();

        // Inform the wrapper the startup process is going ok
        if (useWrapper) {
            WrapperManager.signalStarting(60000);
        }

        // Configure any HTTP / HTTPS / SOCKS proxy servers
        configureProxyServers();

        PropertyList l = contextConfiguration.retrievePropertyList(new ContextKey("webServer.bindAddress"));
        getBootProgressMonitor().updateMessage("Creating server lock");
        getBootProgressMonitor().updateProgress(6);
        serverLock = new ServerLock(l.get(0));
        if (serverLock.isLocked()) {
            if (!isSetupMode()) {
                if (serverLock.isSetup()) {
                    throw new Exception("The installation wizard is currently running. "
                            + "Please shut this down by pointing your browser " + "to http://" + getHostname()
                            + ":" + serverLock.getPort()
                            + "/showShutdown.do before attempting to start the server again.");
                } else {
                    throw new Exception("The server is already running.");
                }
            } else {
                if (!serverLock.isSetup()) {
                    throw new Exception("The server is currently already running. "
                            + "Please shut this down by pointing your browser " + "to https://" + getHostname()
                            + ":" + serverLock.getPort()
                            + "/showShutdown.do before attempting to start the server again.");
                } else {
                    throw new Exception("The installation wizard is running..");
                }

            }

        }

        // Inform the wrapper the startup process is going ok
        if (useWrapper) {
            WrapperManager.signalStarting(60000);
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                serverLock.stop();
            }
        });

        //
        registerKeyStores();

        //
        threadGroup = new ThreadGroup("MainThreadGroup");

        if (install) {
            setupMode();

        } else {
            normalMode();
            startHttpServer();
        }
    } catch (Exception t) {
        startupException = t;
        LOG.error("Failed to start the server. " + t.getMessage(), t);
        return 1;
    }

    return null;
}

From source file:com.adito.server.Main.java

public Integer start(String[] args) {
    startupStarted = System.currentTimeMillis();

    // Inform the wrapper the startup process may take a while
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }//from w  w  w  .  j  a  va  2  s.c  o m

    // Parse the command line
    Integer returnCode = parseCommandLine(args);
    if (returnCode != null) {
        if (returnCode.intValue() == 999) {
            return null;
        }
        return returnCode;
    }

    // Create the boot progress monitor
    if (gui) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        bootProgressMonitor = new SwingBootProgressMonitor();
    } else {
        bootProgressMonitor = new LogBootProgressMonitor();
    }

    //
    resourceCaches = new HashMap<URL, ResourceCache>();
    contextListeners = new ArrayList<ContextListener>();

    loadSystemProperties();
    initialiseLogging();

    /*
     * Migrate preferences.
     */
    File newPrefDir = new File(ContextHolder.getContext().getConfDirectory(), "prefs");
    PREF = PropertyPreferences.SYSTEM_ROOT;
    try {
        if (!newPrefDir.exists() && Preferences.systemRoot().node("/com").nodeExists("adito")) {
            Preferences from = Preferences.systemRoot().node("/com/adito");
            log.warn("Migrating preferences");
            try {
                copyNode(from.node("core"), PREF.node("core"));
                from.node("core").removeNode();
                copyNode(from.node("plugin"), PREF.node("plugin"));
                from.node("plugin").removeNode();
                copyNode(from.node("extensions"), PREF.node("extensions"));
                from.node("extensions").removeNode();
                copyNode(from.node("dbupgrader"), PREF.node("dbupgrader"));
                from.node("dbupgrader").removeNode();
            } catch (Exception e) {
                log.error("Failed to migrate preferences.", e);
            }
            try {
                from.flush();
            } catch (BackingStoreException bse) {
                log.error("Failed to flush old preferences");
            }
            try {
                PREF.flush();
            } catch (BackingStoreException bse) {
                log.error("Failed to flush new preferences");
            }
            if (log.isInfoEnabled()) {
                log.info("Flushing preferences");
            }

        }
    } catch (BackingStoreException bse) {
        log.error("Failed to migrate preferences.", bse);
    }

    // Inform the wrapper the startup process is going ok
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }

    try {
        clearTemp();
        try {
            hostname = Inet4Address.getLocalHost().getCanonicalHostName();
            hostAddress = Inet4Address.getLocalHost().getHostAddress();
        } catch (Exception ex) {
            // This should be fatal, we now rely on the hostname being
            // available
            throw new Exception("The host name or address on which this service is running could not "
                    + "be determined. Check you network configuration. One possible cause is "
                    + "a misconfigured 'hosts' file (e.g. on UNIX-like systems this would be "
                    + "/etc/hosts, on Windows XP it would be "
                    + "C:\\Windows\\System32\\Drivers\\Etc\\Hosts).");
        }

        PropertyClassManager.getInstance()
                .registerPropertyClass(contextConfiguration = new ContextConfig(getClass().getClassLoader()));

        // Display some information about the system we are running on
        displaySystemInfo();

        // Load the context property definitions
        loadContextProperties();

        // Inform the wrapper the startup process is going ok
        if (useWrapper) {
            WrapperManager.signalStarting(60000);
        }

        // Configure any HTTP / HTTPS / SOCKS proxy servers
        configureProxyServers();

        PropertyList l = contextConfiguration.retrievePropertyList(new ContextKey("webServer.bindAddress"));
        getBootProgressMonitor().updateMessage("Creating server lock");
        getBootProgressMonitor().updateProgress(6);
        serverLock = new ServerLock((String) l.get(0));
        if (serverLock.isLocked()) {
            if (!isSetupMode()) {
                if (serverLock.isSetup()) {
                    throw new Exception("The installation wizard is currently running. "
                            + "Please shut this down by pointing your browser " + "to http://" + getHostname()
                            + ":" + serverLock.getPort()
                            + "/showShutdown.do before attempting to start the server again.");
                } else {
                    throw new Exception("The server is already running.");
                }
            } else {
                if (!serverLock.isSetup()) {
                    throw new Exception("The server is currently already running. "
                            + "Please shut this down by pointing your browser " + "to https://" + getHostname()
                            + ":" + serverLock.getPort()
                            + "/showShutdown.do before attempting to start the server again.");
                } else {
                    throw new Exception("The installation wizard is running..");
                }

            }

        }

        // Inform the wrapper the startup process is going ok
        if (useWrapper) {
            WrapperManager.signalStarting(60000);
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                serverLock.stop();
            }
        });

        //
        registerKeyStores();

        //
        threadGroup = new ThreadGroup("MainThreadGroup");

        if (install) {
            setupMode();

        } else {
            normalMode();
            startHttpServer();
        }
    } catch (Throwable t) {
        startupException = t;
        log.error("Failed to start the server. " + t.getMessage(), t);
        return new Integer(1);
    }

    return null;
}

From source file:com.sslexplorer.server.Main.java

public Integer start(String[] args) {
    startupStarted = System.currentTimeMillis();

    // Inform the wrapper the startup process may take a while
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }/*from   w w w.ja  va2 s . c o  m*/

    // Parse the command line
    Integer returnCode = parseCommandLine(args);
    if (returnCode != null) {
        if (returnCode.intValue() == 999) {
            return null;
        }
        return returnCode;
    }

    // Create the boot progress monitor
    if (gui) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        bootProgressMonitor = new SwingBootProgressMonitor();
    } else {
        bootProgressMonitor = new LogBootProgressMonitor();
    }

    //
    resourceCaches = new HashMap<URL, ResourceCache>();
    contextListeners = new ArrayList<ContextListener>();

    loadSystemProperties();
    initialiseLogging();

    /*
     * Migrate preferences.
     */
    File newPrefDir = new File(ContextHolder.getContext().getConfDirectory(), "prefs");
    PREF = PropertyPreferences.SYSTEM_ROOT;
    try {
        if (!newPrefDir.exists() && Preferences.systemRoot().node("/com").nodeExists("sslexplorer")) {
            Preferences from = Preferences.systemRoot().node("/com/sslexplorer");
            log.warn("Migrating preferences");
            try {
                copyNode(from.node("core"), PREF.node("core"));
                from.node("core").removeNode();
                copyNode(from.node("plugin"), PREF.node("plugin"));
                from.node("plugin").removeNode();
                copyNode(from.node("extensions"), PREF.node("extensions"));
                from.node("extensions").removeNode();
                copyNode(from.node("dbupgrader"), PREF.node("dbupgrader"));
                from.node("dbupgrader").removeNode();
            } catch (Exception e) {
                log.error("Failed to migrate preferences.", e);
            }
            try {
                from.flush();
            } catch (BackingStoreException bse) {
                log.error("Failed to flush old preferences");
            }
            try {
                PREF.flush();
            } catch (BackingStoreException bse) {
                log.error("Failed to flush new preferences");
            }
            if (log.isInfoEnabled()) {
                log.info("Flushing preferences");
            }

        }
    } catch (BackingStoreException bse) {
        log.error("Failed to migrate preferences.", bse);
    }

    // Inform the wrapper the startup process is going ok
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }

    try {
        clearTemp();
        try {
            hostname = Inet4Address.getLocalHost().getCanonicalHostName();
            hostAddress = Inet4Address.getLocalHost().getHostAddress();
        } catch (Exception ex) {
            // This should be fatal, we now rely on the hostname being
            // available
            throw new Exception("The host name or address on which this service is running could not "
                    + "be determined. Check you network configuration. One possible cause is "
                    + "a misconfigured 'hosts' file (e.g. on UNIX-like systems this would be "
                    + "/etc/hosts, on Windows XP it would be "
                    + "C:\\Windows\\System32\\Drivers\\Etc\\Hosts).");
        }

        PropertyClassManager.getInstance()
                .registerPropertyClass(contextConfiguration = new ContextConfig(getClass().getClassLoader()));

        // Display some information about the system we are running on
        displaySystemInfo();

        // Load the context property definitions
        loadContextProperties();

        // Inform the wrapper the startup process is going ok
        if (useWrapper) {
            WrapperManager.signalStarting(60000);
        }

        // Configure any HTTP / HTTPS / SOCKS proxy servers
        configureProxyServers();

        PropertyList l = contextConfiguration.retrievePropertyList(new ContextKey("webServer.bindAddress"));
        getBootProgressMonitor().updateMessage("Creating server lock");
        getBootProgressMonitor().updateProgress(6);
        serverLock = new ServerLock((String) l.get(0));
        if (serverLock.isLocked()) {
            if (!isSetupMode()) {
                if (serverLock.isSetup()) {
                    throw new Exception("The installation wizard is currently running. "
                            + "Please shut this down by pointing your browser " + "to http://" + getHostname()
                            + ":" + serverLock.getPort()
                            + "/showShutdown.do before attempting to start the server again.");
                } else {
                    throw new Exception("The server is already running.");
                }
            } else {
                if (!serverLock.isSetup()) {
                    throw new Exception("The server is currently already running. "
                            + "Please shut this down by pointing your browser " + "to https://" + getHostname()
                            + ":" + serverLock.getPort()
                            + "/showShutdown.do before attempting to start the server again.");
                } else {
                    throw new Exception("The installation wizard is running..");
                }

            }

        }

        // Inform the wrapper the startup process is going ok
        if (useWrapper) {
            WrapperManager.signalStarting(60000);
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                serverLock.stop();
            }
        });

        //
        registerKeyStores();

        //
        threadGroup = new ThreadGroup("MainThreadGroup");

        if (install) {
            setupMode();

        } else {
            normalMode();
            startHttpServer();
        }
    } catch (Throwable t) {
        startupException = t;
        log.error("Failed to start the server. " + t.getMessage(), t);
        return new Integer(1);
    }

    return null;
}

From source file:org.rhq.server.control.command.AbstractInstall.java

private void configureAgent(File agentBasedir, CommandLine commandLine) throws Exception {
    // If the user provided us with an agent config file, we will use it.
    // Otherwise, we are going to use the out-of-box agent config file.
    ///*from  ww w.ja v a  2  s. com*/
    // Because we want to accept all defaults and consider the agent fully configured, we need to set
    //    rhq.agent.configuration-setup-flag=true
    // This tells the agent not to ask any setup questions at startup.
    // We do this whether using a custom config file or the default config file - this is because
    // we cannot allow the agent to ask the setup questions (rhqctl doesn't support that).
    //
    // Note that agent preferences found in the config file can be overridden with
    // the AGENT_PREFERENCE settings (you can set more than one).
    try {
        File agentConfDir = new File(agentBasedir, "conf");
        File agentConfigFile = new File(agentConfDir, "agent-configuration.xml");

        if (commandLine.hasOption(AGENT_CONFIG_OPTION)) {
            log.info("Configuring the RHQ agent with custom configuration file: "
                    + commandLine.getOptionValue(AGENT_CONFIG_OPTION));
            replaceAgentConfigIfNecessary(commandLine);
        } else {
            log.info("Configuring the RHQ agent with default configuration file: " + agentConfigFile);
        }

        // we require our agent preference node to be the user node called "default"
        Preferences preferencesNode = getAgentPreferences();

        // read the comments in AgentMain.loadConfigurationFile(String) to know why we do all of this
        String securityToken = preferencesNode.get(PREF_RHQ_AGENT_SECURITY_TOKEN, null);
        ByteArrayOutputStream rawConfigFileData = new ByteArrayOutputStream();
        StreamUtil.copy(new FileInputStream(agentConfigFile), rawConfigFileData, true);
        String newConfig = rawConfigFileData.toString().replace("${rhq.agent.preferences-node}", "default");
        ByteArrayInputStream newConfigInputStream = new ByteArrayInputStream(newConfig.getBytes());
        Preferences.importPreferences(newConfigInputStream);
        if (securityToken != null) {
            preferencesNode.put(PREF_RHQ_AGENT_SECURITY_TOKEN, securityToken);
        }

        // get the configured server endpoint information and tell the agent so it knows where the server is.
        Properties serverEndpoint = getAgentServerEndpoint();
        String endpointTransport = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_TRANSPORT);
        String endpointAddress = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_BINDADDRESS);
        String endpointPort = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_BINDPORT);
        String endpointParams = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_TRANSPORTPARAMS);
        if (endpointTransport != null) {
            preferencesNode.put(PREF_RHQ_AGENT_SERVER_TRANSPORT, endpointTransport);
        }
        if (endpointAddress != null) {
            preferencesNode.put(PREF_RHQ_AGENT_SERVER_BINDADDRESS, endpointAddress);
        }
        if (endpointPort != null) {
            preferencesNode.put(PREF_RHQ_AGENT_SERVER_BINDPORT, endpointPort);
        }
        if (endpointParams != null) {
            preferencesNode.put(PREF_RHQ_AGENT_SERVER_TRANSPORTPARAMS, endpointParams);
        }

        // if the user provided any overrides to the agent config, use them.
        overrideAgentPreferences(commandLine, preferencesNode);

        // set some prefs that must be a specific value
        // - do not tell this agent to auto-update itself - this agent must be managed by rhqctl only
        // - set the config setup flag to true to prohibit the agent from asking setup questions at startup
        String agentUpdateEnabledPref = PREF_RHQ_AGENT_AUTO_UPDATE_FLAG;
        preferencesNode.putBoolean(agentUpdateEnabledPref, false);
        String setupPref = PREF_RHQ_AGENT_CONFIGURATION_SETUP_FLAG;
        preferencesNode.putBoolean(setupPref, true);

        try {
            preferencesNode.flush();
            preferencesNode.sync();
        } catch (BackingStoreException bse) {
            log.error("Failed to store agent preferences, for Linux systems we require writable user.home ["
                    + System.getProperty("user.home")
                    + "]. You can also set different location for agent preferences by setting \"-Djava.util.prefs.userRoot=/some/path/\""
                    + " java system property. You may need to put this property to RHQ_CONTROL_ADDIDIONAL_JAVA_OPTS and RHQ_AGENT_ADDIDIONAL_JAVA_OPTS env variables.");
            throw bse;
        }

        log.info("Finished configuring the agent");
    } catch (Exception e) {
        log.error("An error occurred while configuring the agent: " + e.getMessage());
        throw e;
    }
}