Example usage for java.util.prefs Preferences userNodeForPackage

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

Introduction

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

Prototype

public static Preferences userNodeForPackage(Class<?> c) 

Source Link

Document

Returns the preference node from the calling user's preference tree that is associated (by convention) with the specified class's package.

Usage

From source file:PreferencesDemo.java

public static void main(String[] args) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(PreferencesDemo.class);
    prefs.put("Location", "Oz");
    prefs.put("Footwear", "Ruby Slippers");
    prefs.putInt("Companions", 4);
    prefs.putBoolean("Are there witches?", true);
    int usageCount = prefs.getInt("UsageCount", 0);
    usageCount++;/*w  w w  .  j a  va  2s .c om*/
    prefs.putInt("UsageCount", usageCount);
    Iterator it = Arrays.asList(prefs.keys()).iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        System.out.println(key + ": " + prefs.get(key, null));
    }
    // You must always provide a default value:
    System.out.println("How many companions does Dorothy have? " + prefs.getInt("Companions", 0));
}

From source file:PreferenceExample.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");

    System.out.println("userNodeForPackage: " + Preferences.userNodeForPackage(PreferenceExample.class));

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    // System preference nodes

    // Use a Class
    Preferences prefs = Preferences.systemNodeForPackage(java.lang.String.class);

    // Use an absolute path
    prefs = Preferences.systemRoot().node("/java/lang/String");

    // Use a relative path
    prefs = Preferences.systemRoot().node("/javax/swing");
    prefs = prefs.node("text/html");

    // User preference nodes

    // Use a class
    prefs = Preferences.userNodeForPackage(Main.class);

    // Use an absolute path
    prefs = Preferences.userRoot().node("/com/mycompany");

    // Use a relative path
    prefs = Preferences.userRoot().node("/javax/swing");
    prefs = prefs.node("text/html");
}

From source file:gridrover.GridRover.java

/**
* This method does the work of getting our application started.
*
* @param args Command line arguments//w  w  w . j a  v  a 2 s .co m
*/
public static void main(String[] args) {
    System.out.println("GridRover Copyright (C) 2008-2009 Lucas Adam M. Paul");
    System.out.println("This program comes with ABSOLUTELY NO WARRANTY; for details see LICENSE.TXT.");
    System.out.println("This is free software, and you are welcome to redistribute it");
    System.out.println("under certain conditions; see LICENSE.TXT for details.\n");

    log.info("Loading preferences...");
    Preferences prefs = Preferences.userNodeForPackage(GridRover.class);
    int width = prefs.getInt(MAP_WIDTH, 10);
    int length = prefs.getInt(MAP_HEIGHT, 10);
    double maxElevation = prefs.getDouble(MAX_ELEVATION, 25.0);
    int precision = prefs.getInt(ELEVATION_PRECISION, 2);

    log.info("Loading data files...");

    XmlFileParser fileParser = new XmlFileParser(new ResourceLocater(null));
    List<Spectrum> spectra = fileParser.getSpectra("spectrum_types.xml");
    log.debug("Checking we got our spectra.");
    for (Spectrum spec : spectra) {
        log.debug("Type: " + spec.getName());
        List<String> list = spec.getColors();
        for (String color : list)
            log.debug("\tColor: " + color);
        list = spec.getShapes();
        for (String shape : list)
            log.debug("\tShape: " + shape);
    }
    //List<Thing> itemPrototypes = fileParser.getThings("physical_objects.xml");
    List<ThingBean> itemPrototypes = fileParser.getThings("physical_objects.xml", spectra);
    log.debug("Checking we got our Things.");
    for (ThingBean tb : itemPrototypes) {
        log.debug("Name: " + tb.getName());
        log.debug("Mass: " + tb.getMinMass() + " - " + tb.getMaxMass());
        log.debug("Density: " + tb.getMinDensity() + " - " + tb.getMaxDensity());
        List<AppearanceBean> appearance = tb.getAppearanceBeans();
        for (AppearanceBean ab : appearance) {
            log.debug("Under the " + ab.getStimulus() + " spectrum, " + tb.getName() + " reacts with:");
            List<ResponseBean> responses = ab.getResponseBeans();
            for (ResponseBean rb : responses) {
                log.debug(rb.getSpectrumAction().toString() + " " + rb.getColor() + " " + rb.getShape()
                        + " in spectrum " + rb.getSpectrum());
            }
        }
    }

    log.info("Initializing GridRover...");
    GameEngine engine = new GameEngine(width, length, maxElevation, precision);
    Rover rover = new Rover("Rover", 185.0, 5.52, 100.0, new CommandlineRoverControl()); // Mass 185.0 kg, 1.5 meters tall by 2.3 meters wide by 1.6 meters long
    engine.addRover(rover, width / 2, length / 2); // Add a single rover in the middle of the map
    engine.addAmbientLighting(spectra.get(0));
    engine.scatterItemsRandomly(itemPrototypes, 0.5, 5); // 50% chance of items in a given square, up to 5 items per square

    log.info("Running GridRover...");
    engine.eventLoop();
    System.out.println("All events completed.  GridRover now terminating.");
}

From source file:net.zdechov.sharpmz.jmzemu.JMzEmu.java

/**
 * Main method launching the application.
 *
 * @param args arguments/*w w  w . ja  v  a 2  s . c  o m*/
 */
public static void main(String[] args) {

    try {
        preferences = Preferences.userNodeForPackage(JMzEmu.class);
    } catch (SecurityException ex) {
        preferences = null;
    }
    try {
        bundle = LanguageUtils.getResourceBundleByClass(JMzEmu.class);
        // Parameters processing
        Options opt = new Options();
        opt.addOption("h", "help", false, bundle.getString("cl_option_help"));
        opt.addOption("v", false, bundle.getString("cl_option_verbose"));
        opt.addOption("dev", false, bundle.getString("cl_option_dev"));
        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opt, args);
        if (cl.hasOption('h')) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp(bundle.getString("cl_syntax"), opt);
        } else {
            verboseMode = cl.hasOption("v");
            devMode = cl.hasOption("dev");
            Logger logger = Logger.getLogger("");
            try {
                logger.setLevel(Level.ALL);
                logger.addHandler(new XBHead.XBLogHandler(verboseMode));
            } catch (java.security.AccessControlException ex) {
                // Ignore it in java webstart
            }

            XBBaseApplication app = new XBBaseApplication();
            app.setAppPreferences(new PreferencesWrapper(preferences));
            app.setAppBundle(bundle, LanguageUtils.getResourceBaseNameBundleByClass(JMzEmu.class));

            XBApplicationModuleRepository moduleRepository = app.getModuleRepository();
            moduleRepository.addClassPathModules();
            moduleRepository.addModulesFromManifest(JMzEmu.class);
            moduleRepository.loadModulesFromPath(new File("plugins").toURI());
            moduleRepository.initModules();
            app.init();

            GuiFrameModuleApi frameModule = moduleRepository.getModuleByInterface(GuiFrameModuleApi.class);
            GuiEditorModuleApi editorModule = moduleRepository.getModuleByInterface(GuiEditorModuleApi.class);
            GuiMenuModuleApi menuModule = moduleRepository.getModuleByInterface(GuiMenuModuleApi.class);
            GuiAboutModuleApi aboutModule = moduleRepository.getModuleByInterface(GuiAboutModuleApi.class);
            GuiFileModuleApi fileModule = moduleRepository.getModuleByInterface(GuiFileModuleApi.class);
            GuiOptionsModuleApi optionsModule = moduleRepository
                    .getModuleByInterface(GuiOptionsModuleApi.class);
            GuiUpdateModuleApi updateModule = moduleRepository.getModuleByInterface(GuiUpdateModuleApi.class);
            frameModule.createMainMenu();

            //                try {
            //                    updateModule.setUpdateUrl(new URL(bundle.getString("update_url")));
            //                    updateModule.setUpdateDownloadUrl(new URL(bundle.getString("update_download_url")));
            //                } catch (MalformedURLException ex) {
            //                    Logger.getLogger(JMzEmu.class.getName()).log(Level.SEVERE, null, ex);
            //                }
            updateModule.registerDefaultMenuItem();
            aboutModule.registerDefaultMenuItem();
            AboutDialogSidePanel sidePanel = new AboutDialogSidePanel();
            aboutModule.setAboutDialogSideComponent(sidePanel);

            frameModule.registerExitAction();
            frameModule.registerBarsVisibilityActions();

            // Register clipboard editing actions
            fileModule.registerMenuFileHandlingActions();
            fileModule.registerToolBarFileHandlingActions();
            fileModule.registerLastOpenedMenuActions();
            fileModule.registerCloseListener();

            //                undoModule.registerMainMenu();
            //                undoModule.registerMainToolBar();
            //                undoModule.registerUndoManagerInMainMenu();
            // Register clipboard editing actions
            menuModule.getClipboardActions();
            //                menuModule.registerMenuClipboardActions();
            //                menuModule.registerToolBarClipboardActions();
            optionsModule.registerMenuAction();

            //                HexPanel hexPanel = (HexPanel) deltaHexModule.getEditorProvider();
            //                editorModule.registerEditor("hex", hexPanel);
            //                editorModule.registerUndoHandler();
            //                undoModule.setUndoHandler(hexPanel.getHexUndoHandler());
            //                deltaHexModule.registerStatusBar();
            //                deltaHexModule.registerOptionsPanels();
            //                deltaHexModule.getTextStatusPanel();
            updateModule.registerOptionsPanels();

            //                deltaHexModule.loadFromPreferences(preferences);
            ApplicationFrameHandler frameHandler = frameModule.getFrameHandler();
            GraphicsModule graphicsModule = new GraphicsModule();
            frameHandler.setMainPanel(graphicsModule.getGraphicsComponent());
            frameHandler.setDefaultSize(new Dimension(600, 400));
            frameHandler.show();
            updateModule.checkOnStart(frameHandler.getFrame());

            List fileArgs = cl.getArgList();
            if (fileArgs.size() > 0) {
                fileModule.loadFromFile((String) fileArgs.get(0));
            }
        }
    } catch (ParseException | RuntimeException ex) {
        Logger.getLogger(JMzEmu.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.exbin.deltahex.editor.DeltaHexEditor.java

/**
 * Main method launching the application.
 *
 * @param args arguments//from   www . j a v a 2 s.  co m
 */
public static void main(String[] args) {
    try {
        preferences = Preferences.userNodeForPackage(DeltaHexEditor.class);
    } catch (SecurityException ex) {
        preferences = null;
    }
    try {
        bundle = LanguageUtils.getResourceBundleByClass(DeltaHexEditor.class);
        // Parameters processing
        Options opt = new Options();
        opt.addOption("h", "help", false, bundle.getString("cl_option_help"));
        opt.addOption("v", false, bundle.getString("cl_option_verbose"));
        opt.addOption("dev", false, bundle.getString("cl_option_dev"));
        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opt, args);
        if (cl.hasOption('h')) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp(bundle.getString("cl_syntax"), opt);
        } else {
            verboseMode = cl.hasOption("v");
            devMode = cl.hasOption("dev");
            Logger logger = Logger.getLogger("");
            try {
                logger.setLevel(Level.ALL);
                logger.addHandler(new XBHead.XBLogHandler(verboseMode));
            } catch (java.security.AccessControlException ex) {
                // Ignore it in java webstart
            }

            XBBaseApplication app = new XBBaseApplication();
            app.setAppPreferences(preferences);
            app.setAppBundle(bundle, LanguageUtils.getResourceBaseNameBundleByClass(DeltaHexEditor.class));

            XBApplicationModuleRepository moduleRepository = app.getModuleRepository();
            moduleRepository.addClassPathModules();
            moduleRepository.addModulesFromManifest(DeltaHexEditor.class);
            moduleRepository.loadModulesFromPath(new File("plugins").toURI());
            moduleRepository.initModules();
            app.init();

            GuiFrameModuleApi frameModule = moduleRepository.getModuleByInterface(GuiFrameModuleApi.class);
            GuiEditorModuleApi editorModule = moduleRepository.getModuleByInterface(GuiEditorModuleApi.class);
            GuiMenuModuleApi menuModule = moduleRepository.getModuleByInterface(GuiMenuModuleApi.class);
            GuiAboutModuleApi aboutModule = moduleRepository.getModuleByInterface(GuiAboutModuleApi.class);
            GuiUndoModuleApi undoModule = moduleRepository.getModuleByInterface(GuiUndoModuleApi.class);
            GuiFileModuleApi fileModule = moduleRepository.getModuleByInterface(GuiFileModuleApi.class);
            GuiOptionsModuleApi optionsModule = moduleRepository
                    .getModuleByInterface(GuiOptionsModuleApi.class);
            GuiDockingModuleApi dockingModule = moduleRepository
                    .getModuleByInterface(GuiDockingModuleApi.class);
            GuiUpdateModuleApi updateModule = moduleRepository.getModuleByInterface(GuiUpdateModuleApi.class);

            DeltaHexModule deltaHexModule = moduleRepository.getModuleByInterface(DeltaHexModule.class);

            frameModule.createMainMenu();
            try {
                updateModule.setUpdateUrl(new URL(bundle.getString("update_url")));
                updateModule.setUpdateDownloadUrl(new URL(bundle.getString("update_download_url")));
            } catch (MalformedURLException ex) {
                Logger.getLogger(DeltaHexEditor.class.getName()).log(Level.SEVERE, null, ex);
            }
            updateModule.registerDefaultMenuItem();
            aboutModule.registerDefaultMenuItem();

            frameModule.registerExitAction();
            frameModule.registerBarsVisibilityActions();
            //                Component dockingPanel = dockingModule.getDockingPanel();

            // Register clipboard editing actions
            fileModule.registerMenuFileHandlingActions();
            fileModule.registerToolBarFileHandlingActions();
            fileModule.registerLastOpenedMenuActions();
            fileModule.registerCloseListener();

            undoModule.registerMainMenu();
            undoModule.registerMainToolBar();
            undoModule.registerUndoManagerInMainMenu();

            // Register clipboard editing actions
            menuModule.registerMenuClipboardActions();
            menuModule.registerToolBarClipboardActions();

            optionsModule.registerMenuAction();

            //                HexEditorProvider editorProvider = deltaHexModule.getMultiEditorProvider();
            HexEditorProvider editorProvider = deltaHexModule.getEditorProvider();
            deltaHexModule.registerEditFindMenuActions();
            deltaHexModule.registerEditFindToolBarActions();
            deltaHexModule.registerViewNonprintablesMenuActions();
            deltaHexModule.registerToolsOptionsMenuActions();
            deltaHexModule.registerClipboardCodeActions();
            deltaHexModule.registerOptionsMenuPanels();
            deltaHexModule.registerGoToLine();
            deltaHexModule.registerPropertiesMenu();
            deltaHexModule.registerPrintMenu();
            deltaHexModule.registerViewModeMenu();
            deltaHexModule.registerCodeTypeMenu();
            deltaHexModule.registerPositionCodeTypeMenu();
            deltaHexModule.registerHexCharactersCaseHandlerMenu();
            deltaHexModule.registerWordWrapping();

            ApplicationFrameHandler frameHandler = frameModule.getFrameHandler();
            editorModule.registerEditor("hex", editorProvider);
            // editorModule.registerMultiEditor("hex", (MultiEditorProvider) editorProvider);
            editorModule.registerUndoHandler();
            undoModule.setUndoHandler(editorProvider.getHexUndoHandler());

            deltaHexModule.registerStatusBar();
            deltaHexModule.registerOptionsPanels();
            deltaHexModule.getTextStatusPanel();
            updateModule.registerOptionsPanels();

            deltaHexModule.loadFromPreferences(preferences);

            //                frameHandler.setMainPanel(dockingPanel);
            // Single editor only
            frameHandler.setMainPanel(editorModule.getEditorPanel());
            frameHandler.setDefaultSize(new Dimension(600, 400));
            frameHandler.show();
            updateModule.checkOnStart(frameHandler.getFrame());

            List fileArgs = cl.getArgList();
            if (fileArgs.size() > 0) {
                fileModule.loadFromFile((String) fileArgs.get(0));
            }
        }
    } catch (ParseException | RuntimeException ex) {
        Logger.getLogger(DeltaHexEditor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:PrefsUtil.java

public static void main(String[] args) {
    try {//w  ww  .  jav  a2 s .c  o  m
        Map map = new HashMap();
        map.put("0", "A");
        map.put("1", "B");
        map.put("2", "C");
        map.put("3", "D");
        map.put("5", "f");

        Preferences prefs = Preferences.userNodeForPackage(String.class);

        String RECENT_FILES = "XXX";

        List recentFiles = PrefsUtil.getList(prefs, RECENT_FILES);
        PrefsUtil.clear(prefs, RECENT_FILES);

        PrefsUtil.putList(prefs, recentFiles, RECENT_FILES);

        //System.out.println( PrefsUtil.getList( prefs, RECENT_FILES ) );

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.diversityarrays.dal.server.DalServer.java

public static void main(String[] args) {

    String host = null;/* ww  w  . j  av a2s.  co  m*/
    int port = DalServerUtil.DEFAULT_DAL_SERVER_PORT;

    int inactiveMins = DalServerUtil.DEFAULT_MAX_INACTIVE_MINUTES;

    File docRoot = null;

    String serviceName = null;

    for (int i = 0; i < args.length; ++i) {
        String argi = args[i];
        if (argi.startsWith("-")) {
            if ("--".equals(argi)) {
                break;
            }

            if ("-version".equals(argi)) {
                System.out.println(DAL_SERVER_VERSION);
                System.exit(0);
            }

            if ("-help".equals(argi)) {
                giveHelpThenExit(0);
            }

            if ("-docroot".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                docRoot = new File(args[i]);
            } else if ("-sqllog".equals(argi)) {
                SqlUtil.logger = Logger.getLogger(SqlUtil.class.getName());
            } else if ("-expire".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }

                try {
                    inactiveMins = Integer.parseInt(args[i], 10);
                    if (inactiveMins <= 0) {
                        fatal("invalid minutes: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid minutes: " + args[i]);
                }
            } else if ("-localhost".equals(argi)) {
                host = "localhost";
            } else if ("-port".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                try {
                    port = Integer.parseInt(args[i], 10);
                    if (port < 0 || port > 65535) {
                        fatal("invalid port number: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid port number: " + args[i]);
                }
            } else {
                fatal("invalid option: " + argi);
            }
        } else {
            if (serviceName != null) {
                fatal("multiple serviceNames not supported: " + argi);
            }
            serviceName = argi;
        }
    }

    final DalServerPreferences preferences = new DalServerPreferences(
            Preferences.userNodeForPackage(DalServer.class));

    if (docRoot == null) {
        docRoot = preferences.getWebRoot(new File(System.getProperty("user.dir"), "www"));
    }

    DalServer server = null;

    if (serviceName != null && docRoot.isDirectory()) {
        try {
            DalDatabase db = createDalDatabase(serviceName, preferences);
            if (db.isInitialiseRequired()) {
                Closure<String> progress = new Closure<String>() {
                    @Override
                    public void execute(String msg) {
                        System.out.println("Database Initialisation: " + msg);
                    }
                };
                db.initialise(progress);
            }
            server = create(preferences, host, port, docRoot, db);
        } catch (NoServiceException e) {
            throw new RuntimeException(e);
        } catch (DalDbException e) {
            throw new RuntimeException(e);
        }
    }

    Image serverIconImage = null;
    InputStream imageIs = DalServer.class.getResourceAsStream("dalserver-24.png");
    if (imageIs != null) {
        try {
            serverIconImage = ImageIO.read(imageIs);

            if (Util.isMacOS()) {
                try {
                    MacApplication macapp = new MacApplication(null);
                    macapp.setDockIconImage(serverIconImage);
                } catch (MacApplicationException e) {
                    System.err.println(e.getMessage());
                }
            }

        } catch (IOException ignore) {
        }
    }

    if (server != null) {
        server.setMaxInactiveMinutes(inactiveMins);
    } else {
        AskServerParams asker = new AskServerParams(serverIconImage, null, "DAL Server Start", docRoot,
                preferences);
        GuiUtil.centreOnScreen(asker);
        asker.setVisible(true);

        if (asker.cancelled) {
            System.exit(0);
        }

        host = asker.dalServerHostName;
        port = asker.dalServerPort;
        inactiveMins = asker.maxInactiveMinutes;

        server = create(preferences, host, port, asker.wwwRoot, asker.dalDatabase);
        // server.setUseSimpleDatabase(asker.useSimpleDatabase);
    }

    final DalServer f_server = server;
    final File f_wwwRoot = docRoot;
    final Image f_serverIconImage = serverIconImage;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            DalServerFactory factory = new DalServerFactory() {
                @Override
                public DalServer create(String hostName, int port, File wwwRoot, DalDatabase dalDatabase) {
                    return DalServer.create(preferences, hostName, port, wwwRoot, dalDatabase);
                }
            };
            ServerGui gui = new ServerGui(f_serverIconImage, f_server, factory, f_wwwRoot, preferences);
            gui.setVisible(true);
        }
    });

}

From source file:Main.java

public Main() {
    userPrefs = Preferences.userNodeForPackage(Main.class);

    System.out.println(userPrefs.get(NAMEPREF, ""));
    System.out.println(userPrefs.get(EMAILPREF, ""));

    userPrefs.put(NAMEPREF, "name");
    userPrefs.put(EMAILPREF, "email");
    Preferences.userNodeForPackage(Main.class).addPreferenceChangeListener(this);
}

From source file:LookAndFeelPrefs.java

/**
 * Get the desired look and feel from a per-user preference. If the
 * preferences doesn't exist or is unavailable, use the default look and feel.
 * The preference is shared by all classes in the same package as prefsClass.
 *//*from w w  w.  j av  a  2  s.c o m*/
public static void setPreferredLookAndFeel(Class prefsClass) {
    Preferences prefs = Preferences.userNodeForPackage(prefsClass);
    String defaultLAF = UIManager.getSystemLookAndFeelClassName();
    String laf = prefs.get(PREF_NAME, defaultLAF);
    try {
        UIManager.setLookAndFeel(laf);
    } catch (Exception e) { // ClassNotFound or InstantiationException
        // An exception here is probably caused by a bogus preference.
        // Ignore it silently; the user will make do with the default LAF.
    }
}