source: DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/rest/DebugResource.java @ 6038

Last change on this file since 6038 was 6038, checked in by olhsha@mpi.nl, 9 years ago

Javadoc annotations are completed.

File size: 10.0 KB
Line 
1/*
2 * Copyright (C) 2013 DASISH
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18package eu.dasish.annotation.backend.rest;
19
20import eu.dasish.annotation.backend.BackendConstants;
21import eu.dasish.annotation.backend.Helpers;
22import eu.dasish.annotation.backend.NotInDataBaseException;
23import eu.dasish.annotation.backend.Resource;
24import eu.dasish.annotation.schema.AnnotationInfo;
25import eu.dasish.annotation.schema.AnnotationInfoList;
26import eu.dasish.annotation.schema.ObjectFactory;
27import java.io.BufferedReader;
28import java.io.FileReader;
29import java.io.IOException;
30import java.util.ArrayList;
31import java.util.List;
32import java.util.Random;
33import java.util.UUID;
34import javax.servlet.http.HttpServletResponse;
35import javax.ws.rs.GET;
36import javax.ws.rs.PUT;
37import javax.ws.rs.Path;
38import javax.ws.rs.PathParam;
39import javax.ws.rs.Produces;
40import javax.ws.rs.core.MediaType;
41import javax.xml.bind.JAXBElement;
42import org.springframework.stereotype.Component;
43import org.springframework.transaction.annotation.Transactional;
44
45/**
46 * REST class for GETting information useful for debugging the back-end or a front-end;
47 * Every REST method in the case of successful completion of its action outputs the declared output type
48 * (a JAXB-element or a message string) or sends a HTTP-error with the corresponding diagnostics otherwise;
49 * The class is used only by "admin" and "developer" principals; these account types are set in "principal" table.
50 * @author olhsha
51 */
52@Component
53@Path("/debug")
54public class DebugResource extends ResourceResource {
55
56    public static final String developer = "developer";
57   
58    /**
59     *
60     * @return an arbitrary UUID string.
61     */
62    @GET
63    @Produces(MediaType.TEXT_PLAIN)
64    @Path("uuid")
65    public String generateUUID(){
66       return (Helpers.generateUUID()).toString();
67    }
68   
69    /**
70     *
71     * @return An {@link AnnotationInfoList}-element containing the list of {@link AnnotationInfo} objects of ALL the annotations,
72     * with the latest (youngest) annotation on the top.
73     * @throws IOException if sending the error fails.
74     */
75    @GET
76    @Produces(MediaType.TEXT_XML)
77    @Path("annotations")
78    @Transactional(readOnly = true)
79    public JAXBElement<AnnotationInfoList> getAllAnnotations() throws IOException {
80        Number remotePrincipalID = this.getPrincipalID();
81        if (remotePrincipalID == null) {
82            return new ObjectFactory().createAnnotationInfoList(new AnnotationInfoList());
83        }
84        String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
85        if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
86            final AnnotationInfoList annotationInfoList = dbDispatcher.getAllAnnotationInfos();
87            return new ObjectFactory().createAnnotationInfoList(annotationInfoList);
88        } else {
89            this.DEVELOPER_RIGHTS_EXPECTED();
90            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
91            return new ObjectFactory().createAnnotationInfoList(new AnnotationInfoList());
92        }
93    }
94   
95   
96    /**
97     *
98     * @param n # of strings.
99     * @return the latest n strings of the dasish database log file.
100     * @throws IOException if sending the error fails.
101     */
102    @GET
103    @Produces(MediaType.TEXT_PLAIN)
104    @Path("/logDatabase/{n}")
105    @Transactional(readOnly = true)
106    public String getDasishBackendLog(@PathParam("n") int n) throws IOException {
107        Number remotePrincipalID = this.getPrincipalID();
108        if (remotePrincipalID == null) {
109            return " ";
110        }
111        String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
112        if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
113            return logFile("eu.dasish.annotation.backend.logDatabaseLocation", n);
114        } else {
115            this.DEVELOPER_RIGHTS_EXPECTED();
116            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
117            return "Coucou.";
118        }
119    }
120
121    /**
122     *
123     * @return the remote ID of the logged in user.
124     */
125    @GET
126    @Produces(MediaType.TEXT_PLAIN)
127    @Path("/remoteID")
128    @Transactional(readOnly = true)
129    public String getLoggedInRemoteID() {
130        return (httpServletRequest.getRemoteUser() != null) ? httpServletRequest.getRemoteUser() : "Null";
131    }
132
133   /**
134    *
135    * @param n # of strings
136    * @return the last n strings of the dasish server logger (non-SQL-request logs).
137    * @throws IOException if sending the error fails.
138    */
139    @GET
140    @Produces(MediaType.TEXT_PLAIN)
141    @Path("/logServer/{n}")
142    @Transactional(readOnly = true)
143    public String getDasishServerLog(@PathParam("n") int n) throws IOException {
144        Number remotePrincipalID = this.getPrincipalID();
145        if (remotePrincipalID == null) {
146            return " ";
147        }
148        String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
149        if (typeOfAccount.equals(admin) || typeOfAccount.equals(developer)) {
150            return logFile("eu.dasish.annotation.backend.logServerLocation", n);
151        } else {
152            this.DEVELOPER_RIGHTS_EXPECTED();
153            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
154            return "Coucou.";
155        }
156    }
157
158    /**
159     *
160     * @param principalId the external UUID of a principal whose account type must be updated,
161     * @param account the new account type (admin, developer, user).
162     * @return a message if the account has been updated or not.
163     * @throws IOException if sending the error fails.
164     */
165    @PUT
166    @Produces(MediaType.TEXT_XML)
167    @Path("/account/{principalId}/make/{account}")
168    @Transactional(readOnly = true)
169    public String updatePrincipalsAccount(@PathParam("principalId") String principalId, @PathParam("account") String account) throws IOException {
170        Number remotePrincipalID = this.getPrincipalID();
171        if (remotePrincipalID == null) {
172            return " ";
173        }
174        String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
175        if (typeOfAccount.equals(admin)) {
176            try {
177                final boolean update = dbDispatcher.updateAccount(UUID.fromString(principalId), account);
178                return (update ? "The account is updated" : "The account is not updated, see the log.");
179            } catch (NotInDataBaseException e) {
180                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
181                return e.toString();
182            }
183        } else {
184            this.ADMIN_RIGHTS_EXPECTED();
185            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
186            return "Coucou.";
187        }
188
189    }
190   
191    /**
192     *
193     * @param resource a type of resource (annotation, target, cached representation, principal, notebook).
194     * @param oldExternalId the old external UUID of the resource.
195     * @param newExternalId the new UUID of the resource
196     * @return the message if the "newExternalIdentifier" has replaced the "oldExternalIdentifier" or not,
197     * @throws IOException is sending the error fails.
198     */
199    @PUT
200    @Produces(MediaType.TEXT_XML)
201    @Path("/resource/{resource}/{oldId: " + BackendConstants.regExpIdentifier + "}/newid/{newId:" + BackendConstants.regExpIdentifier + "}")
202    public String updateResourceIdentifier(@PathParam("resource") String resource, @PathParam("oldId") String oldExternalId, @PathParam("newId") String newExternalId) throws IOException {
203        Number remotePrincipalID = this.getPrincipalID();
204        if (remotePrincipalID == null) {
205            return "null inlogged principal";
206        }
207        String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
208        if (typeOfAccount.equals(admin)) {
209            try {
210                final boolean update = dbDispatcher.updateResourceIdentifier(Resource.valueOf(resource), UUID.fromString(oldExternalId), UUID.fromString(newExternalId));
211                return (update ? "The identifier is updated" : "The account is not updated, see the log.");
212            } catch (NotInDataBaseException e) {
213                httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
214                return e.toString();
215            }
216        } else {
217            this.ADMIN_RIGHTS_EXPECTED();
218            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
219            return "Dooooeeeii!!";
220        }
221
222    }
223
224    ///////////////////////////////////////////////////
225    private String logFile(String location, int n) throws IOException {
226        BufferedReader read = new BufferedReader(new FileReader(context.getInitParameter(location)));
227        List<String> lines = new ArrayList<String>();
228        StringBuilder result = new StringBuilder();
229        int i = 0;
230        String line;
231        while ((line = read.readLine()) != null) {
232            lines.add(line);
233            i++;
234        }
235        // want to read the last n rows, i.e. the rows (i-1), (i-1-1),...,(i-1-(n-1))
236        int last = (i > n) ? (i - n) : 0;
237        for (int j = i - 1; j >= last; j--) {
238            result.append(lines.get(j)).append("\n");
239        }
240        return result.toString();
241    }
242   
243    private void DEVELOPER_RIGHTS_EXPECTED() throws IOException {
244        loggerServer.debug("The request can be performed only by the principal with the developer's or admin rights. The logged in principal does not have either developer's or admin rights.");
245    }
246}
Note: See TracBrowser for help on using the repository browser.