Project

General

Profile

1
package eu.dnetlib.repo.manager.controllers;
2

    
3
import eu.dnetlib.domain.data.PiwikInfo;
4
import eu.dnetlib.repo.manager.domain.OrderByField;
5
import eu.dnetlib.repo.manager.domain.OrderByType;
6
import eu.dnetlib.repo.manager.domain.Paging;
7
import eu.dnetlib.repo.manager.service.PiWikServiceImpl;
8
import eu.dnetlib.repo.manager.service.RepositoryService;
9
import eu.dnetlib.repo.manager.domain.RepositoryServiceException;
10
import io.swagger.annotations.Api;
11
import io.swagger.annotations.ApiImplicitParam;
12
import io.swagger.annotations.ApiImplicitParams;
13
import org.apache.log4j.Logger;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.core.io.FileSystemResource;
16
import org.springframework.http.MediaType;
17
import org.springframework.http.ResponseEntity;
18
import org.springframework.security.access.prepost.PreAuthorize;
19
import org.springframework.web.bind.annotation.*;
20

    
21
import javax.servlet.http.HttpServletRequest;
22
import javax.servlet.http.HttpServletResponse;
23
import java.io.FileNotFoundException;
24
import java.io.IOException;
25
import java.io.PrintWriter;
26
import java.nio.file.Files;
27
import java.nio.file.Path;
28
import java.text.SimpleDateFormat;
29
import java.util.Date;
30
import java.util.List;
31

    
32
@RestController
33
@RequestMapping(value = "/piwik")
34
@Api(description = "Piwik API",  tags = {"piwik"})
35
public class PiWikController {
36

    
37
    private static final Logger LOGGER = Logger
38
            .getLogger(PiWikController.class);
39

    
40
    @Autowired
41
    private PiWikServiceImpl piWikService;
42

    
43
    @Autowired
44
    private RepositoryService repositoryService;
45

    
46

    
47
    @RequestMapping(value = "/getPiwikSiteForRepo/{repositoryId}" , method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
48
    @ResponseBody
49
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or ((@repositoryService.getRepositoryById(#repositoryId).registeredBy==authentication.userInfo.email or @repositoryService.getRepositoryById(#repositoryId).registeredBy=='null') and hasRole('ROLE_USER'))")
50
    public PiwikInfo getPiwikSiteForRepo(@PathVariable("repositoryId") String repositoryId) {
51
        return piWikService.getPiwikSiteForRepo(repositoryId);
52
    }
53

    
54
    @RequestMapping(value = "/savePiwikInfo" , method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
55
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or ((@repositoryService.getRepositoryById(#piwikInfo.repositoryId).registeredBy==authentication.userInfo.email or @repositoryService.getRepositoryById(#piwikInfo.repositoryId).registeredBy=='null') and hasRole('ROLE_USER'))")
56
    public PiwikInfo savePiwikInfo(@RequestBody PiwikInfo piwikInfo) {
57
        return piWikService.savePiwikInfo(piwikInfo);
58
    }
59

    
60
    @RequestMapping(value = "/getPiwikSitesForRepos" , method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
61
    @ApiImplicitParams({
62
            @ApiImplicitParam(name = "from", dataType = "number", paramType = "query"),
63
            @ApiImplicitParam(name = "quantity", dataType = "number", paramType = "query"),
64
            @ApiImplicitParam(name = "order", dataType = "eu.dnetlib.repo.manager.domain.OrderByType", paramType = "query"),
65
            @ApiImplicitParam(name = "orderField", dataType = "eu.dnetlib.repo.manager.domain.OrderByField", paramType = "query"),
66
            @ApiImplicitParam(name = "searchField", dataType = "string", paramType = "query"),
67
    })
68
    public Paging<PiwikInfo> getPiwikSitesForRepos(
69
            @RequestParam(value = "from",required=false,defaultValue = "0") int from,
70
            @RequestParam(value = "quantity",required=false,defaultValue = "100") int quantity,
71
            @RequestParam(value = "order",required=false,defaultValue = "DSC") OrderByType orderType,
72
            @RequestParam(value = "orderField", required = false, defaultValue = "REPOSITORY_NAME") OrderByField orderField,
73
            @RequestParam(value = "searchField", required = false, defaultValue = "") String searchField
74

    
75
    ){
76
        Paging<PiwikInfo> results = new Paging<>();
77
        List<PiwikInfo> returning = piWikService.getPiwikSitesForRepos(orderField,orderType,from,quantity,searchField);
78
        results.setFrom(from);
79
        results.setTo(from + returning.size());
80
        results.setTotal(piWikService.getPiwikSitesTotals(searchField));
81
        results.setResults(returning);
82
        return results;
83
    }
84
    @ApiImplicitParams({
85
            @ApiImplicitParam(name = "from", dataType = "number", paramType = "query"),
86
            @ApiImplicitParam(name = "quantity", dataType = "number", paramType = "query"),
87
            @ApiImplicitParam(name = "order", dataType = "eu.dnetlib.repo.manager.domain.OrderByType", paramType = "query"),
88
            @ApiImplicitParam(name = "searchField", dataType = "eu.dnetlib.repo.manager.domain.OrderByField", paramType = "query"),
89
            @ApiImplicitParam(name = "orderField", dataType = "string", paramType = "query"),
90
    })
91
    @RequestMapping(value = "/getPiwikSitesForRepos/csv" , method = RequestMethod.GET,produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
92
    @ResponseBody
93
    public FileSystemResource getPiwikSitesForReposToCsv(
94
            @RequestParam(value = "from",required=false,defaultValue = "0") int from,
95
            @RequestParam(value = "quantity",required=false,defaultValue = "10000") int quantity,
96
            @RequestParam(value = "order",required=false,defaultValue = "DSC") OrderByType orderType,
97
            @RequestParam(value = "orderField", required = false, defaultValue = "REPOSITORY_NAME") OrderByField orderField,
98
            @RequestParam(value = "searchField", required = false, defaultValue = "") String searchField,
99
            HttpServletResponse response,
100
            HttpServletRequest request
101
    ) throws IOException {
102

    
103
        Path p = Files.createTempFile("exportingCsv-", new Date().toString());
104
        List<PiwikInfo> returning = piWikService.getPiwikSitesForRepos(orderField,orderType,0,10000,searchField);
105
        try (PrintWriter writer = new PrintWriter(p.toFile())) {
106

    
107
            StringBuilder sb = new StringBuilder();
108
            sb.append(" Repository ID , Repository name, Country, Site ID, Authentication token, Creation date, Requestor full name, Requestor email, Validated, Validation date, Comment \n");
109

    
110
            for(PiwikInfo piwikInfo : returning){
111
                sb.append(
112
                        (piwikInfo.getRepositoryId() == null ? "," : piwikInfo.getRepositoryId()+ ",")+
113
                                (piwikInfo.getRepositoryName() == null ? "," : piwikInfo.getRepositoryName()+ ",")+
114
                                (piwikInfo.getCountry() == null ? "," : piwikInfo.getCountry()+ ",")+
115
                                (piwikInfo.getSiteId() == null ? "," : piwikInfo.getSiteId()+ ",") +
116
                                (piwikInfo.getAuthenticationToken() == null ? "," : piwikInfo.getAuthenticationToken()+ ",")+
117
                                (piwikInfo.getCreationDate() == null ? "," : piwikInfo.getCreationDate().toString()+ ",") +
118
                                (piwikInfo.getRequestorName() == null ? "," : piwikInfo.getRequestorName()+ ",") +
119
                                (piwikInfo.getRequestorEmail() == null ? "," : piwikInfo.getRequestorEmail()+ ",")+
120
                                piwikInfo.isValidated() + "," +
121
                                (piwikInfo.getValidationDate() == null ? "," : piwikInfo.getValidationDate().toString()+ ",") +
122
                                (piwikInfo.getComment() == null ? "\n" : piwikInfo.getComment()+ "\n")
123

    
124
                );
125
            }
126
            writer.write(sb.toString());
127

    
128
        } catch (FileNotFoundException e) {
129
            LOGGER.error(e.getMessage());
130
        }
131

    
132

    
133
        String mimeType = request.getServletContext().getMimeType(p.toFile().getAbsolutePath());
134
        if (mimeType == null) {
135
            mimeType = "application/octet-stream";
136
        }
137
        response.setContentType(mimeType);
138
        response.setContentLength((int) p.toFile().length());
139

    
140

    
141
        String headerKey = "Content-Disposition";
142
        SimpleDateFormat sdfDate = new SimpleDateFormat("ddMMyyyy");//dd/MM/yyyy
143
        Date now = new Date();
144
        String strDate = sdfDate.format(now);
145
        String headerValue = String.format("attachment; filename=\"csv-%s.csv\"",
146
                strDate);
147
        response.setHeader(headerKey, headerValue);
148

    
149

    
150
        return new FileSystemResource(p.toFile());
151

    
152
    }
153

    
154

    
155
    @RequestMapping(value = "/approvePiwikSite/{repositoryId}" , method = RequestMethod.GET)
156
    @ResponseBody
157
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN')")
158
    public ResponseEntity<Object> approvePiwikSite(@PathVariable("repositoryId") String repositoryId) {
159
        return piWikService.approvePiwikSite(repositoryId);
160
    }
161

    
162
    @RequestMapping(value = "/getOpenaireId/{repositoryId}" , method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
163
    @ResponseBody
164
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or ((@repositoryService.getRepositoryById(#repositoryId).registeredBy==authentication.userInfo.email or @repositoryService.getRepositoryById(#repositoryId).registeredBy=='null') and hasRole('ROLE_USER'))")
165
    public String getOpenaireId(String repositoryid){
166
        return piWikService.getOpenaireId(repositoryid);
167
    }
168

    
169
    @RequestMapping(value = "/markPiwikSiteAsValidated/{repositoryId}" , method = RequestMethod.POST,
170
            consumes = MediaType.APPLICATION_JSON_VALUE)
171
    @ResponseBody
172
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN')")
173
    public ResponseEntity<Object> markPiwikSiteAsValidated(@PathVariable("repositoryId") String repositoryId) throws RepositoryServiceException {
174
        return piWikService.markPiwikSiteAsValidated(repositoryId);
175
    }
176

    
177
    @RequestMapping(value = "/enableMetricsForRepository", method = RequestMethod.POST,
178
            consumes = MediaType.APPLICATION_JSON_VALUE)
179
    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_PROVIDE_ADMIN') or (hasRole('ROLE_USER') and #piwikInfo.requestorEmail == authentication.userInfo.email)")
180
    public PiwikInfo enableMetricsForRepository(@RequestParam("officialName") String officialName,
181
                                                @RequestParam("repoWebsite") String repoWebsite,
182
                                                @RequestBody PiwikInfo piwikInfo) throws RepositoryServiceException {
183
        return piWikService.enableMetricsForRepository(officialName, repoWebsite, piwikInfo);
184
    }
185

    
186

    
187
}
(5-5/11)