Merge "Rewrite LoggerControllerTests"
[vid.git] / vid-app-common / src / main / java / org / onap / vid / controller / LoggerController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.controller;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.util.List;
26 import java.util.Objects;
27 import java.util.function.Supplier;
28 import java.util.stream.Collectors;
29 import java.util.stream.Stream;
30 import javax.servlet.http.HttpServletRequest;
31 import javax.ws.rs.InternalServerErrorException;
32 import javax.ws.rs.NotAuthorizedException;
33 import org.apache.commons.io.input.ReversedLinesFileReader;
34 import org.apache.commons.lang3.StringUtils;
35 import org.onap.portalsdk.core.controller.RestrictedBaseController;
36 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
37 import org.onap.vid.model.ExceptionResponse;
38 import org.onap.vid.roles.Role;
39 import org.onap.vid.roles.RoleProvider;
40 import org.onap.vid.utils.Streams;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.web.bind.annotation.ExceptionHandler;
44 import org.springframework.web.bind.annotation.GetMapping;
45 import org.springframework.web.bind.annotation.PathVariable;
46 import org.springframework.web.bind.annotation.RequestMapping;
47 import org.springframework.web.bind.annotation.RequestParam;
48 import org.springframework.web.bind.annotation.ResponseStatus;
49 import org.springframework.web.bind.annotation.RestController;
50
51
52 @RestController
53 @RequestMapping("logger")
54 public class LoggerController extends RestrictedBaseController {
55
56     private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(LoggerController.class);
57     private RoleProvider roleProvider;
58     private LogfilePathCreator logfilePathCreator;
59
60     @Autowired
61     public LoggerController(RoleProvider roleProvider, LogfilePathCreator logfilePathCreator) {
62         this.roleProvider = roleProvider;
63         this.logfilePathCreator = logfilePathCreator;
64     }
65
66     @GetMapping(value = "/{loggerName:audit|error|metrics}")
67     public String getLog(@PathVariable String loggerName, HttpServletRequest request,
68                          @RequestParam(value="limit", defaultValue = "5000") Integer limit) throws IOException {
69
70         List<Role> roles = roleProvider.getUserRoles(request);
71         boolean userPermitted = roleProvider.userPermissionIsReadLogs(roles);
72         if (!userPermitted) {
73             throw new NotAuthorizedException("User not authorized to get logs");
74         }
75
76         String logfilePath = logfilePathCreator.getLogfilePath(loggerName);
77         try (final ReversedLinesFileReader reader = new ReversedLinesFileReader(new File(logfilePath))) {
78             Supplier<String> reverseLinesSupplier = () -> {
79                 try {
80                     return reader.readLine();
81                 } catch (NullPointerException e) {
82                     // EOF Reached
83                     return null;
84                 } catch (IOException e) {
85                     throw new InternalServerErrorException("error while reading " + logfilePath, e);
86                 }
87             };
88
89             return Streams.takeWhile(
90                     Stream.generate(reverseLinesSupplier),
91                     line -> !StringUtils.contains(line, "Logging is started"))
92                     .limit(limit)
93                     .limit(5_000)
94                     .filter(Objects::nonNull)
95                     .collect(Collectors.joining("\n"));
96         }
97     }
98
99     @ExceptionHandler({ NotAuthorizedException.class })
100     @ResponseStatus(HttpStatus.UNAUTHORIZED)
101     public String notAuthorizedHandler(NotAuthorizedException e) {
102         return "UNAUTHORIZED";
103     }
104
105     @ExceptionHandler({ IOException.class, InternalServerErrorException.class })
106     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
107     public ExceptionResponse ioExceptionHandler(Exception e) {
108         return ControllersUtils.handleException(e, LOGGER);
109     }
110
111 }