Example usage for java.util.prefs Preferences sync

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

Introduction

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

Prototype

public abstract void sync() throws BackingStoreException;

Source Link

Document

Ensures that future reads from this preference node and its descendants reflect any changes that were committed to the persistent store (from any VM) prior to the sync invocation.

Usage

From source file:com.delcyon.capo.Configuration.java

@SuppressWarnings({ "unchecked", "static-access" })
public Configuration(String... programArgs) throws Exception {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();

    options = new Options();
    // the enum this is a little complicated, but it gives us a nice
    // centralized place to put all of the system parameters
    // and lets us iterate of the list of options and preferences
    PREFERENCE[] preferences = PREFERENCE.values();
    for (PREFERENCE preference : preferences) {
        // not the most elegant, but there is no default constructor, but
        // the has arguments value is always there
        OptionBuilder optionBuilder = OptionBuilder.hasArg(preference.hasArgument);
        if (preference.hasArgument == true) {
            String[] argNames = preference.arguments;
            for (String argName : argNames) {
                optionBuilder = optionBuilder.withArgName(argName);
            }/* ww w.j a  v a2 s .c om*/
        }

        optionBuilder = optionBuilder.withDescription(preference.getDescription());
        optionBuilder = optionBuilder.withLongOpt(preference.getLongOption());
        options.addOption(optionBuilder.create(preference.getOption()));

        preferenceHashMap.put(preference.toString(), preference);
    }

    //add dynamic options

    Set<String> preferenceProvidersSet = CapoApplication.getAnnotationMap()
            .get(PreferenceProvider.class.getCanonicalName());
    if (preferenceProvidersSet != null) {
        for (String className : preferenceProvidersSet) {
            Class preferenceClass = Class.forName(className).getAnnotation(PreferenceProvider.class)
                    .preferences();
            if (preferenceClass.isEnum()) {
                Object[] enumObjects = preferenceClass.getEnumConstants();
                for (Object enumObject : enumObjects) {

                    Preference preference = (Preference) enumObject;
                    //filter out any preferences that don't belong on this server or client.
                    if (preference.getLocation() != Location.BOTH) {
                        if (CapoApplication.isServer() == true && preference.getLocation() == Location.CLIENT) {
                            continue;
                        } else if (CapoApplication.isServer() == false
                                && preference.getLocation() == Location.SERVER) {
                            continue;
                        }
                    }
                    preferenceHashMap.put(preference.toString(), preference);
                    boolean hasArgument = false;
                    if (preference.getArguments() == null || preference.getArguments().length == 0) {
                        hasArgument = false;
                    } else {
                        hasArgument = true;
                    }

                    OptionBuilder optionBuilder = OptionBuilder.hasArg(hasArgument);
                    if (hasArgument == true) {
                        String[] argNames = preference.getArguments();
                        for (String argName : argNames) {
                            optionBuilder = optionBuilder.withArgName(argName);
                        }
                    }

                    optionBuilder = optionBuilder.withDescription(preference.getDescription());
                    optionBuilder = optionBuilder.withLongOpt(preference.getLongOption());
                    options.addOption(optionBuilder.create(preference.getOption()));
                }

            }
        }
    }

    // create parser
    CommandLineParser commandLineParser = new GnuParser();
    this.commandLine = commandLineParser.parse(options, programArgs);

    Preferences systemPreferences = Preferences
            .systemNodeForPackage(CapoApplication.getApplication().getClass());
    String capoDirString = null;
    while (true) {
        capoDirString = systemPreferences.get(PREFERENCE.CAPO_DIR.longOption, null);
        if (capoDirString == null) {

            systemPreferences.put(PREFERENCE.CAPO_DIR.longOption, PREFERENCE.CAPO_DIR.defaultValue);
            capoDirString = PREFERENCE.CAPO_DIR.defaultValue;
            try {
                systemPreferences.sync();
            } catch (BackingStoreException e) {
                //e.printStackTrace();            
                if (systemPreferences.isUserNode() == false) {
                    System.err.println("Problem with System preferences, trying user's");
                    systemPreferences = Preferences
                            .userNodeForPackage(CapoApplication.getApplication().getClass());
                    continue;
                } else //just bail out
                {
                    throw e;
                }

            }
        }
        break;
    }

    disableAutoSync = hasOption(PREFERENCE.DISABLE_CONFIG_AUTOSYNC);

    File capoDirFile = new File(capoDirString);
    if (capoDirFile.exists() == false) {
        if (disableAutoSync == false) {
            capoDirFile.mkdirs();
        }
    }
    File configDir = new File(capoDirFile, PREFERENCE.CONFIG_DIR.defaultValue);
    if (configDir.exists() == false) {
        if (disableAutoSync == false) {
            configDir.mkdirs();
        }
    }

    if (disableAutoSync == false) {
        capoConfigFile = new File(configDir, CONFIG_FILENAME);
        if (capoConfigFile.exists() == false) {

            Document configDocument = CapoApplication.getDefaultDocument("config.xml");

            FileOutputStream configFileOutputStream = new FileOutputStream(capoConfigFile);
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(new DOMSource(configDocument), new StreamResult(configFileOutputStream));
            configFileOutputStream.close();
        }

        configDocument = documentBuilder.parse(capoConfigFile);
    } else //going memory only, because of disabled auto sync
    {
        configDocument = CapoApplication.getDefaultDocument("config.xml");
    }
    if (configDocument instanceof CDocument) {
        ((CDocument) configDocument).setSilenceEvents(true);
    }
    loadPreferences();
    preferenceValueHashMap.put(PREFERENCE.CAPO_DIR.longOption, capoDirString);
    //print out preferences
    //this also has the effect of persisting all of the default values if a values doesn't already exist
    for (PREFERENCE preference : preferences) {
        if (getValue(preference) != null) {
            CapoApplication.logger.log(Level.CONFIG, preference.longOption + "='" + getValue(preference) + "'");
        }
    }

    CapoApplication.logger.setLevel(Level.parse(getValue(PREFERENCE.LOGGING_LEVEL)));
}

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   w w  w.jav a  2  s .c o m
    // 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;
    }
}