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:au.org.ala.delta.intkey.ui.UIUtils.java

/**
 * Save the parent directory for the most recently opened dataset to
 * preferences/*  w ww . j  ava 2  s.  c  om*/
 * 
 * @param lastOpenedDatasetDirectory
 */
public static void saveLastOpenedDatasetDirectory(File lastOpenedDatasetDirectory) {
    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);
    prefs.put(LAST_OPENED_DATASET_LOCATION_PREF_KEY, lastOpenedDatasetDirectory.getAbsolutePath());
    try {
        prefs.sync();
    } catch (BackingStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mirth.connect.client.ui.components.rsta.MirthRSyntaxTextArea.java

public static void updateFindReplacePreferences() {
    updateFindReplacePreferences(Preferences.userNodeForPackage(Mirth.class));
}

From source file:com.mirth.connect.client.ui.components.rsta.MirthRSyntaxTextArea.java

public static void updateToggleOptionPreferences() {
    updateToggleOptionPreferences(Preferences.userNodeForPackage(Mirth.class));
}

From source file:com.concursive.connect.config.ApplicationPrefs.java

/**
 * Description of the Method//from   ww w  . j av  a  2s.  c o m
 *
 * @param context Description of the Parameter
 * @return Description of the Return Value
 */
private String retrieveFileLibraryLocation(ServletContext context) {
    String dir = ApplicationPrefs.getRealPath(context);
    try {
        if (dir == null) {
            dir = node;
        }
        // Read from Preferences
        LOG.info("Java preferences key: " + dir);
        Preferences javaPrefs = Preferences.userNodeForPackage(ApplicationPrefs.class);
        // Check "dir" prefs first, based on the installed directory of this webapp
        String fileLibrary = null;
        if (dir.length() <= Preferences.MAX_KEY_LENGTH) {
            fileLibrary = javaPrefs.get(dir, null);
        } else {
            fileLibrary = javaPrefs.get(dir.substring(dir.length() - Preferences.MAX_KEY_LENGTH), null);
        }
        boolean doSave = false;
        // Preferences not found
        if (fileLibrary == null) {
            // Check in the current dir of the webapp for a pointer to the properties
            // NOTE: Some containers return null for getRealPath()
            String realPath = ApplicationPrefs.getRealPath(context);
            if (realPath != null) {
                fileLibrary = realPath + "WEB-INF" + fs + "fileLibrary" + fs;
                doSave = true;
            }
        }
        // See if properties exist
        if (fileLibrary != null) {
            File propertyFile = new File(fileLibrary + "build.properties");
            if (propertyFile.exists()) {
                if (doSave) {
                    saveFileLibraryLocation(dir, fileLibrary);
                }
                return fileLibrary;
            }
        }
    } catch (Exception e) {
        LOG.error("ApplicationPrefs", e);
        e.printStackTrace(System.out);
    }
    return null;
}

From source file:au.org.ala.delta.intkey.ui.UIUtils.java

/**
 * Gets the dataset index from preferences
 * //from www.  j av a2 s  .com
 * @return The dataset index - a list of dataset description, dataset path
 *         value pairs
 */
public static List<Pair<String, String>> readDatasetIndex() {
    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);

    List<Pair<String, String>> indexList = new ArrayList<Pair<String, String>>();

    if (prefs != null) {
        String datasetIndexJSON = prefs.get(DATASET_INDEX_PREF_KEY, "");
        if (!StringUtils.isEmpty(datasetIndexJSON)) {
            List<List<String>> deserializedJSON = (List<List<String>>) JSONSerializer
                    .toJava(JSONArray.fromObject(datasetIndexJSON));
            for (List<String> datasetInfoList : deserializedJSON) {
                indexList.add(new Pair<String, String>(datasetInfoList.get(0), datasetInfoList.get(1)));
            }
        }
    }

    return indexList;
}

From source file:com.mirth.connect.client.ui.components.rsta.MirthRSyntaxTextArea.java

public static void updateAutoCompletePreferences() {
    updateAutoCompletePreferences(Preferences.userNodeForPackage(Mirth.class));
}

From source file:com.mirth.connect.connectors.ws.WebServiceSender.java

public void setHeaderProperties(Map<String, List<String>> properties) {
    int size = 0;
    for (List<String> list : properties.values()) {
        size += list.size();// w ww . j a va2  s  . c o m
    }

    Object[][] tableData = new Object[size][2];

    headersTable = new MirthTable();

    int j = 0;
    Iterator i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        for (String keyValue : (List<String>) entry.getValue()) {
            tableData[j][NAME_COLUMN] = (String) entry.getKey();
            tableData[j][VALUE_COLUMN] = keyValue;
            j++;
        }
    }

    headersTable.setModel(new javax.swing.table.DefaultTableModel(tableData,
            new String[] { NAME_COLUMN_NAME, VALUE_COLUMN_NAME }) {

        boolean[] canEdit = new boolean[] { true, true };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }
    });

    headersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent evt) {
            if (getSelectedRow(headersTable) != -1) {
                headerLastIndex = getSelectedRow(headersTable);
                headersDeleteButton.setEnabled(true);
            } else {
                headersDeleteButton.setEnabled(false);
            }
        }
    });

    class WebServiceTableCellEditor extends TextFieldCellEditor {
        boolean checkProperties;

        public WebServiceTableCellEditor(boolean checkProperties) {
            super();
            this.checkProperties = checkProperties;
        }

        @Override
        public boolean isCellEditable(EventObject evt) {
            boolean editable = super.isCellEditable(evt);

            if (editable) {
                headersDeleteButton.setEnabled(false);
            }

            return editable;
        }

        @Override
        protected boolean valueChanged(String value) {
            headersDeleteButton.setEnabled(true);

            if (checkProperties && (value.length() == 0)) {
                return false;
            }

            parent.setSaveEnabled(true);
            return true;
        }
    }

    headersTable.getColumnModel().getColumn(headersTable.getColumnModel().getColumnIndex(NAME_COLUMN_NAME))
            .setCellEditor(new WebServiceTableCellEditor(true));
    headersTable.getColumnModel().getColumn(headersTable.getColumnModel().getColumnIndex(VALUE_COLUMN_NAME))
            .setCellEditor(new WebServiceTableCellEditor(false));
    headersTable.setCustomEditorControls(true);

    headersTable.setSelectionMode(0);
    headersTable.setRowSelectionAllowed(true);
    headersTable.setRowHeight(UIConstants.ROW_HEIGHT);
    headersTable.setDragEnabled(false);
    headersTable.setOpaque(true);
    headersTable.setSortable(false);
    headersTable.getTableHeader().setReorderingAllowed(false);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        headersTable.setHighlighters(highlighter);
    }

    headersPane.setViewportView(headersTable);
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Starts controller with a special config file, and creates and starts all
 * components of PowerFolder./*from   www  .  j a v  a  2  s .c o  m*/
 *
 * @param filename
 *            The filename to uses as config file (located in the
 *            "getConfigLocationBase()")
 */
public void startConfig(String filename) {
    if (started) {
        throw new IllegalStateException("Configuration already started, shutdown controller first");
    }

    additionalConnectionListeners = Collections.synchronizedList(new ArrayList<ConnectionListener>());
    started = false;
    shuttingDown = false;
    threadPool = new WrappedScheduledThreadPoolExecutor(Constants.CONTROLLER_THREADS_IN_THREADPOOL,
            new NamedThreadFactory("Controller-Thread-"));

    // Initialize resource bundle eager
    // check forced language file from commandline
    if (commandLine != null && commandLine.hasOption("f")) {
        String langfilename = commandLine.getOptionValue("f");
        try {
            ResourceBundle resourceBundle = new ForcedLanguageFileResourceBundle(langfilename);
            Translation.setResourceBundle(resourceBundle);
            logInfo("Loading language bundle from file " + langfilename);
        } catch (FileNotFoundException fnfe) {
            logSevere("forced language file (" + langfilename + ") not found: " + fnfe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        } catch (IOException ioe) {
            logSevere("forced language file io error: " + ioe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        }
    } else {
        Translation.resetResourceBundle();
    }
    Translation.getResourceBundle();

    // loadConfigFile
    if (!loadConfigFile(filename)) {
        return;
    }

    boolean isDefaultConfig = Constants.DEFAULT_CONFIG_FILE.startsWith(getConfigName());
    if (isDefaultConfig) {
        // To keep compatible with previous versions
        preferences = Preferences.userNodeForPackage(PowerFolder.class);
    } else {
        preferences = Preferences.userNodeForPackage(PowerFolder.class).node(getConfigName());

    }

    // initialize logger
    // Enabled verbose mode if in config.
    // This logs to file for analysis.
    verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
    initLogger();

    if (verbose) {
        ByteSerializer.BENCHMARK = true;
        scheduleAndRepeat(new Runnable() {
            @Override
            public void run() {
                ByteSerializer.printStats();
            }
        }, 600000L, 600000L);
        Profiling.setEnabled(false);
        Profiling.reset();
    }

    String arch = OSUtil.is64BitPlatform() ? "64bit" : "32bit";
    logFine("OS: " + System.getProperty("os.name") + " (" + arch + ')');
    logFine("Java: " + JavaVersion.systemVersion().toString() + " (" + System.getProperty("java.vendor") + ')');
    logFine("Current time: " + new Date());
    Runtime runtime = Runtime.getRuntime();
    long maxMemory = runtime.maxMemory();
    long totalMemory = runtime.totalMemory();
    logFine("Max Memory: " + Format.formatBytesShort(maxMemory) + ", Total Memory: "
            + Format.formatBytesShort(totalMemory));
    if (!Desktop.isDesktopSupported() && isUIEnabled()) {
        logWarning("Desktop utility not supported");
    }

    // If we have a new config. clear the preferences.
    clearPreferencesOnConfigSwitch();

    // Load and set http proxy settings
    HTTPProxySettings.loadFromConfig(this);

    // #2179: Load from server. How to handle timeouts?
    // Command line option -c http://are.de
    ConfigurationLoader.loadAndMergeCLI(this);
    // Config entry in file
    ConfigurationLoader.loadAndMergeConfigURL(this);
    // Read from installer temp file
    ConfigurationLoader.loadAndMergeFromInstaller(this);

    if (verbose != ConfigurationEntry.VERBOSE.getValueBoolean(this)) {
        verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
        initLogger();
    }

    // Init paused only if user expects pause to be permanent or
    // "while I work"
    int pauseSecs = ConfigurationEntry.PAUSE_RESUME_SECONDS.getValueInt(getController());
    paused = PreferencesEntry.PAUSED.getValueBoolean(this)
            && (pauseSecs == Integer.MAX_VALUE || pauseSecs == 0);

    // Now set it, just in case it was paused in permanent mode.
    PreferencesEntry.PAUSED.setValue(this, paused);

    // Load and set http proxy settings again.
    HTTPProxySettings.loadFromConfig(this);

    // Initialize branding/preconfiguration of the client
    initDistribution();
    logFine("Build time: " + getBuildTime());
    logInfo("Program version " + PROGRAM_VERSION);

    if (getDistribution().getBinaryName().toLowerCase().contains("powerfolder")) {
        Debug.writeSystemProperties();
    }

    if (ConfigurationEntry.KILL_RUNNING_INSTANCE.getValueBoolean(this)) {
        killRunningInstance();
    }
    FolderList.removeMemberFiles(this);

    // Initialize plugins
    setupProPlugins();
    pluginManager = new PluginManager(this);
    pluginManager.init();

    // create node manager
    nodeManager = new NodeManager(this);

    // Only one task brother left...
    taskManager = new PersistentTaskManager(this);

    // Folder repository
    folderRepository = new FolderRepository(this);
    setLoadingCompletion(0, 10);

    // Create transfer manager
    // If this is a unit test it might have been set before.
    try {
        transferManager = transferManagerFactory.call();
    } catch (Exception e) {
        logSevere("Exception", e);
    }

    reconnectManager = new ReconnectManager(this);
    // Create os client
    osClient = new ServerClient(this);

    if (isUIEnabled()) {
        uiController = new UIController(this);
        if (ConfigurationEntry.USER_INTERFACE_LOCKED.getValueBoolean(this)) {
            // Don't let the user pass this step.
            new UIUnLockDialog(this).openAndWait();
        }
    }

    setLoadingCompletion(10, 20);

    // The io provider.
    ioProvider = new IOProvider(this);
    ioProvider.start();

    // Set hostname by CLI
    if (commandLine != null && commandLine.hasOption('d')) {
        String host = commandLine.getOptionValue("d");
        if (StringUtils.isNotBlank(host)) {
            InetSocketAddress addr = Util.parseConnectionString(host);
            if (addr != null) {
                ConfigurationEntry.HOSTNAME.setValue(this, addr.getHostName());
                ConfigurationEntry.NET_BIND_PORT.setValue(this, addr.getPort());
            }
        }
    }

    // initialize dyndns manager
    dyndnsManager = new DynDnsManager(this);

    setLoadingCompletion(20, 30);

    // initialize listener on local port
    if (!initializeListenerOnLocalPort()) {
        return;
    }
    if (!isUIEnabled()) {
        // Disable paused function
        paused = false;
    }

    setLoadingCompletion(30, 35);

    // Start the nodemanager
    nodeManager.init();
    if (!ProUtil.isRunningProVersion()) {
        // Nodemanager gets later (re) started by ProLoader.
        nodeManager.start();
    }

    setLoadingCompletion(35, 60);
    securityManager = new SecurityManagerClient(this, osClient);

    // init repo (read folders)
    folderRepository.init();
    logInfo("Dataitems: " + Debug.countDataitems(Controller.this));
    // init of folders takes rather long so a big difference with
    // last number to get smooth bar... ;-)
    setLoadingCompletion(60, 65);

    // start repo maintainance Thread
    folderRepository.start();
    setLoadingCompletion(65, 70);

    // Start the transfer manager thread
    transferManager.start();
    setLoadingCompletion(70, 75);

    // Initalize rcon manager
    startRConManager();

    setLoadingCompletion(75, 80);

    // Start all configured listener if not in paused mode
    startConfiguredListener();
    setLoadingCompletion(80, 85);

    // open broadcast listener
    openBroadcastManager();
    setLoadingCompletion(85, 90);

    // Controller now started
    started = true;
    startTime = new Date();

    // Now taskmanager
    taskManager.start();

    logInfo("Controller started");

    // dyndns updater
    /*
     * boolean onStartUpdate = ConfigurationEntry.DYNDNS_AUTO_UPDATE
     * .getValueBoolean(this).booleanValue(); if (onStartUpdate) {
     * getDynDnsManager().onStartUpdate(); }
     */
    dyndnsManager.updateIfNessesary();

    setLoadingCompletion(90, 100);

    // Login to OS
    if (Feature.OS_CLIENT.isEnabled()) {
        try {
            osClient.loginWithLastKnown();
        } catch (Exception e) {
            logWarning("Unable to login with last known username. " + e);
            logFiner(e);
        }
    }

    // Start Plugins
    pluginManager.start();

    // open UI
    if (isConsoleMode()) {
        logFine("Running in console");
    } else {
        logFine("Opening UI");
        openUI();
    }

    // Load anything that was not handled last time.
    loadPersistentObjects();

    setLoadingCompletion(100, 100);
    if (!isConsoleMode()) {
        uiController.hideSplash();
    }

    if (ConfigurationEntry.AUTO_CONNECT.getValueBoolean(this)) {
        // Now start the connecting process
        reconnectManager.start();
    } else {
        logFine("Not starting reconnection process. " + "Config auto.connect set to false");
    }
    // Start connecting to OS client.
    if (Feature.OS_CLIENT.isEnabled() && ConfigurationEntry.SERVER_CONNECT.getValueBoolean(this)) {
        osClient.start();
    } else {
        logInfo("Not connecting to server (" + osClient.getServerString() + "): Disabled");
    }

    // Setup our background working tasks
    setupPeriodicalTasks();

    if (MacUtils.isSupported()) {
        if (isFirstStart()) {
            MacUtils.getInstance().setPFStartup(true, this);
        }
        MacUtils.getInstance().setAppReOpenedListener(this);
    }

    if (pauseSecs == 0) {
        // Activate adaptive logic
        setPaused(paused);
    }
}

From source file:corelyzer.ui.CorelyzerApp.java

public void pingLaunchTracker() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            // load or create unique user ID
            Preferences sysPrefs = Preferences.userNodeForPackage(CorelyzerApp.class);
            String uuid = sysPrefs.get("uuid", null);
            if (uuid == null) {
                uuid = java.util.UUID.randomUUID().toString();
                sysPrefs.put("uuid", uuid);
            }/*  ww w  .j  a va2 s  . co  m*/

            // track launch
            GoogleAnalytics ga = new GoogleAnalytics("UA-88247383-1");
            GoogleAnalyticsResponse response = ga
                    .post(new PageViewHit("http://www.laccore.org", "launch: UUID=" + uuid));
            //            for (NameValuePair kvp : response.getPostedParms()) {
            //               System.out.println("key: " + kvp.getName() + ", value: "+ kvp.getValue());
            //            }
        }
    });
}

From source file:com.mirth.connect.client.ui.SettingsPanelResources.java

private void initComponents() {
    setLayout(new MigLayout("insets 12, novisualpadding, hidemode 3, fill"));
    setBackground(UIConstants.BACKGROUND_COLOR);

    JPanel resourceListPanel = new JPanel(new MigLayout("insets 0, novisualpadding, hidemode 3, fill"));
    resourceListPanel.setBackground(getBackground());
    resourceListPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(204, 204, 204)), "Resources",
            TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", 1, 11)));

    resourceTable = new MirthTable();
    resourceTable.setModel(/*from w ww . j a  v  a 2 s.  co  m*/
            new RefreshTableModel(new Object[] { "Properties", "Name", "Type", "Global Scripts" }, 0) {
                @Override
                public boolean isCellEditable(int row, int column) {
                    if (row == 0) {
                        return column == GLOBAL_SCRIPTS_COLUMN;
                    } else {
                        return column == NAME_COLUMN || column == TYPE_COLUMN
                                || column == GLOBAL_SCRIPTS_COLUMN;
                    }
                }
            });
    resourceTable.setDragEnabled(false);
    resourceTable.setRowSelectionAllowed(true);
    resourceTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    resourceTable.setRowHeight(UIConstants.ROW_HEIGHT);
    resourceTable.setFocusable(true);
    resourceTable.setOpaque(true);
    resourceTable.getTableHeader().setReorderingAllowed(false);
    resourceTable.setEditable(true);
    resourceTable.setSortable(false);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        resourceTable.setHighlighters(HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR));
    }

    for (ResourceClientPlugin plugin : LoadedExtensions.getInstance().getResourceClientPlugins().values()) {
        propertiesPanelMap.put(plugin.getType(), plugin.getPropertiesPanel());
    }

    resourceTable.getColumnModel().getColumn(NAME_COLUMN).setCellEditor(new NameEditor());
    resourceTable.getColumnExt(NAME_COLUMN).setToolTipText("The unique name of the resource.");

    resourceTable.getColumnModel().getColumn(TYPE_COLUMN).setMinWidth(100);
    resourceTable.getColumnModel().getColumn(TYPE_COLUMN).setMaxWidth(200);
    resourceTable.getColumnModel().getColumn(TYPE_COLUMN)
            .setCellRenderer(new ComboBoxRenderer(propertiesPanelMap.keySet().toArray()));
    resourceTable.getColumnModel().getColumn(TYPE_COLUMN).setCellEditor(new ComboBoxEditor(resourceTable,
            propertiesPanelMap.keySet().toArray(), 1, true, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    typeComboBoxActionPerformed(evt);
                }
            }));
    resourceTable.getColumnExt(TYPE_COLUMN).setToolTipText("The type of resource.");

    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setMinWidth(80);
    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setMaxWidth(80);
    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setCellRenderer(new CheckBoxRenderer());
    resourceTable.getColumnModel().getColumn(GLOBAL_SCRIPTS_COLUMN).setCellEditor(new CheckBoxEditor());
    resourceTable.getColumnExt(GLOBAL_SCRIPTS_COLUMN).setToolTipText(
            "<html>If checked, libraries associated with the corresponding<br/>resource will be included in global script contexts.</html>");

    resourceTable.removeColumn(resourceTable.getColumnModel().getColumn(PROPERTIES_COLUMN));

    resourceTable.getSelectionModel().addListSelectionListener(this);

    resourceTable
            .setToolTipText("<html>Add or remove resources to use<br/>in specific channels/connectors.</html>");

    resourceTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "selectNextColumnCell");

    resourceListPanel.add(new JScrollPane(resourceTable), "grow, push");

    add(resourceListPanel, "grow, h 20%");

    for (ResourcePropertiesPanel panel : propertiesPanelMap.values()) {
        add(panel, "newline, grow, h 80%");
    }

    fillerPanel = new JPanel(new MigLayout("insets 5, novisualpadding, hidemode 3, fill", "", "[][grow]"));
    fillerPanel.setBackground(getBackground());
    fillerPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(204, 204, 204)), "Resource Settings",
            TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", 1, 11)));
    fillerLabel = new JLabel("Select a resource from the table above.");
    fillerPanel.add(fillerLabel);

    exceptionTextPane = new JTextPane();
    exceptionTextPane.setBackground(new Color(224, 223, 227));
    exceptionTextPane.setEditable(false);
    exceptionScrollPane = new JScrollPane(exceptionTextPane);
    fillerPanel.add(exceptionScrollPane, "newline, grow");

    add(fillerPanel, "newline, grow, h 80%");
}