Added retrieveVCByName and deleteVCByName.

Change-Id: Ib1ed86342b6deaaa32e55367217a2203786d63e4
diff --git a/full/Changes b/full/Changes
index eee2da3..a83aed6 100644
--- a/full/Changes
+++ b/full/Changes
@@ -11,6 +11,8 @@
 11/01/2019
    - Degraded API version to 1.0 (margaretha)
    - Added OAuth2 client info tests (margaretha)
+14/01/2019
+   - Added retrieveVCByName and deleteVCByName controllers (margaretha)
 
 # version 0.61.4
 14/11/2018
diff --git a/full/src/main/java/de/ids_mannheim/korap/service/VirtualCorpusService.java b/full/src/main/java/de/ids_mannheim/korap/service/VirtualCorpusService.java
index c4f2241..15da11f 100644
--- a/full/src/main/java/de/ids_mannheim/korap/service/VirtualCorpusService.java
+++ b/full/src/main/java/de/ids_mannheim/korap/service/VirtualCorpusService.java
@@ -57,7 +57,7 @@
             LogManager.getLogger(VirtualCorpusService.class);
 
     public static boolean DEBUG = false;
-    
+
     public static Pattern wordPattern = Pattern.compile("[-\\w. ]+");
 
     @Autowired
@@ -83,22 +83,22 @@
         return createVCDtos(vcList);
     }
 
-    public List<VirtualCorpusDto> listVCByUser (String contextUsername,
-            String createdBy) throws KustvaktException {
+    public List<VirtualCorpusDto> listAvailableVCForUser (String authenticatedUsername,
+            String username) throws KustvaktException {
 
-        boolean isAdmin = adminDao.isAdmin(contextUsername);
+        boolean isAdmin = adminDao.isAdmin(authenticatedUsername);
 
-        if (createdBy != null) {
-            if (!createdBy.equals(contextUsername) && !isAdmin) {
+        if (username != null) {
+            if (!username.equals(authenticatedUsername) && !isAdmin) {
                 throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
-                        "Unauthorized operation for user: " + contextUsername,
-                        contextUsername);
+                        "Unauthorized operation for user: " + authenticatedUsername,
+                        authenticatedUsername);
             }
         }
         else {
-            createdBy = contextUsername;
+            username = authenticatedUsername;
         }
-        List<VirtualCorpus> vcList = vcDao.retrieveVCByUser(createdBy);
+        List<VirtualCorpus> vcList = vcDao.retrieveVCByUser(username);
         return createVCDtos(vcList);
     }
 
@@ -145,6 +145,7 @@
      *            virtual corpus id
      * @throws KustvaktException
      */
+    @Deprecated
     public void deleteVC (String username, int vcId) throws KustvaktException {
 
         VirtualCorpus vc = vcDao.retrieveVCById(vcId);
@@ -166,6 +167,40 @@
         }
     }
 
+    /**
+     * Only admin and the owner of the virtual corpus are allowed to
+     * delete a virtual corpus.
+     * 
+     * @param username
+     *            username
+     * @param vcName
+     *            virtual corpus name
+     * @param createdBy
+     *            virtual corpus creator
+     * @throws KustvaktException
+     */
+    public void deleteVCByName (String username, String vcName,
+            String createdBy) throws KustvaktException {
+
+        VirtualCorpus vc = vcDao.retrieveVCByName(vcName, createdBy);
+
+        if (vc.getCreatedBy().equals(username) || adminDao.isAdmin(username)) {
+
+            if (vc.getType().equals(VirtualCorpusType.PUBLISHED)) {
+                VirtualCorpusAccess access =
+                        accessDao.retrieveHiddenAccess(vc.getId());
+                accessDao.deleteAccess(access, "system");
+                userGroupService.deleteAutoHiddenGroup(
+                        access.getUserGroup().getId(), "system");
+            }
+            vcDao.deleteVirtualCorpus(vc);
+        }
+        else {
+            throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
+                    "Unauthorized operation for user: " + username, username);
+        }
+    }
+
     public void editVC (VirtualCorpusJson vcJson, String username)
             throws KustvaktException {
         ParameterChecker.checkIntegerValue(vcJson.getId(), "id");
@@ -252,28 +287,28 @@
                     name);
         }
 
-        if (type.equals(VirtualCorpusType.SYSTEM) 
-                && !username.equals("system")
+        if (type.equals(VirtualCorpusType.SYSTEM) && !username.equals("system")
                 && !adminDao.isAdmin(username)) {
             throw new KustvaktException(StatusCodes.AUTHORIZATION_FAILED,
                     "Unauthorized operation for user: " + username, username);
         }
 
         CorpusAccess requiredAccess;
-        if (isCached){
-            KoralCollectionQueryBuilder koral = new KoralCollectionQueryBuilder();
-            koral.with("referTo "+name);
+        if (isCached) {
+            KoralCollectionQueryBuilder koral =
+                    new KoralCollectionQueryBuilder();
+            koral.with("referTo " + name);
             String vcRef = koral.toJSON();
             if (DEBUG) {
                 jlog.debug("Determine vc access with vc ref: " + vcRef);
             }
             requiredAccess = determineRequiredAccess(vcRef);
         }
-        else{
+        else {
             requiredAccess = determineRequiredAccess(koralQuery);
         }
-        
-        if (DEBUG) jlog.debug("Storing VC "+name+"in the database ");
+
+        if (DEBUG) jlog.debug("Storing VC " + name + "in the database ");
         int vcId = 0;
         try {
             vcId = vcDao.createVirtualCorpus(name, type, requiredAccess,
@@ -486,6 +521,14 @@
         return vc;
     }
 
+    public VirtualCorpusDto retrieveVCByName (String username, String vcName,
+            String createdBy) throws KustvaktException {
+        VirtualCorpus vc = searchVCByName(username, vcName, createdBy);
+        String json = vc.getKoralQuery();
+        String statistics = krill.getStatistics(json);
+        return converter.createVirtualCorpusDto(vc, statistics);
+    }
+
     public VirtualCorpusDto searchVCById (String username, int vcId)
             throws KustvaktException {
 
diff --git a/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java b/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java
index 180e319..06d0d90 100644
--- a/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java
+++ b/full/src/main/java/de/ids_mannheim/korap/web/controller/VirtualCorpusController.java
@@ -136,6 +136,7 @@
     @GET
     @Path("{vcId}")
     @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+    @Deprecated
     public VirtualCorpusDto retrieveVC (
             @Context SecurityContext securityContext,
             @PathParam("vcId") int vcId) {
@@ -151,16 +152,50 @@
     }
 
     /**
-     * Lists not only private virtual corpora but all virtual corpora
-     * available to a user.
-     * 
-     * Users, except system admins, cannot list virtual corpora of
-     * other users. Thus, createdBy parameter is only relevant for
-     * requests from system admins.
+     * Returns the virtual corpus with the given name and creator.
      * 
      * @param securityContext
      * @param createdBy
-     *            username of virtual corpus creator (optional)
+     *            vc creator
+     * @param vcName
+     *            vc name
+     * @return the virtual corpus with the given name and creator.
+     */
+    @GET
+    @Path("{createdBy}/{vcName}")
+    @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
+    public VirtualCorpusDto retrieveVCByName (
+            @Context SecurityContext securityContext,
+            @PathParam("createdBy") String createdBy,
+            @PathParam("vcName") String vcName) {
+        TokenContext context =
+                (TokenContext) securityContext.getUserPrincipal();
+        try {
+            scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
+            return service.retrieveVCByName(context.getUsername(), vcName,
+                    createdBy);
+        }
+        catch (KustvaktException e) {
+            throw kustvaktResponseHandler.throwit(e);
+        }
+    }
+
+    /**
+     * Lists not only owned virtual corpora but all virtual corpora
+     * available to the authenticated user.
+     *
+     * System-admins can list available vc for a specific user by
+     * specifiying the username parameter.
+     * 
+     * Normal users cannot list virtual corpora
+     * available for other users. Thus, username parameter is optional
+     * and must be identical to the authenticated username.
+     * 
+     * 
+     * 
+     * @param securityContext
+     * @param username
+     *            a username (optional)
      * @return a list of virtual corpora
      */
     @GET
@@ -168,12 +203,13 @@
     @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
     public List<VirtualCorpusDto> listVCByUser (
             @Context SecurityContext securityContext,
-            @QueryParam("createdBy") String createdBy) {
+            @QueryParam("username") String username) {
         TokenContext context =
                 (TokenContext) securityContext.getUserPrincipal();
         try {
             scopeService.verifyScope(context, OAuth2Scope.VC_INFO);
-            return service.listVCByUser(context.getUsername(), createdBy);
+            return service.listAvailableVCForUser(context.getUsername(),
+                    username);
         }
         catch (KustvaktException e) {
             throw kustvaktResponseHandler.throwit(e);
@@ -248,6 +284,7 @@
      */
     @DELETE
     @Path("delete/{vcId}")
+    @Deprecated
     public Response deleteVC (@Context SecurityContext securityContext,
             @PathParam("vcId") int vcId) {
         TokenContext context =
@@ -263,6 +300,35 @@
     }
 
     /**
+     * Only the VC owner and system admins can delete VC. VCA admins
+     * can delete VC-accesses e.g. of project VC, but not the VC
+     * themselves.
+     * 
+     * @param securityContext
+     * @param createdBy
+     *            vc creator
+     * @param vcName
+     *            vc name
+     * @return HTTP status 200, if successful
+     */
+    @DELETE
+    @Path("{createdBy}/{vcName}")
+    public Response deleteVCByName (@Context SecurityContext securityContext,
+            @PathParam("createdBy") String createdBy,
+            @PathParam("vcName") String vcName) {
+        TokenContext context =
+                (TokenContext) securityContext.getUserPrincipal();
+        try {
+            scopeService.verifyScope(context, OAuth2Scope.DELETE_VC);
+            service.deleteVCByName(context.getUsername(), vcName, createdBy);
+        }
+        catch (KustvaktException e) {
+            throw kustvaktResponseHandler.throwit(e);
+        }
+        return Response.ok().build();
+    }
+
+    /**
      * VC can only be shared with a group, not individuals.
      * Only VCA admins are allowed to share VC and the VC must have
      * been created by themselves.
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
index 98444b6..b4f0194 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
@@ -73,7 +73,7 @@
     public void testListDoryVC () throws UniformInterfaceException,
             ClientHandlerException, KustvaktException {
         ClientResponse response = resource().path(API_VERSION).path("vc").path("list")
-                .queryParam("createdBy", "dory")
+                .queryParam("username", "dory")
                 .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
                 .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
                         .createBasicAuthorizationHeaderValue(admin, "pass"))