Quellcode durchsuchen

Add new Profile wrapper and basic store.

pull/137/head
Greg Holmes vor 9 Jahren
Ursprung
Commit
624a8754fa

+ 100
- 0
src/com/dmdirc/config/profiles/Profile.java Datei anzeigen

@@ -0,0 +1,100 @@
1
+/*
2
+ * Copyright (c) 2006-2014 DMDirc Developers
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+package com.dmdirc.config.profiles;
24
+
25
+import com.google.common.base.MoreObjects;
26
+import com.google.common.collect.Lists;
27
+
28
+import java.util.Collections;
29
+import java.util.List;
30
+import java.util.Objects;
31
+import java.util.Optional;
32
+
33
+/**
34
+ * Describes a profile, used to describe the settings associated with the local client on a
35
+ * connection.
36
+ */
37
+public class Profile {
38
+
39
+    /** Profile Name, must be a sanitised filename. */
40
+    private final String name;
41
+    /** Real name. */
42
+    private final String realname;
43
+    /** Ident. */
44
+    private final Optional<String> ident;
45
+    /** Nicknames. */
46
+    private final List<String> nicknames;
47
+
48
+    public Profile(final String name, final String realname, final Optional<String> ident,
49
+            final Iterable<String> nicknames) {
50
+        this.name = name;
51
+        this.realname = realname;
52
+        this.ident = ident;
53
+        this.nicknames = Lists.newArrayList(nicknames);
54
+    }
55
+
56
+    public String getName() {
57
+        return name;
58
+    }
59
+
60
+    public String getRealname() {
61
+        return realname;
62
+    }
63
+
64
+    public Optional<String> getIdent() {
65
+        return ident;
66
+    }
67
+
68
+    public List<String> getNicknames() {
69
+        return Collections.unmodifiableList(nicknames);
70
+    }
71
+
72
+    public String toString() {
73
+        return MoreObjects.toStringHelper(this)
74
+                .add("name", name)
75
+                .add("realname", realname)
76
+                .add("ident", ident)
77
+                .add("nicknames", nicknames)
78
+                .toString();
79
+    }
80
+
81
+    @Override
82
+    public boolean equals(final Object o) {
83
+        if (this == o) {
84
+            return true;
85
+        }
86
+        if (o == null || getClass() != o.getClass()) {
87
+            return false;
88
+        }
89
+        final Profile profile = (Profile) o;
90
+        return Objects.equals(name, profile.getName())
91
+                && Objects.equals(realname, profile.getRealname())
92
+                && Objects.equals(nicknames, profile.getNicknames())
93
+                && Objects.equals(ident, profile.getIdent());
94
+    }
95
+
96
+    @Override
97
+    public int hashCode() {
98
+        return Objects.hash(name, realname, ident, nicknames);
99
+    }
100
+}

+ 2
- 35
src/com/dmdirc/config/profiles/ProfileManager.java Datei anzeigen

@@ -22,53 +22,34 @@
22 22
 
23 23
 package com.dmdirc.config.profiles;
24 24
 
25
-import com.dmdirc.actions.wrappers.Profile;
26
-import com.dmdirc.interfaces.config.ConfigProvider;
27
-import com.dmdirc.interfaces.config.ConfigProviderListener;
28
-import com.dmdirc.interfaces.config.IdentityController;
29
-import com.dmdirc.interfaces.config.IdentityFactory;
30
-
31 25
 import java.util.ArrayList;
32 26
 import java.util.Collection;
33 27
 import java.util.Collections;
34
-import java.util.List;
35
-import java.util.stream.Collectors;
36 28
 
37 29
 import javax.inject.Inject;
38 30
 
39 31
 /**
40 32
  * Manager for {@link Profile}s.
41 33
  */
42
-public class ProfileManager implements ConfigProviderListener {
34
+public class ProfileManager {
43 35
 
44
-    private final IdentityFactory identityFactory;
45
-    private final IdentityController identityController;
46 36
     private final Collection<Profile> profiles;
47 37
 
48 38
     @Inject
49
-    public ProfileManager(final IdentityController identityController,
50
-            final IdentityFactory identityFactory) {
51
-        this.identityFactory = identityFactory;
52
-        this.identityController = identityController;
39
+    public ProfileManager() {
53 40
         profiles = new ArrayList<>();
54
-        final List<ConfigProvider> identities = identityController.getProvidersByType("profile");
55
-        profiles.addAll(identities.stream()
56
-                .map(identity -> new Profile(identityFactory, identity))
57
-                .collect(Collectors.toList()));
58 41
     }
59 42
 
60 43
     /**
61 44
      * Starts this manager, registering listeners.
62 45
      */
63 46
     public void start() {
64
-        identityController.registerIdentityListener(this);
65 47
     }
66 48
 
67 49
     /**
68 50
      * Stops this manager, unregistering listeners.
69 51
      */
70 52
     public void stop() {
71
-        identityController.unregisterIdentityListener(this);
72 53
     }
73 54
 
74 55
     /**
@@ -97,18 +78,4 @@ public class ProfileManager implements ConfigProviderListener {
97 78
     public Collection<Profile> getProfiles() {
98 79
         return Collections.unmodifiableCollection(profiles);
99 80
     }
100
-
101
-    @Override
102
-    public void configProviderAdded(final ConfigProvider configProvider) {
103
-        if (configProvider.isProfile()) {
104
-            profiles.removeIf(p-> p.equalsConfigProvider(configProvider));
105
-        }
106
-    }
107
-
108
-    @Override
109
-    public void configProviderRemoved(final ConfigProvider configProvider) {
110
-        if (configProvider.isProfile()) {
111
-            profiles.add(new Profile(identityFactory, configProvider));
112
-        }
113
-    }
114 81
 }

+ 46
- 0
src/com/dmdirc/config/profiles/ProfileStore.java Datei anzeigen

@@ -0,0 +1,46 @@
1
+/*
2
+ * Copyright (c) 2006-2014 DMDirc Developers
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+package com.dmdirc.config.profiles;
24
+
25
+import java.util.Set;
26
+
27
+/**
28
+ * A store of {@link Profile}s that can read and write them to some kind of persistent media.
29
+ */
30
+public interface ProfileStore {
31
+
32
+    /**
33
+     * Reads and returns all profiles from within the store.
34
+     *
35
+     * @return A set of known profiles, or an empty set if the store is uninitialised.
36
+     */
37
+    Set<Profile> readProfiles();
38
+
39
+    /**
40
+     * Writes all the given profiles to the store, replacing any existing commands.
41
+     *
42
+     * @param profiles The set of profiles to be written to the store.
43
+     */
44
+    void writeProfiles(Set<Profile> profiles);
45
+
46
+}

+ 153
- 0
src/com/dmdirc/config/profiles/YamlProfileStore.java Datei anzeigen

@@ -0,0 +1,153 @@
1
+/*
2
+ * Copyright (c) 2006-2014 DMDirc Developers
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+package com.dmdirc.config.profiles;
24
+
25
+import com.google.common.base.Splitter;
26
+
27
+import java.io.IOException;
28
+import java.io.InputStream;
29
+import java.io.InputStreamReader;
30
+import java.io.OutputStream;
31
+import java.io.OutputStreamWriter;
32
+import java.nio.file.Files;
33
+import java.nio.file.Path;
34
+import java.util.ArrayList;
35
+import java.util.Collection;
36
+import java.util.HashMap;
37
+import java.util.HashSet;
38
+import java.util.List;
39
+import java.util.Map;
40
+import java.util.Optional;
41
+import java.util.Set;
42
+
43
+import org.slf4j.Logger;
44
+import org.slf4j.LoggerFactory;
45
+
46
+import com.esotericsoftware.yamlbeans.YamlReader;
47
+import com.esotericsoftware.yamlbeans.YamlWriter;
48
+
49
+import static com.dmdirc.util.YamlReaderUtils.asList;
50
+import static com.dmdirc.util.YamlReaderUtils.asMap;
51
+import static com.dmdirc.util.YamlReaderUtils.optionalString;
52
+import static com.dmdirc.util.YamlReaderUtils.requiredString;
53
+
54
+/**
55
+ * Store that reads and writes profiles from a YAML file on disk.
56
+ */
57
+public class YamlProfileStore implements ProfileStore {
58
+
59
+    private static final Logger LOG = LoggerFactory.getLogger(YamlProfileStore.class);
60
+    /** The charset to use when reading and writing files. */
61
+    private static final String CHARSET = "UTF-8";
62
+
63
+    /** The path to the file to read and write auto commands in. */
64
+    private final Path path;
65
+
66
+    /**
67
+     * Creates a new YAML profiles store.
68
+     *
69
+     * @param path The path to the YAML file to read and write profiles in.
70
+     */
71
+    public YamlProfileStore(final Path path) {
72
+        this.path = path;
73
+    }
74
+
75
+    @Override
76
+    public Set<Profile> readProfiles() {
77
+        final Set<Profile> commands = new HashSet<>();
78
+        if (Files.exists(path)) {
79
+            try (final InputStream stream = Files.newInputStream(path);
80
+                    final InputStreamReader reader = new InputStreamReader(stream, CHARSET)) {
81
+                final YamlReader yamlReader = new YamlReader(reader);
82
+                final Object root = yamlReader.read();
83
+                commands.addAll(readProfilesFromYaml(asList(root)));
84
+                yamlReader.close();
85
+            } catch (IOException | IllegalArgumentException ex) {
86
+                LOG.warn("Unable to read auto commands", ex);
87
+            }
88
+        }
89
+
90
+        return commands;
91
+    }
92
+
93
+    @Override
94
+    public void writeProfiles(final Set<Profile> profiles) {
95
+        final List<Object> list = getProfilesForYaml(profiles);
96
+        try (final OutputStream stream = Files.newOutputStream(path);
97
+                final OutputStreamWriter writer = new OutputStreamWriter(stream, CHARSET)) {
98
+            final YamlWriter yamlWriter = new YamlWriter(writer);
99
+            yamlWriter.write(list);
100
+            yamlWriter.close();
101
+        } catch (IOException ex) {
102
+            LOG.error("Unable to write auto commands", ex);
103
+        }
104
+    }
105
+
106
+    /**
107
+     * Builds a set of auto commands from the given YAML representations.
108
+     *
109
+     * @param objects The raw objects read from the YAML file.
110
+     *
111
+     * @return A list of corresponding auto commands.
112
+     */
113
+    private Collection<Profile> readProfilesFromYaml(final Collection<Object> objects) {
114
+        final Collection<Profile> res = new ArrayList<>(objects.size());
115
+        for (Object profile : objects) {
116
+            try {
117
+                final Map<Object, Object> map = asMap(profile);
118
+                final String name = requiredString(map, "name");
119
+                final String realname = requiredString(map, "realname");
120
+                final Optional<String> ident =
121
+                        Optional.ofNullable(optionalString(map, "ident"));
122
+                final List<String> nicknames =
123
+                        Splitter.on('\n').splitToList(requiredString(map, "nicknames"));
124
+                res.add(new Profile(name, realname, ident, nicknames));
125
+            } catch (IllegalArgumentException ex) {
126
+                LOG.info("Unable to read alias", ex);
127
+            }
128
+        }
129
+        return res;
130
+    }
131
+
132
+    /**
133
+     * Gets a set of maps that can be written to a YAML file.
134
+     *
135
+     * @param profiles The profiles to be stored.
136
+     *
137
+     * @return A list of corresponding maps.
138
+     */
139
+    private List<Object> getProfilesForYaml(final Collection<Profile> profiles) {
140
+        final List<Object> res = new ArrayList<>(profiles.size());
141
+        for (Profile profile : profiles) {
142
+            final Map<Object, Object> map = new HashMap<>();
143
+            map.put("name", profile.getName());
144
+            map.put("realname", profile.getRealname());
145
+            if (profile.getIdent().isPresent()) {
146
+                map.put("ident", profile.getIdent().get());
147
+            }
148
+            map.put("nicknames", profile.getNicknames());
149
+            res.add(map);
150
+        }
151
+        return res;
152
+    }
153
+}

+ 10
- 0
test-res/com/dmdirc/config/profiles/profiles.yml Datei anzeigen

@@ -0,0 +1,10 @@
1
+- name: profile1
2
+  realname: realname1
3
+  nicknames: nickname1, nickname2
4
+- name: profile2
5
+  realname: realname2
6
+  nicknames: nickname1, nickname1
7
+  ident: ident2
8
+- name: profile3
9
+  realname: profile3
10
+  nicknames: nickname3

+ 68
- 0
test/com/dmdirc/config/profiles/YamlProfileStoreTest.java Datei anzeigen

@@ -0,0 +1,68 @@
1
+/*
2
+ * Copyright (c) 2006-2014 DMDirc Developers
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in
12
+ * all copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+package com.dmdirc.config.profiles;
24
+
25
+import com.google.common.collect.Lists;
26
+import com.google.common.collect.Sets;
27
+import com.google.common.jimfs.Configuration;
28
+import com.google.common.jimfs.Jimfs;
29
+
30
+import java.nio.file.FileSystem;
31
+import java.nio.file.Files;
32
+import java.nio.file.Paths;
33
+import java.util.Collection;
34
+import java.util.List;
35
+import java.util.Optional;
36
+import java.util.Set;
37
+
38
+import org.junit.Test;
39
+import org.junit.runner.RunWith;
40
+import org.mockito.runners.MockitoJUnitRunner;
41
+
42
+import static junit.framework.TestCase.assertEquals;
43
+
44
+@RunWith(MockitoJUnitRunner.class)
45
+public class YamlProfileStoreTest {
46
+
47
+    @Test
48
+    public void testReadProfiles() throws Exception {
49
+        final ProfileStore store = new YamlProfileStore(Paths.get(getClass()
50
+                .getResource("profiles.yml").toURI()));
51
+        final Collection<Profile> profiles = store.readProfiles();
52
+        assertEquals(3, profiles.size());
53
+    }
54
+
55
+    @Test
56
+    public void testWriteProfiles() throws Exception {
57
+        try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) {
58
+            final ProfileStore store = new YamlProfileStore(fs.getPath("/")
59
+                    .resolve("profiles.yml"));
60
+            final Profile profile1 = new Profile("name", "realname", Optional.of("ident"),
61
+                    Lists.newArrayList("nickname"));
62
+            final Set<Profile> profiles = Sets.newHashSet(profile1);
63
+            store.writeProfiles(profiles);
64
+            final List<String> lines = Files.readAllLines(fs.getPath("/").resolve("profiles.yml"));
65
+            assertEquals(5, lines.size());
66
+        }
67
+    }
68
+}

Laden…
Abbrechen
Speichern