Example usage for java.util.prefs Preferences getByteArray

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

Introduction

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

Prototype

public abstract byte[] getByteArray(String key, byte[] def);

Source Link

Document

Returns the byte array value represented by the string associated with the specified key in this preference node.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(Main.class);

    // Preference key name
    final String PREF_NAME = "name_of_preference";

    // Save/*from w w  w . j  a v a2  s.  c  o  m*/
    prefs.put(PREF_NAME, "a string"); // String
    prefs.putBoolean(PREF_NAME, true); // boolean
    prefs.putInt(PREF_NAME, 123); // int
    prefs.putLong(PREF_NAME, 123L); // long
    prefs.putFloat(PREF_NAME, 12.3F); // float
    prefs.putDouble(PREF_NAME, 12.3); // double
    byte[] bytes = new byte[1024];
    prefs.putByteArray(PREF_NAME, bytes); // byte[]

    // Retrieve
    String s = prefs.get(PREF_NAME, "a string"); // String
    boolean b = prefs.getBoolean(PREF_NAME, true); // boolean
    int i = prefs.getInt(PREF_NAME, 123); // int
    long l = prefs.getLong(PREF_NAME, 123L); // long
    float f = prefs.getFloat(PREF_NAME, 12.3F); // float
    double d = prefs.getDouble(PREF_NAME, 12.3); // double
    bytes = prefs.getByteArray(PREF_NAME, bytes); // byte[]
}

From source file:de.scoopgmbh.copper.monitoring.client.context.ApplicationContext.java

public ApplicationContext() {
    mainStackPane = new StackPane();
    mainPane = new BorderPane();
    mainPane.setId("background");//important for css
    mainStackPane.getChildren().add(mainPane);
    messageProvider = new MessageProvider(ResourceBundle.getBundle("de.scoopgmbh.copper.gui.message"));

    final Preferences prefs = Preferences.userRoot().node("de.scoopgmbh.coppermonitor");

    SettingsModel defaultSettings = new SettingsModel();
    AuditralColorMapping newItem = new AuditralColorMapping();
    newItem.color.setValue(Color.rgb(255, 128, 128));
    newItem.loglevelRegEx.setValue("1");
    defaultSettings.auditralColorMappings.add(newItem);
    byte[] defaultModelbytes;
    ByteArrayOutputStream os = null;
    try {// ww  w  . j  av a 2s  .  c  o m
        os = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(os);
        o.writeObject(defaultSettings);
        defaultModelbytes = os.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    settingsModelSingleton = defaultSettings;
    ByteArrayInputStream is = null;
    try {
        is = new ByteArrayInputStream(prefs.getByteArray(SETTINGS_KEY, defaultModelbytes));
        ObjectInputStream o = new ObjectInputStream(is);
        Object object = o.readObject();
        if (object instanceof SettingsModel) {
            settingsModelSingleton = (SettingsModel) object;
        }
    } catch (Exception e) {
        logger.error("", e);
        getIssueReporterSingleton()
                .reportWarning("Can't load settings from (Preferences: " + prefs + ") use defaults instead", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            ByteArrayOutputStream os = null;
            try {
                os = new ByteArrayOutputStream();
                ObjectOutputStream o = new ObjectOutputStream(os);
                o.writeObject(settingsModelSingleton);
                prefs.putByteArray(SETTINGS_KEY, os.toByteArray());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }));
}

From source file:edu.umd.cs.findbugs.gui2.GUISaveState.java

public static void loadInstance() {
    GUISaveState newInstance = new GUISaveState();
    newInstance.recentFiles = new ArrayList<File>();
    Preferences p = Preferences.userNodeForPackage(GUISaveState.class);

    newInstance.tabSize = p.getInt(TAB_SIZE, 4);

    newInstance.fontSize = p.getFloat(FONT_SIZE, 12.0f);

    newInstance.starterDirectoryForLoadBugs = new File(
            p.get(GUISaveState.STARTERDIRECTORY, SystemProperties.getProperty("user.dir")));

    int prevCommentsSize = p.getInt(GUISaveState.PREVCOMMENTSSIZE, 0);

    for (int x = 0; x < prevCommentsSize; x++) {
        String comment = p.get(GUISaveState.COMMENTKEYS[x], "");
        newInstance.previousComments.add(comment);
    }/*from   ww w  .j av a2s  .  com*/

    int size = Math.min(MAXNUMRECENTPROJECTS, p.getInt(GUISaveState.NUMPROJECTS, 0));
    for (int x = 0; x < size; x++) {
        newInstance.addRecentFile(new File(p.get(GUISaveState.RECENTPROJECTKEYS[x], "")));
    }

    int sorterSize = p.getInt(GUISaveState.SORTERTABLELENGTH, -1);
    if (sorterSize != -1) {
        ArrayList<Sortables> sortColumns = new ArrayList<Sortables>();
        String[] sortKeys = GUISaveState.generateSorterKeys(sorterSize);
        for (int x = 0; x < sorterSize; x++) {
            Sortables s = Sortables.getSortableByPrettyName(p.get(sortKeys[x], "*none*"));

            if (s == null) {
                if (MainFrame.GUI2_DEBUG) {
                    System.err.println("Sort order was corrupted, using default sort order");
                }
                newInstance.useDefault = true;
                break;
            }
            sortColumns.add(s);
        }
        if (!newInstance.useDefault) {
            // add in default columns
            Set<Sortables> missingSortColumns = new HashSet<Sortables>(Arrays.asList(DEFAULT_COLUMN_HEADERS));
            missingSortColumns.removeAll(sortColumns);
            sortColumns.addAll(missingSortColumns);
            newInstance.sortColumns = sortColumns.toArray(new Sortables[sortColumns.size()]);
        }
    } else {
        newInstance.useDefault = true;
    }

    newInstance.dockingLayout = p.getByteArray(DOCKINGLAYOUT, new byte[0]);

    String boundsString = p.get(FRAME_BOUNDS, null);
    Rectangle r = new Rectangle(0, 0, 800, 650);
    if (boundsString != null) {
        String[] a = boundsString.split(",", 4);
        if (a.length > 0) {
            try {
                r.x = Math.max(0, Integer.parseInt(a[0]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
        if (a.length > 1) {
            try {
                r.y = Math.max(0, Integer.parseInt(a[1]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
        if (a.length > 2) {
            try {
                r.width = Math.max(40, Integer.parseInt(a[2]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
        if (a.length > 3) {
            try {
                r.height = Math.max(40, Integer.parseInt(a[3]));
            } catch (NumberFormatException nfe) {
                assert true;
            }
        }
    }
    newInstance.frameBounds = r;
    newInstance.extendedWindowState = p.getInt(EXTENDED_WINDOW_STATE, Frame.NORMAL);

    newInstance.splitMain = p.getInt(SPLIT_MAIN, 400);
    newInstance.splitSummary = p.getInt(SPLIT_SUMMARY_NEW, 400);
    newInstance.splitTop = p.getInt(SPLIT_TOP, -1);
    newInstance.splitTreeComments = p.getInt(SPLIT_TREE_COMMENTS, 250);
    newInstance.packagePrefixSegments = p.getInt(PACKAGE_PREFIX_SEGEMENTS, 3);

    String plugins = p.get(CUSTOM_PLUGINS, "");
    if (plugins.length() > 0) {
        for (String s : plugins.split(" ")) {
            try {
                URI u = new URI(s);
                Plugin.addCustomPlugin(u);
                newInstance.customPlugins.add(u);
            } catch (PluginException e) {
                assert true;
            } catch (URISyntaxException e) {
                assert true;
            }
        }
    }

    String enabledPluginsString = p.get(ENABLED_PLUGINS, "");
    String disabledPluginsString = p.get(DISABLED_PLUGINS, "");
    newInstance.enabledPlugins = new ArrayList<String>(Arrays.asList(enabledPluginsString.split(",")));
    newInstance.disabledPlugins = new ArrayList<String>(Arrays.asList(disabledPluginsString.split(",")));

    instance = newInstance;
}

From source file:org.apache.pdfbox.pdmodel.font.FileSystemFontProvider.java

private List<FSFontInfo> loadCache(List<File> files) {
    // Get the preferences database for this package.
    Preferences prefs = Preferences.userNodeForPackage(FileSystemFontProvider.class);
    List<FSFontInfo> results = new ArrayList<FSFontInfo>();
    for (File file : files) {
        // The second argument is the default if the key isn't found.
        byte[] stored = prefs.getByteArray(file.getAbsolutePath(), null);
        if (stored != null) {
            try {
                ByteArrayInputStream byteIn = new ByteArrayInputStream(stored);
                ObjectInputStream objectIn = new ObjectInputStream(byteIn);
                Object object = objectIn.readObject();
                if (object instanceof FSFontInfo) {
                    FSFontInfo info = (FSFontInfo) object;
                    info.parent = this;
                    results.add(info);//www .j  a v  a2  s  .c  om
                }
            } catch (ClassNotFoundException e) {
                LOG.error("Error loading font cache, will be re-built", e);
                return null;
            } catch (IOException e) {
                LOG.error("Error loading font cache, will be re-built", e);
                return null;
            }
        } else {
            // re-build the entire cache if we encounter un-cached fonts (could be optimised)
            LOG.warn("New fonts found, font cache will be re-built");
            return null;
        }
    }
    return results;
}

From source file:org.netbeans.jcode.util.PreferenceUtils.java

public static <T> T get(Preferences pref, Class<T> _class) {
    T newInstance = null;/*from ww w  .  jav  a2s  .  c om*/
    //        ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
    try {
        //            Thread.currentThread().setContextClassLoader(_class.getClassLoader());
        newInstance = _class.newInstance();
        return (T) PreferenceUtils.deserialize(
                pref.getByteArray(_class.getName(), PreferenceUtils.serialize((Serializable) newInstance)),
                _class.getClassLoader());
    } catch (InvalidClassException ex) {
        return newInstance;
    } catch (InstantiationException | IllegalAccessException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        //            Thread.currentThread().setContextClassLoader(ctxLoader);
    }
    return null;
}