Example usage for java.util.prefs Preferences put

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

Introduction

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

Prototype

public abstract void put(String key, String value);

Source Link

Document

Associates the specified value with the specified key in this preference node.

Usage

From source file:org.openmicroscopy.shoola.util.ui.UIUtilities.java

/**
 * Sets the pathname string of the default folder.
 * //from   w  w  w .j a v  a  2 s.  c o  m
 * @param f The value to set.
 */
public static void setDefaultFolder(String f) {
    Preferences prefs = Preferences.userNodeForPackage(UIUtilities.class);
    if (prefs == null)
        return;
    if (f == null)
        f = "";
    prefs.put(DEFAULT_FOLDER, f);
}

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

private void overrideAgentPreferences(CommandLine commandLine, Preferences preferencesNode) {
    // override the out of box config with user custom agent preference values
    String[] customPrefs = commandLine.getOptionValues(AGENT_PREFERENCE);
    if (customPrefs != null && customPrefs.length > 0) {
        for (String nameValuePairString : customPrefs) {
            String[] nameValuePairArray = nameValuePairString.split("=", 2);
            String prefName = nameValuePairArray[0];
            String prefValue = nameValuePairArray.length == 1 ? "true" : nameValuePairArray[1];
            log.info("Overriding agent preference: " + prefName + "=" + prefValue);
            preferencesNode.put(prefName, prefValue);
        }/*from w ww  .j av  a 2s  . co  m*/
    }
    return;
}

From source file:de._692b8c32.cdlauncher.MainController.java

public MainController(Application application, Preferences preferences) {
    this.application = application;
    this.preferences = preferences;

    if (preferences.get("basedir", null) == null) {
        while (new OptionsController(application, preferences).selectDirectory() == null) {
            new Alert(Alert.AlertType.ERROR,
                    "The launcher needs a directory to store temporary files. Press cancel if you want to close the application.",
                    ButtonType.CANCEL, ButtonType.PREVIOUS).showAndWait().ifPresent(button -> {
                        if (button == ButtonType.CANCEL) {
                            throw new RuntimeException("User requested abort.");
                        }//ww w. jav  a2 s .co  m
                    });
        }

        new Alert(Alert.AlertType.INFORMATION,
                "Do you want to use a prebuilt version of OpenRA? This is recommended unless you are an OpenRA developer.",
                ButtonType.NO, ButtonType.YES).showAndWait().ifPresent(button -> {
                    if (button == ButtonType.YES) {
                        preferences.putBoolean("buildFromSources", false);
                    }
                    if (button == ButtonType.NO) {
                        preferences.putBoolean("buildFromSources", true);
                    }
                });

        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            preferences.put("commandMono", "");
            preferences.put("commandMake", "");
        }
    }
}

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

void copyNode(Preferences from, Preferences to) throws BackingStoreException {
    String[] keys = from.keys();//  w w w.  ja v  a 2s.  c  o m
    for (String key : keys) {
        to.put(key, from.get(key, ""));
    }
    String childNodes[] = from.childrenNames();
    for (String childNode : childNodes) {
        Preferences cn = from.node(childNode);
        Preferences tn = to.node(childNode);
        copyNode(cn, tn);
    }
}

From source file:com.nbt.TreeFrame.java

private void createActions() {
    newAction = new NBTAction("New", "New", "New", KeyEvent.VK_N) {

        {// ww w.j a va2s .  c o  m
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('N', Event.CTRL_MASK));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            updateTreeTable(new CompoundTag(""));
        }

    };

    browseAction = new NBTAction("Browse...", "Open", "Browse...", KeyEvent.VK_O) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('O', Event.CTRL_MASK));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = createFileChooser();
            switch (fc.showOpenDialog(TreeFrame.this)) {
            case JFileChooser.APPROVE_OPTION:
                File file = fc.getSelectedFile();
                Preferences prefs = getPreferences();
                prefs.put(KEY_FILE, file.getAbsolutePath());
                doImport(file);
                break;
            }
        }

    };

    saveAction = new NBTAction("Save", "Save", "Save", KeyEvent.VK_S) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('S', Event.CTRL_MASK));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String path = textFile.getText();
            File file = new File(path);
            if (file.canWrite()) {
                doExport(file);
            } else {
                saveAsAction.actionPerformed(e);
            }
        }

    };

    saveAsAction = new NBTAction("Save As...", "SaveAs", "Save As...", KeyEvent.VK_UNDEFINED) {

        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = createFileChooser();
            switch (fc.showSaveDialog(TreeFrame.this)) {
            case JFileChooser.APPROVE_OPTION:
                File file = fc.getSelectedFile();
                Preferences prefs = getPreferences();
                prefs.put(KEY_FILE, file.getAbsolutePath());
                doExport(file);
                break;
            }
        }

    };

    refreshAction = new NBTAction("Refresh", "Refresh", "Refresh", KeyEvent.VK_F5) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("F5"));
        }

        public void actionPerformed(ActionEvent e) {
            String path = textFile.getText();
            File file = new File(path);
            if (file.canRead())
                doImport(file);
            else
                showErrorDialog("The file could not be read.");
        }

    };

    exitAction = new NBTAction("Exit", "Exit", KeyEvent.VK_ESCAPE) {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO: this should check to see if any changes have been made
            // before exiting
            System.exit(0);
        }

    };

    cutAction = new DefaultEditorKit.CutAction() {

        {
            String name = "Cut";
            putValue(NAME, name);
            putValue(SHORT_DESCRIPTION, name);
            putValue(MNEMONIC_KEY, KeyEvent.VK_X);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('X', Event.CTRL_MASK));

            ImageFactory factory = new ImageFactory();
            try {
                putValue(SMALL_ICON, new ImageIcon(factory.readGeneralImage(name, NBTAction.smallIconSize)));
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                putValue(LARGE_ICON_KEY,
                        new ImageIcon(factory.readGeneralImage(name, NBTAction.largeIconSize)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    copyAction = new DefaultEditorKit.CopyAction() {

        {
            String name = "Copy";
            putValue(NAME, name);
            putValue(SHORT_DESCRIPTION, name);
            putValue(MNEMONIC_KEY, KeyEvent.VK_C);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('C', Event.CTRL_MASK));

            ImageFactory factory = new ImageFactory();
            try {
                putValue(SMALL_ICON, new ImageIcon(factory.readGeneralImage(name, NBTAction.smallIconSize)));
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                putValue(LARGE_ICON_KEY,
                        new ImageIcon(factory.readGeneralImage(name, NBTAction.largeIconSize)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    pasteAction = new DefaultEditorKit.CutAction() {

        {
            String name = "Paste";
            putValue(NAME, name);
            putValue(SHORT_DESCRIPTION, name);
            putValue(MNEMONIC_KEY, KeyEvent.VK_V);
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('V', Event.CTRL_MASK));

            ImageFactory factory = new ImageFactory();
            try {
                putValue(SMALL_ICON, new ImageIcon(factory.readGeneralImage(name, NBTAction.smallIconSize)));
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                putValue(LARGE_ICON_KEY,
                        new ImageIcon(factory.readGeneralImage(name, NBTAction.largeIconSize)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    };

    deleteAction = new NBTAction("Delete", "Delete", "Delete", KeyEvent.VK_DELETE) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("DELETE"));
        }

        public void actionPerformed(ActionEvent e) {
            int row = treeTable.getSelectedRow();
            TreePath path = treeTable.getPathForRow(row);
            Object last = path.getLastPathComponent();

            if (last instanceof NBTFileBranch) {
                NBTFileBranch branch = (NBTFileBranch) last;
                File file = branch.getFile();
                String name = file.getName();
                String message = "Are you sure you want to delete " + name + "?";
                String title = "Continue?";
                int option = JOptionPane.showConfirmDialog(TreeFrame.this, message, title,
                        JOptionPane.OK_CANCEL_OPTION);
                switch (option) {
                case JOptionPane.CANCEL_OPTION:
                    return;
                }
                if (!FileUtils.deleteQuietly(file)) {
                    showErrorDialog(name + " could not be deleted.");
                    return;
                }
            }

            TreePath parentPath = path.getParentPath();
            Object parentLast = parentPath.getLastPathComponent();
            NBTTreeTableModel model = treeTable.getTreeTableModel();
            int index = model.getIndexOfChild(parentLast, last);
            if (parentLast instanceof Mutable<?>) {
                Mutable<?> mutable = (Mutable<?>) parentLast;
                if (last instanceof ByteWrapper) {
                    ByteWrapper wrapper = (ByteWrapper) last;
                    index = wrapper.getIndex();
                }
                mutable.remove(index);
            } else {
                System.err.println(last.getClass());
                return;
            }

            updateTreeTable();
            treeTable.expandPath(parentPath);
            scrollTo(parentLast);
            treeTable.setRowSelectionInterval(row, row);
        }

    };

    openAction = new NBTAction("Open...", "Open...", KeyEvent.VK_T) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('T', Event.CTRL_MASK));

            final int diamondPickaxe = 278;
            SpriteRecord record = NBTTreeTable.register.getRecord(diamondPickaxe);
            BufferedImage image = record.getImage();
            setSmallIcon(image);

            int width = 24, height = 24;
            Dimension size = new Dimension(width, height);
            Map<RenderingHints.Key, ?> hints = Thumbnail.createRenderingHints(Thumbnail.QUALITY);
            BufferedImage largeImage = Thumbnail.createThumbnail(image, size, hints);
            setLargeIcon(largeImage);
        }

        public void actionPerformed(ActionEvent e) {
            TreePath path = treeTable.getPath();
            if (path == null)
                return;

            Object last = path.getLastPathComponent();
            if (last instanceof Region) {
                Region region = (Region) last;
                createAndShowTileCanvas(new TileCanvas.TileWorld(region));
                return;
            } else if (last instanceof World) {
                World world = (World) last;
                createAndShowTileCanvas(world);
                return;
            }

            if (last instanceof NBTFileBranch) {
                NBTFileBranch fileBranch = (NBTFileBranch) last;
                File file = fileBranch.getFile();
                try {
                    open(file);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    showErrorDialog(ex.getMessage());
                }
            }
        }

        private void open(File file) throws IOException {
            if (Desktop.isDesktopSupported()) {
                Desktop desktop = Desktop.getDesktop();
                if (desktop.isSupported(Desktop.Action.OPEN)) {
                    desktop.open(file);
                }
            }
        }

    };

    addByteAction = new NBTAction("Add Byte", NBTConstants.TYPE_BYTE, "Add Byte", KeyEvent.VK_1) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('1', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new ByteTag("new byte", (byte) 0));
        }

    };

    addShortAction = new NBTAction("Add Short", NBTConstants.TYPE_SHORT, "Add Short", KeyEvent.VK_2) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('2', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new ShortTag("new short", (short) 0));
        }

    };

    addIntAction = new NBTAction("Add Integer", NBTConstants.TYPE_INT, "Add Integer", KeyEvent.VK_3) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('3', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new IntTag("new int", 0));
        }

    };

    addLongAction = new NBTAction("Add Long", NBTConstants.TYPE_LONG, "Add Long", KeyEvent.VK_4) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('4', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new LongTag("new long", 0));
        }

    };

    addFloatAction = new NBTAction("Add Float", NBTConstants.TYPE_FLOAT, "Add Float", KeyEvent.VK_5) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('5', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new FloatTag("new float", 0));
        }

    };

    addDoubleAction = new NBTAction("Add Double", NBTConstants.TYPE_DOUBLE, "Add Double", KeyEvent.VK_6) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('6', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new DoubleTag("new double", 0));
        }

    };

    addByteArrayAction = new NBTAction("Add Byte Array", NBTConstants.TYPE_BYTE_ARRAY, "Add Byte Array",
            KeyEvent.VK_7) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('7', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new ByteArrayTag("new byte array"));
        }

    };

    addStringAction = new NBTAction("Add String", NBTConstants.TYPE_STRING, "Add String", KeyEvent.VK_8) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('8', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new StringTag("new string", "..."));
        }

    };

    addListAction = new NBTAction("Add List Tag", NBTConstants.TYPE_LIST, "Add List Tag", KeyEvent.VK_9) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('9', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            Class<? extends Tag> type = queryType();
            if (type != null)
                addTag(new ListTag("new list", null, type));
        }

        private Class<? extends Tag> queryType() {
            Object[] items = { NBTConstants.TYPE_BYTE, NBTConstants.TYPE_SHORT, NBTConstants.TYPE_INT,
                    NBTConstants.TYPE_LONG, NBTConstants.TYPE_FLOAT, NBTConstants.TYPE_DOUBLE,
                    NBTConstants.TYPE_BYTE_ARRAY, NBTConstants.TYPE_STRING, NBTConstants.TYPE_LIST,
                    NBTConstants.TYPE_COMPOUND };
            JComboBox comboBox = new JComboBox(new DefaultComboBoxModel(items));
            comboBox.setRenderer(new DefaultListCellRenderer() {

                @Override
                public Component getListCellRendererComponent(JList list, Object value, int index,
                        boolean isSelected, boolean cellHasFocus) {
                    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

                    if (value instanceof Integer) {
                        Integer i = (Integer) value;
                        Class<? extends Tag> c = NBTUtils.getTypeClass(i);
                        String name = NBTUtils.getTypeName(c);
                        setText(name);
                    }

                    return this;
                }

            });
            Object[] message = { new JLabel("Please select a type."), comboBox };
            String title = "Title goes here";
            int result = JOptionPane.showOptionDialog(TreeFrame.this, message, title,
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
            switch (result) {
            case JOptionPane.OK_OPTION:
                ComboBoxModel model = comboBox.getModel();
                Object item = model.getSelectedItem();
                if (item instanceof Integer) {
                    Integer i = (Integer) item;
                    return NBTUtils.getTypeClass(i);
                }
            }
            return null;
        }

    };

    addCompoundAction = new NBTAction("Add Compound Tag", NBTConstants.TYPE_COMPOUND, "Add Compound Tag",
            KeyEvent.VK_0) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('0', Event.CTRL_MASK));
        }

        public void actionPerformed(ActionEvent e) {
            addTag(new CompoundTag());
        }

    };

    String name = "About " + TITLE;
    helpAction = new NBTAction(name, "Help", name, KeyEvent.VK_F1) {

        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("F1"));
        }

        public void actionPerformed(ActionEvent e) {
            Object[] message = { new JLabel(TITLE + " " + VERSION),
                    new JLabel("\u00A9 Copyright Taggart Spilman 2011.  All rights reserved."),
                    new Hyperlink("<html><a href=\"#\">NamedBinaryTag.com</a></html>",
                            "http://www.namedbinarytag.com"),
                    new Hyperlink("<html><a href=\"#\">Contact</a></html>", "mailto:tagadvance@gmail.com"),
                    new JLabel(" "),
                    new Hyperlink("<html><a href=\"#\">JNBT was written by Graham Edgecombe</a></html>",
                            "http://jnbt.sf.net"),
                    new Hyperlink("<html><a href=\"#\">Available open-source under the BSD license</a></html>",
                            "http://jnbt.sourceforge.net/LICENSE.TXT"),
                    new JLabel(" "), new JLabel("This product includes software developed by"),
                    new Hyperlink("<html><a href=\"#\">The Apache Software Foundation</a>.</html>",
                            "http://www.apache.org"),
                    new JLabel(" "), new JLabel("Default texture pack:"),
                    new Hyperlink("<html><a href=\"#\">SOLID COLOUR. SOLID STYLE.</a></html>",
                            "http://www.minecraftforum.net/topic/72253-solid-colour-solid-style/"),
                    new JLabel("Bundled with the permission of Trigger_Proximity."),

            };
            String title = "About";
            JOptionPane.showMessageDialog(TreeFrame.this, message, title, JOptionPane.INFORMATION_MESSAGE);
        }

    };

}

From source file:com.jidesoft.spring.richclient.docking.JideApplicationLifecycleAdvisor.java

@Override
public void onWindowOpened(ApplicationWindow arg0) {
    super.onWindowOpened(arg0);
    if (PreferenceRegistry.instance().getPreferenceValue("general.tipOfTheDay").equals("yes")) {
        GraphicUtils.showTipOfTheDay();/*from   www. j  av a2  s .  c om*/
    }

    // automatic version checking
    // get preference
    String pval = PreferenceRegistry.instance().getPreferenceValue("updates.autoCheckForNewVersion");
    if (pval == null || pval.equals("")) {
        // if preference is null, ask user if they want to activate version
        // checking
        //TODO:I18N
        final MessageDialog dlg = new MessageDialog("Automatic version check",
                "As of version 1.0.4 JOverseer comes with a mechanism to automatically check for new versions on the web site.\r\n Note that if you choose yes, JOverseer will try to connect to the internet every time upon start-up to check for a new version.\n Do you wish to activate this check?") {
            @Override
            protected Object[] getCommandGroupMembers() {
                return new Object[] { new ActionCommand("actionYes") {
                    @Override
                    protected void doExecuteCommand() {
                        PreferenceRegistry.instance().setPreferenceValue("updates.autoCheckForNewVersion",
                                "yes");
                        getDialog().dispose();
                    }
                }, new ActionCommand("actionNo") {
                    @Override
                    protected void doExecuteCommand() {
                        PreferenceRegistry.instance().setPreferenceValue("updates.autoCheckForNewVersion",
                                "no");
                        getDialog().dispose();
                    }
                } };
            }
        };
        dlg.showDialog();
    }
    // get preference value and do version checking if needed
    pval = PreferenceRegistry.instance().getPreferenceValue("updates.autoCheckForNewVersion");
    if (pval.equals("yes")) {
        // check once every week
        Preferences prefs = Preferences.userNodeForPackage(JOverseerJIDEClient.class);

        pval = prefs.get("lastVersionCheckDate", null);
        Date dt = null;
        try {
            dt = new SimpleDateFormat().parse(pval);
        } catch (Exception exc) {
            // do nothing
        }
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -7);
        Date dateMinusOneWeek = c.getTime();
        if (dt == null || dateMinusOneWeek.after(dt)) {

            DefaultApplicationDescriptor descriptor = (DefaultApplicationDescriptor) Application.instance()
                    .getApplicationContext().getBean("applicationDescriptor");
            ThreepartVersion current = new ThreepartVersion(descriptor.getVersion());

            try {
                if (UpdateChecker
                        .getLatestVersion(PreferenceRegistry.instance().getPreferenceValue("updates.RSSFeed"))
                        .isLaterThan(current)) {
                    new com.middleearthgames.updater.UpdateInfo(UpdateChecker
                            .getWhatsNew(PreferenceRegistry.instance().getPreferenceValue("updates.RSSFeed")));
                }
                String str = new SimpleDateFormat().format(new Date());
                prefs.put("lastVersionCheckDate", str);
            } catch (Exception exc) {
                // do nothing
            }
        }
    }
}

From source file:main.UIController.java

public Time calculateSunset(Calendar calendar, String city, String country, boolean useCacheSunset) {
    Time time = null;//from  ww  w  .  j  a  v  a 2  s. co  m
    boolean useCache = useCacheSunset;
    Preferences data = this.getCurrentPreferences();
    if (!useCache) {
        String place = this.makeLocationString(city, country);
        if (place.length() > 0) {
            GeoAddressStandardizer st = new GeoAddressStandardizer(Config.getGoogleMapsApiKey(),
                    Config.getRateLimitInterval());
            HttpClientParams params = st.getHttpClientParams();
            params.setSoTimeout(Config.getConnectionTimeout());
            st.setHttpClientParams(params);
            Location location = null;
            try {
                GeoCoordinate geo = st.standardizeToGeoCoordinate(place);
                double latitude = geo.getLatitude();
                double longitude = geo.getLongitude();
                location = new Location(Double.toString(latitude), Double.toString(longitude));
                String timezone = data.get(FIELD_TIMEZONE, DEF_TIMEZONE);
                SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, timezone);
                String sunset = calculator.getOfficialSunsetForDate(calendar) + ":00";
                data.put(FIELD_CACHE_SUNSET, sunset);
                time = Time.valueOf(sunset);
            } catch (GeoException e) {
                useCache = true;
            }
        } else {
            useCache = true;
        }
    }
    if (useCache) {
        String cacheSunset = data.get(FIELD_CACHE_SUNSET, DEF_CACHE_SUNSET);
        if (!cacheSunset.isEmpty()) {
            time = Time.valueOf(cacheSunset);
        }
    }
    return time;
}

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.
    ////  w  w  w.  j  a  va  2  s . co  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;
    }
}

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

void copyNode(Preferences from, Preferences to) throws BackingStoreException {
    String[] keys = from.keys();//from w  w  w .  ja  va 2  s .co  m
    for (int i = 0; i < keys.length; i++) {
        to.put(keys[i], from.get(keys[i], ""));
    }
    String childNodes[] = from.childrenNames();
    for (int i = 0; i < childNodes.length; i++) {
        Preferences cn = from.node(childNodes[i]);
        Preferences tn = to.node(childNodes[i]);
        copyNode(cn, tn);
    }
}

From source file:net.sf.jabref.JabRefPreferences.java

/**
 * Adds the given key pattern to the preferences
 *
 * @param pattern the pattern to store/*from ww w  . j  a  v a  2  s .  c  om*/
 */
public void putKeyPattern(GlobalLabelPattern pattern) {
    keyPattern = pattern;

    // Store overridden definitions to Preferences.
    Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class);
    try {
        pre.clear(); // We remove all old entries.
    } catch (BackingStoreException ex) {
        LOGGER.info("BackingStoreException in JabRefPreferences.putKeyPattern", ex);
    }

    Set<String> allKeys = pattern.getAllKeys();
    for (String key : allKeys) {
        if (!pattern.isDefaultValue(key)) {
            // no default value
            // the first entry in the array is the full pattern
            // see net.sf.jabref.logic.labelPattern.LabelPatternUtil.split(String)
            pre.put(key, pattern.getValue(key).get(0));
        }
    }
}