Search in sources :

Example 6 with Preferences

use of java.util.prefs.Preferences in project cryptomator by cryptomator.

the class SingleInstanceManager method getRemoteInstance.

/**
	 * Checks if there is a valid port at
	 * {@link Preferences#userNodeForPackage(Class)} for {@link Cryptomator} under the
	 * given applicationKey, tries to connect to the port at the loopback
	 * address and checks if the port identifies with the applicationKey.
	 * 
	 * @param applicationKey
	 *            key used to load the port and check the identity of the
	 *            connection.
	 * @return
	 */
public static Optional<RemoteInstance> getRemoteInstance(String applicationKey) {
    Optional<Integer> port = getSavedPort(applicationKey);
    if (!port.isPresent()) {
        return Optional.empty();
    }
    SocketChannel channel = null;
    boolean close = true;
    try {
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        LOG.debug("connecting to instance {}", port.get());
        channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), port.get()));
        SocketChannel fChannel = channel;
        if (!TimeoutTask.attempt(t -> fChannel.finishConnect(), 1000, 10)) {
            return Optional.empty();
        }
        LOG.debug("connected to instance {}", port.get());
        final byte[] bytes = applicationKey.getBytes(StandardCharsets.UTF_8);
        ByteBuffer buf = ByteBuffer.allocate(bytes.length);
        tryFill(channel, buf, 1000);
        if (buf.hasRemaining()) {
            return Optional.empty();
        }
        buf.flip();
        for (int i = 0; i < bytes.length; i++) {
            if (buf.get() != bytes[i]) {
                return Optional.empty();
            }
        }
        close = false;
        return Optional.of(new RemoteInstance(channel));
    } catch (Exception e) {
        return Optional.empty();
    } finally {
        if (close) {
            IOUtils.closeQuietly(channel);
        }
    }
}
Also used : Cryptomator(org.cryptomator.ui.Cryptomator) Selector(java.nio.channels.Selector) LoggerFactory(org.slf4j.LoggerFactory) ByteBuffer(java.nio.ByteBuffer) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet) ListenerRegistration(org.cryptomator.ui.util.ListenerRegistry.ListenerRegistration) SocketChannel(java.nio.channels.SocketChannel) ExecutorService(java.util.concurrent.ExecutorService) ReadableByteChannel(java.nio.channels.ReadableByteChannel) Logger(org.slf4j.Logger) ClosedChannelException(java.nio.channels.ClosedChannelException) SelectionKey(java.nio.channels.SelectionKey) Set(java.util.Set) IOException(java.io.IOException) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Preferences(java.util.prefs.Preferences) Objects(java.util.Objects) IOUtils(org.apache.commons.io.IOUtils) ClosedSelectorException(java.nio.channels.ClosedSelectorException) SelectableChannel(java.nio.channels.SelectableChannel) Closeable(java.io.Closeable) WritableByteChannel(java.nio.channels.WritableByteChannel) Optional(java.util.Optional) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ClosedSelectorException(java.nio.channels.ClosedSelectorException)

Example 7 with Preferences

use of java.util.prefs.Preferences in project jmonkeyengine by jMonkeyEngine.

the class AppSettings method load.

/**
     * Loads settings previously saved in the Java preferences.
     *
     * @param preferencesKey The preferencesKey previously used to save the settings.
     * @throws BackingStoreException If an exception occurs with the preferences
     *
     * @see #save(java.lang.String)
     */
public void load(String preferencesKey) throws BackingStoreException {
    Preferences prefs = Preferences.userRoot().node(preferencesKey);
    String[] keys = prefs.keys();
    if (keys != null) {
        for (String key : keys) {
            if (key.charAt(1) == '_') {
                // Try loading using new method
                switch(key.charAt(0)) {
                    case 'I':
                        put(key.substring(2), prefs.getInt(key, (Integer) 0));
                        break;
                    case 'F':
                        put(key.substring(2), prefs.getFloat(key, (Float) 0f));
                        break;
                    case 'S':
                        put(key.substring(2), prefs.get(key, (String) null));
                        break;
                    case 'B':
                        put(key.substring(2), prefs.getBoolean(key, (Boolean) false));
                        break;
                    default:
                        throw new UnsupportedOperationException("Undefined setting type: " + key.charAt(0));
                }
            } else {
                // Use old method for compatibility with older preferences
                // TODO: Remove when no longer neccessary
                Object defaultValue = defaults.get(key);
                if (defaultValue instanceof Integer) {
                    put(key, prefs.getInt(key, (Integer) defaultValue));
                } else if (defaultValue instanceof String) {
                    put(key, prefs.get(key, (String) defaultValue));
                } else if (defaultValue instanceof Boolean) {
                    put(key, prefs.getBoolean(key, (Boolean) defaultValue));
                }
            }
        }
    }
}
Also used : Preferences(java.util.prefs.Preferences)

Example 8 with Preferences

use of java.util.prefs.Preferences in project jmonkeyengine by jMonkeyEngine.

the class AppSettings method save.

/**
     * Saves settings into the Java preferences.
     * <p>
     * On the Windows operating system, the preferences are saved in the registry
     * at the following key:<br>
     * <code>HKEY_CURRENT_USER\Software\JavaSoft\Prefs\[preferencesKey]</code>
     *
     * @param preferencesKey The preferences key to save at. Generally the
     * application's unique name.
     *
     * @throws BackingStoreException If an exception occurs with the preferences
     */
public void save(String preferencesKey) throws BackingStoreException {
    Preferences prefs = Preferences.userRoot().node(preferencesKey);
    // Clear any previous settings set before saving, this will
    // purge any other parameters set in older versions of the app, so
    // that they don't leak onto the AppSettings of newer versions.
    prefs.clear();
    for (String key : keySet()) {
        Object val = get(key);
        if (val instanceof Integer) {
            prefs.putInt("I_" + key, (Integer) val);
        } else if (val instanceof Float) {
            prefs.putFloat("F_" + key, (Float) val);
        } else if (val instanceof String) {
            prefs.put("S_" + key, (String) val);
        } else if (val instanceof Boolean) {
            prefs.putBoolean("B_" + key, (Boolean) val);
        }
    // NOTE: Ignore any parameters of unsupported types instead
    // of throwing exception. This is specifically for handling
    // BufferedImage which is used in setIcons(), as you do not
    // want to export such data in the preferences.
    }
    // Ensure the data is properly written into preferences before
    // continuing.
    prefs.sync();
}
Also used : Preferences(java.util.prefs.Preferences)

Example 9 with Preferences

use of java.util.prefs.Preferences in project qi4j-sdk by Qi4j.

the class ListPreferencesNodes method printNode.

private static void printNode(Preferences node, String indent) throws BackingStoreException {
    System.out.print(indent);
    String name = node.name();
    if ("".equals(name)) {
        name = "/";
    }
    System.out.print(name);
    String[] nodes = node.keys();
    if (nodes.length > 0) {
        System.out.print("  { ");
        boolean first = true;
        for (String key : nodes) {
            if (!first) {
                System.out.print(", ");
            }
            first = false;
            System.out.print(key);
        }
        System.out.print(" }");
    }
    System.out.println();
    for (String childName : node.childrenNames()) {
        Preferences child = node.node(childName);
        printNode(child, indent + "  ");
    }
}
Also used : Preferences(java.util.prefs.Preferences)

Example 10 with Preferences

use of java.util.prefs.Preferences in project qi4j-sdk by Qi4j.

the class PreferencesEntityStoreMixin method applyChanges.

@Override
public StateCommitter applyChanges(final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> state) {
    return new StateCommitter() {

        @Override
        public void commit() {
            try {
                synchronized (root) {
                    for (EntityState entityState : state) {
                        DefaultEntityState state = (DefaultEntityState) entityState;
                        if (state.status().equals(EntityStatus.NEW)) {
                            Preferences entityPrefs = root.node(state.identity().identity());
                            writeEntityState(state, entityPrefs, unitofwork.identity(), unitofwork.currentTime());
                        } else if (state.status().equals(EntityStatus.UPDATED)) {
                            Preferences entityPrefs = root.node(state.identity().identity());
                            writeEntityState(state, entityPrefs, unitofwork.identity(), unitofwork.currentTime());
                        } else if (state.status().equals(EntityStatus.REMOVED)) {
                            root.node(state.identity().identity()).removeNode();
                        }
                    }
                    root.flush();
                }
            } catch (BackingStoreException e) {
                throw new EntityStoreException(e);
            }
        }

        @Override
        public void cancel() {
        }
    };
}
Also used : DefaultEntityState(org.qi4j.spi.entitystore.helpers.DefaultEntityState) BackingStoreException(java.util.prefs.BackingStoreException) StateCommitter(org.qi4j.spi.entitystore.StateCommitter) EntityState(org.qi4j.spi.entity.EntityState) DefaultEntityState(org.qi4j.spi.entitystore.helpers.DefaultEntityState) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) Preferences(java.util.prefs.Preferences)

Aggregations

Preferences (java.util.prefs.Preferences)291 BackingStoreException (java.util.prefs.BackingStoreException)49 File (java.io.File)45 ResourceBundle (java.util.ResourceBundle)24 FileChooser (javafx.stage.FileChooser)21 ArrayList (java.util.ArrayList)17 FXML (javafx.fxml.FXML)16 IOException (java.io.IOException)14 JFileChooser (javax.swing.JFileChooser)12 List (java.util.List)8 SwingWorker (javax.swing.SwingWorker)8 FileNameExtensionFilter (javax.swing.filechooser.FileNameExtensionFilter)7 Engine (jgnash.engine.Engine)7 AutoCompletePreferences (org.jabref.logic.autocompleter.AutoCompletePreferences)6 FieldContentParserPreferences (org.jabref.logic.bibtex.FieldContentParserPreferences)6 LatexFieldFormatterPreferences (org.jabref.logic.bibtex.LatexFieldFormatterPreferences)6 BibtexKeyPatternPreferences (org.jabref.logic.bibtexkeypattern.BibtexKeyPatternPreferences)6 CleanupPreferences (org.jabref.logic.cleanup.CleanupPreferences)6 ImportFormatPreferences (org.jabref.logic.importer.ImportFormatPreferences)6 JournalAbbreviationPreferences (org.jabref.logic.journals.JournalAbbreviationPreferences)6