Added delete key in setting controllers

Change-Id: I82484d0a94d74cf42a68647310e37611e15a62b6
diff --git a/full/Changes b/full/Changes
index 8fd48a9..0c554ae 100644
--- a/full/Changes
+++ b/full/Changes
@@ -23,6 +23,7 @@
    - Added create, edit, retrieve user default setting controllers (margaretha)
 22/01/2019
    - Updated default setting controllers & added tests (margaretha)
+   - Added delete key in setting controllers (margaretha)
 
 # version 0.61.4
 14/11/2018
diff --git a/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java b/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java
index 99e707d..99b6b52 100644
--- a/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java
+++ b/full/src/main/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManager.java
@@ -47,7 +47,7 @@
 import de.ids_mannheim.korap.user.User.CorpusAccess;
 import de.ids_mannheim.korap.user.User.Location;
 import de.ids_mannheim.korap.user.UserDetails;
-import de.ids_mannheim.korap.user.UserSettings;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
 import de.ids_mannheim.korap.user.Userdata;
 import de.ids_mannheim.korap.utils.TimeUtils;
 
@@ -642,7 +642,7 @@
 		UserDetails d = new UserDetails();
 		d.read(attributes, true);
 
-		UserSettings s = new UserSettings();
+		UserSettingProcessor s = new UserSettingProcessor();
 		s.read(attributes, true);
 
 		entHandler.createAccount(user);
@@ -654,7 +654,7 @@
 		assert dao != null;
 		dao.store(d);
 
-		dao = BeansFactory.getTypeFactory().getTypeInterfaceBean(userdatadaos, UserSettings.class);
+		dao = BeansFactory.getTypeFactory().getTypeInterfaceBean(userdatadaos, UserSettingProcessor.class);
 		assert dao != null;
 		dao.store(d);
 
diff --git a/full/src/main/java/de/ids_mannheim/korap/handlers/UserSettingsDao.java b/full/src/main/java/de/ids_mannheim/korap/handlers/UserSettingsDao.java
index 55d19d9..326ddb3 100644
--- a/full/src/main/java/de/ids_mannheim/korap/handlers/UserSettingsDao.java
+++ b/full/src/main/java/de/ids_mannheim/korap/handlers/UserSettingsDao.java
@@ -6,7 +6,7 @@
 import de.ids_mannheim.korap.interfaces.db.PersistenceClient;
 import de.ids_mannheim.korap.interfaces.db.UserDataDbIface;
 import de.ids_mannheim.korap.user.User;
-import de.ids_mannheim.korap.user.UserSettings;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
 
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
@@ -26,7 +26,7 @@
  * @date 28/01/2016
  */
 @Deprecated
-public class UserSettingsDao implements UserDataDbIface<UserSettings> {
+public class UserSettingsDao implements UserDataDbIface<UserSettingProcessor> {
 
     private static final Logger jlog = LogManager
             .getLogger(UserSettingsDao.class);
@@ -40,7 +40,7 @@
 
 
     @Override
-    public int store (UserSettings data) throws KustvaktException {
+    public int store (UserSettingProcessor data) throws KustvaktException {
         String sql = "INSERT INTO user_settings (user_id, data) VALUES (:userid, :data);";
         MapSqlParameterSource source = new MapSqlParameterSource();
         source.addValue("userid", data.getUserId());
@@ -62,7 +62,7 @@
 
 
     @Override
-    public int update (UserSettings data) throws KustvaktException {
+    public int update (UserSettingProcessor data) throws KustvaktException {
         String sql = "UPDATE user_settings SET data = :data WHERE user_id=:userid;";
         MapSqlParameterSource source = new MapSqlParameterSource();
         source.addValue("userid", data.getUserId());
@@ -78,19 +78,19 @@
 
 
     @Override
-    public UserSettings get (Integer id) throws DatabaseException {
+    public UserSettingProcessor get (Integer id) throws DatabaseException {
         String sql = "SELECT * FROM user_settings WHERE id=:id;";
         MapSqlParameterSource source = new MapSqlParameterSource();
         source.addValue("id", id);
 
         try {
             return this.jdbcTemplate.queryForObject(sql, source,
-                    new RowMapper<UserSettings>() {
+                    new RowMapper<UserSettingProcessor>() {
 
                         @Override
-                        public UserSettings mapRow (ResultSet rs, int rowNum)
+                        public UserSettingProcessor mapRow (ResultSet rs, int rowNum)
                                 throws SQLException {
-                            UserSettings details = new UserSettings(
+                            UserSettingProcessor details = new UserSettingProcessor(
                                     rs.getInt("user_id"));
                             details.setId(rs.getInt("id"));
                             details.setData(rs.getString("data"));
@@ -111,19 +111,19 @@
 
 
     @Override
-    public UserSettings get (User user) throws DatabaseException {
+    public UserSettingProcessor get (User user) throws DatabaseException {
         String sql = "SELECT * FROM user_settings WHERE user_id=:userid;";
         MapSqlParameterSource source = new MapSqlParameterSource();
         source.addValue("userid", user.getId());
 
         try {
             return this.jdbcTemplate.queryForObject(sql, source,
-                    new RowMapper<UserSettings>() {
+                    new RowMapper<UserSettingProcessor>() {
 
                         @Override
-                        public UserSettings mapRow (ResultSet rs, int rowNum)
+                        public UserSettingProcessor mapRow (ResultSet rs, int rowNum)
                                 throws SQLException {
-                            UserSettings details = new UserSettings(
+                            UserSettingProcessor details = new UserSettingProcessor(
                                     rs.getInt("user_id"));
                             details.setId(rs.getInt("id"));
                             details.setData(rs.getString("data"));
@@ -143,7 +143,7 @@
 
 
     @Override
-    public int delete (UserSettings data) {
+    public int delete (UserSettingProcessor data) {
         String sql = "DELETE FROM user_settings WHERE id=:id";
         MapSqlParameterSource source = new MapSqlParameterSource();
         source.addValue("id", data.getId());
@@ -170,7 +170,7 @@
 
 
     @Override
-    public Class<UserSettings> type () {
-        return UserSettings.class;
+    public Class<UserSettingProcessor> type () {
+        return UserSettingProcessor.class;
     }
 }
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java b/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
index 181d934..1aabb9b 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/DefaultSettingService.java
@@ -10,8 +10,8 @@
 import de.ids_mannheim.korap.entity.DefaultSetting;
 import de.ids_mannheim.korap.exceptions.KustvaktException;
 import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.user.UserSettings;
-import de.ids_mannheim.korap.user.Userdata;
+import de.ids_mannheim.korap.user.DataFactory;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
 
 @Service
 public class DefaultSettingService {
@@ -19,65 +19,84 @@
     @Autowired
     private DefaultSettingDao settingDao;
 
-    private void verifiyUsername (String username, String authenticatedUser)
+    public DataFactory dataFactory = DataFactory.getFactory();
+
+    private String verifiyUsername (String username, String contextUsername)
             throws KustvaktException {
-        if (!username.equals(authenticatedUser)) {
+        username = username.substring(0);
+        if (!username.equals(contextUsername)) {
             throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
                     "Username verification failed. Path parameter username "
-                            + "must be the same as the authenticated username.",
+                            + "without prefix must be the same as the "
+                            + "authenticated username.",
                     username);
         }
+        return username;
     }
 
     public int handlePutRequest (String username, Map<String, Object> map,
-            String authenticatedUser) throws KustvaktException {
-        verifiyUsername(username, authenticatedUser);
+            String contextUsername) throws KustvaktException {
+        username = verifiyUsername(username, contextUsername);
 
         if (map == null || map.isEmpty()) {
             throw new KustvaktException(StatusCodes.INVALID_ARGUMENT,
                     "Entity body is empty. No settings are given.");
         }
 
-        Userdata userdata = new UserSettings(username);
-        userdata.readQuietly(map, false);
+        UserSettingProcessor processor = new UserSettingProcessor();
+        processor.readQuietly(map, false);
 
         DefaultSetting defaultSetting =
                 settingDao.retrieveDefautlSetting(username);
         if (defaultSetting == null) {
-            createDefaultSetting(username, userdata);
+            createDefaultSetting(username, processor);
             return HttpStatus.SC_CREATED;
         }
         else {
-            updateDefaultSetting(defaultSetting, userdata);
+            updateDefaultSetting(defaultSetting, processor);
             return HttpStatus.SC_OK;
         }
     }
 
-    public void createDefaultSetting (String username, Userdata userdata)
-            throws KustvaktException {
-        String jsonSettings = userdata.serialize();
+    public void createDefaultSetting (String username,
+            UserSettingProcessor processor) throws KustvaktException {
+        String jsonSettings = processor.serialize();
         settingDao.createDefaultSetting(username, jsonSettings);
     }
 
-    public void updateDefaultSetting (DefaultSetting setting, Userdata newData)
-            throws KustvaktException {
-        Userdata existingData = new UserSettings(setting.getUsername());
-        existingData.setData(setting.getSettings());
-        existingData.update(newData);
+    public void updateDefaultSetting (DefaultSetting setting,
+            UserSettingProcessor newProcessor) throws KustvaktException {
+        UserSettingProcessor processor =
+                new UserSettingProcessor(setting.getSettings());
+        processor.update(newProcessor);
 
-        String newSettings = existingData.serialize();
-        setting.setSettings(newSettings);
+        String jsonSettings = processor.serialize();
+        setting.setSettings(jsonSettings);
         settingDao.updateDefaultSetting(setting);
     }
 
     public String retrieveDefaultSettings (String username,
-            String authenticatedUser) throws KustvaktException {
+            String contextUsername) throws KustvaktException {
 
-        verifiyUsername(username, authenticatedUser);
-
+        username = verifiyUsername(username, contextUsername);
         DefaultSetting defaultSetting =
                 settingDao.retrieveDefautlSetting(username);
         return defaultSetting.getSettings();
     }
 
+    public void deleteKey (String username, String contextUsername, String key)
+            throws KustvaktException {
+        username = verifiyUsername(username, contextUsername);
+        DefaultSetting defaultSetting =
+                settingDao.retrieveDefautlSetting(username);
+
+        String jsonSettings = defaultSetting.getSettings();
+        UserSettingProcessor processor = new UserSettingProcessor(jsonSettings);
+        processor.removeField(key);
+        String json = processor.serialize();
+
+        defaultSetting.setSettings(json);
+        settingDao.updateDefaultSetting(defaultSetting);
+    }
+
 }
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/ShibbolethUserController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/ShibbolethUserController.java
index bd95f13..79ba584 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/ShibbolethUserController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/ShibbolethUserController.java
@@ -39,7 +39,7 @@
 import de.ids_mannheim.korap.user.User;
 import de.ids_mannheim.korap.user.UserDetails;
 import de.ids_mannheim.korap.user.UserQuery;
-import de.ids_mannheim.korap.user.UserSettings;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
 import de.ids_mannheim.korap.user.Userdata;
 import de.ids_mannheim.korap.utils.JsonUtils;
 import de.ids_mannheim.korap.utils.StringUtils;
@@ -130,7 +130,7 @@
         String result;
         try {
             User user = controller.getUser(ctx.getUsername());
-            Userdata data = controller.getUserData(user, UserSettings.class);
+            Userdata data = controller.getUserData(user, UserSettingProcessor.class);
             data.setField(Attributes.USERNAME, ctx.getUsername());
             result = data.serialize();
         }
@@ -159,14 +159,14 @@
             if (User.UserFactory.isDemo(ctx.getUsername()))
                 return Response.notModified().build();
 
-            Userdata data = controller.getUserData(user, UserSettings.class);
+            Userdata data = controller.getUserData(user, UserSettingProcessor.class);
             // todo: check setting only within the scope of user settings permissions; not foundry range. Latter is part of
             // frontend which only displays available foundries and
             //            SecurityManager.findbyId(us.getDefaultConstfoundry(), user, Foundry.class);
             //            SecurityManager.findbyId(us.getDefaultLemmafoundry(), user, Foundry.class);
             //            SecurityManager.findbyId(us.getDefaultPOSfoundry(), user, Foundry.class);
             //            SecurityManager.findbyId(us.getDefaultRelfoundry(), user, Foundry.class);
-            Userdata new_data = new UserSettings(user.getId());
+            Userdata new_data = new UserSettingProcessor(user.getId());
             new_data.readQuietly((Map<String, Object>) settings, false);
             data.update(new_data);
             controller.updateUserData(data);
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java
index 638cd8a..0fba5b7 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/UserController.java
@@ -3,6 +3,7 @@
 import java.util.Map;
 
 import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
 import javax.ws.rs.GET;
 import javax.ws.rs.PUT;
 import javax.ws.rs.Path;
@@ -79,7 +80,7 @@
 
         try {
             scopeService.verifyScope(tokenContext,
-                    OAuth2Scope.CREATE_DEFAULT_SETTING);
+                    OAuth2Scope.READ_DEFAULT_SETTING);
             String settings = settingService.retrieveDefaultSettings(username,
                     tokenContext.getUsername());
             return Response.ok(settings).build();
@@ -89,4 +90,24 @@
         }
     }
 
+    @DELETE
+    @Path("setting/{key}")
+    @Consumes(MediaType.APPLICATION_JSON)
+    @ResourceFilters({ AuthenticationFilter.class, PiwikFilter.class,
+            BlockingFilter.class })
+    public Response createDefaultSetting (@Context SecurityContext context,
+            @PathParam("username") String username,
+            @PathParam("key") String key) {
+
+        TokenContext tokenContext = (TokenContext) context.getUserPrincipal();
+        try {
+            scopeService.verifyScope(tokenContext,
+                    OAuth2Scope.DELETE_DEFAULT_SETTING);
+            settingService.deleteKey(username, tokenContext.getUsername(), key);
+            return Response.ok().build();
+        }
+        catch (KustvaktException e) {
+            throw kustvaktResponseHandler.throwit(e);
+        }
+    }
 }
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManagerTest.java b/full/src/test/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManagerTest.java
index 7c27553..e06d9f7 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManagerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/KustvaktAuthenticationManagerTest.java
@@ -14,7 +14,7 @@
 import de.ids_mannheim.korap.user.KorAPUser;
 import de.ids_mannheim.korap.user.User;
 import de.ids_mannheim.korap.user.UserDetails;
-import de.ids_mannheim.korap.user.UserSettings;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
 import de.ids_mannheim.korap.user.Userdata;
 
 /**
@@ -71,7 +71,7 @@
                 .getUser((String) KustvaktConfiguration.KUSTVAKT_USER
                         .get(Attributes.USERNAME));
 
-        Userdata data = authenticationManager.getUserData(user, UserSettings.class);
+        Userdata data = authenticationManager.getUserData(user, UserSettingProcessor.class);
         assertNotNull(data);
     }
 
@@ -86,7 +86,7 @@
     @Test(expected = KustvaktException.class)
     public void testUserSettingsGetNonExistent () throws KustvaktException {
         User user = new KorAPUser(10, "random");
-        authenticationManager.getUserData(user, UserSettings.class);
+        authenticationManager.getUserData(user, UserSettingProcessor.class);
     }
 
 
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/BeanInjectTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/BeanInjectTest.java
index c5814e4..4de83e0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/BeanInjectTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/BeanInjectTest.java
@@ -12,7 +12,7 @@
 import de.ids_mannheim.korap.handlers.UserDetailsDao;
 import de.ids_mannheim.korap.handlers.UserSettingsDao;
 import de.ids_mannheim.korap.user.UserDetails;
-import de.ids_mannheim.korap.user.UserSettings;
+import de.ids_mannheim.korap.user.UserSettingProcessor;
 
 /**
  * Created by hanl on 03.06.16.
@@ -26,7 +26,7 @@
                 .getUserDataProviders();
         assertFalse(coll.isEmpty());
         Object o = BeansFactory.getTypeFactory().getTypeInterfaceBean(coll,
-                UserSettings.class);
+                UserSettingProcessor.class);
         assertEquals(UserSettingsDao.class, AopUtils.getTargetClass(o));
 
         o = BeansFactory.getTypeFactory().getTypeInterfaceBean(coll,
diff --git a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
index 04f8359..c97d0a5 100644
--- a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
@@ -96,7 +96,7 @@
 
     @Test
     public void testSettingsValidation () {
-        Userdata data = new UserSettings(1);
+        Userdata data = new UserSettingProcessor(1);
         data.setField(Attributes.FILE_FORMAT_FOR_EXPORT, "export");
 
         String[] req = data.requiredFields();
@@ -118,7 +118,7 @@
 
         dao = BeansFactory.getTypeFactory().getTypeInterfaceBean(
                 helper().getContext().getUserDataProviders(),
-                UserSettings.class);
+                UserSettingProcessor.class);
         assertNotNull(dao);
         assertTrue(dao instanceof UserSettingsDao);
     }
diff --git a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest2.java b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest2.java
index acdd062..8364fb9 100644
--- a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest2.java
+++ b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest2.java
@@ -25,7 +25,7 @@
 
     @Test
     public void testReadEmptyMap () throws KustvaktException {
-        Userdata userData = new UserSettings();
+        Userdata userData = new UserSettingProcessor();
         userData.read(new HashMap<>(), false);
         String jsonSettings = userData.serialize();
         assertEquals("{}", jsonSettings);
@@ -33,7 +33,7 @@
 
     @Test
     public void testReadNullMap () throws KustvaktException {
-        Userdata userData = new UserSettings();
+        Userdata userData = new UserSettingProcessor();
         userData.read(null, false);
         String jsonSettings = userData.serialize();
         assertEquals("{}", jsonSettings);
@@ -56,7 +56,7 @@
         map.put("k1", Arrays.asList(new String[] { "a", "b", "c" }));
         map.put("k2", Arrays.asList(new Integer[] { 1, 2, 3 }));
 
-        Userdata data = new UserSettings();
+        Userdata data = new UserSettingProcessor();
         data.read(map, false);
         data.validate(new ApacheValidator());
     }
@@ -80,7 +80,7 @@
 
     @Test
     public void testUserdataDefaultFields () throws KustvaktException {
-        UserSettings settings = new UserSettings(-1);
+        UserSettingProcessor settings = new UserSettingProcessor(-1);
         Map<String, Object> m = new HashMap<>();
         m.put(Attributes.DEFAULT_REL_FOUNDRY, "rel_1");
         m.put(Attributes.DEFAULT_CONST_FOUNDRY, "const_1");
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
index d074d02..69f47df 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
@@ -1,6 +1,7 @@
 package de.ids_mannheim.korap.web.controller;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 
 import java.util.HashMap;
 import java.util.Map;
@@ -32,8 +33,8 @@
 
     private ClientResponse sendPutRequest (String username,
             Map<String, Object> map) throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION)
-                .path(username).path("setting")
+        ClientResponse response = resource().path(API_VERSION).path(username)
+                .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
                 .type(MediaType.APPLICATION_JSON).entity(map)
@@ -47,8 +48,8 @@
         String json = "{\"foundry\":\"opennlp\",\"metadata\":\"author title "
                 + "textSigle availability\",\"resultPerPage\":25}";
 
-        ClientResponse response = resource().path(API_VERSION)
-                .path(username).path("setting")
+        ClientResponse response = resource().path(API_VERSION).path(username)
+                .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
                 .type(MediaType.APPLICATION_JSON).entity(json)
@@ -56,12 +57,17 @@
 
         assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
 
-        testRetrieveSettings(username, "opennlp", 25,
-                "author title textSigle availability");
+        int numOfResult = 25;
+        String metadata = "author title textSigle availability";
+
+        testRetrieveSettings(username, "opennlp", numOfResult, metadata);
+
+        testDeleteKey(username, numOfResult, metadata);
     }
 
     @Test
     public void testCreateSettingWithMap () throws KustvaktException {
+
         Map<String, Object> map = new HashMap<>();
         map.put("foundry", "opennlp");
         map.put("resultPerPage", 25);
@@ -81,8 +87,8 @@
         String json = "{\"foundry\":\"opennlp\",\"metadata\":\"author title "
                 + "textSigle availability\",\"resultPerPage\":25}";
 
-        ClientResponse response = resource().path(API_VERSION)
-                .path(username).path("setting")
+        ClientResponse response = resource().path(API_VERSION).path(username)
+                .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username2, "pass"))
                 .type(MediaType.APPLICATION_JSON).entity(json)
@@ -97,8 +103,8 @@
 
     @Test
     public void testGetDifferentUsername () throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION)
-                .path(username).path("setting")
+        ClientResponse response = resource().path(API_VERSION).path(username)
+                .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username2, "pass"))
                 .get(ClientResponse.class);
@@ -110,6 +116,34 @@
                 node.at("/errors/0/0").asInt());
     }
 
+    @Test
+    public void testDeleteKeyDifferentUsername () throws KustvaktException {
+        ClientResponse response = resource().path(API_VERSION).path(username)
+                .path("setting").path("foundry")
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(username2, "pass"))
+                .delete(ClientResponse.class);
+
+        assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+        String entity = response.getEntity(String.class);
+        JsonNode node = JsonUtils.readTree(entity);
+        assertEquals(StatusCodes.INVALID_ARGUMENT,
+                node.at("/errors/0/0").asInt());
+    }
+
+    private void testDeleteKey (String username, int numOfResult,
+            String metadata) throws KustvaktException {
+
+        ClientResponse response = resource().path(API_VERSION).path(username)
+                .path("setting").path("foundry")
+                .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+                        .createBasicAuthorizationHeaderValue(username, "pass"))
+                .delete(ClientResponse.class);
+
+        assertEquals(Status.OK.getStatusCode(), response.getStatus());
+        testRetrieveSettings(username, null, numOfResult, metadata);
+    }
+
     private void testUpdateSetting (String username) throws KustvaktException {
         Map<String, Object> map = new HashMap<>();
         map.put("foundry", "malt");
@@ -122,10 +156,10 @@
         testRetrieveSettings(username, "malt", 15, "author title");
     }
 
-    private void testRetrieveSettings (String username, String foundry, int numOfResult,
-            String metadata) throws KustvaktException {
-        ClientResponse response = resource().path(API_VERSION)
-                .path(username).path("setting")
+    private void testRetrieveSettings (String username, String foundry,
+            int numOfResult, String metadata) throws KustvaktException {
+        ClientResponse response = resource().path(API_VERSION).path(username)
+                .path("setting")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(username, "pass"))
                 .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
@@ -133,7 +167,12 @@
 
         String entity = response.getEntity(String.class);
         JsonNode node = JsonUtils.readTree(entity);
-        assertEquals(foundry, node.at("/foundry").asText());
+        if (foundry == null) {
+            assertTrue(node.at("/foundry").isMissingNode());
+        }
+        else {
+            assertEquals(foundry, node.at("/foundry").asText());
+        }
         assertEquals(numOfResult, node.at("/resultPerPage").asInt());
         assertEquals(metadata, node.at("/metadata").asText());
     }