View Javadoc
1   /*
2    * This file is part of Waarp Project (named also Waarp or GG).
3    *
4    *  Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5    *  tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    *
8    *  All Waarp Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   *
13   * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   *
17   *  You should have received a copy of the GNU General Public License along with
18   * Waarp . If not, see <http://www.gnu.org/licenses/>.
19   */
20  
21  package org.waarp.openr66.protocol.http.restv2.dbhandlers;
22  
23  import com.fasterxml.jackson.databind.node.ArrayNode;
24  import com.fasterxml.jackson.databind.node.ObjectNode;
25  import io.cdap.http.AbstractHttpHandler;
26  import io.cdap.http.HttpResponder;
27  import io.netty.handler.codec.http.DefaultHttpHeaders;
28  import io.netty.handler.codec.http.HttpMethod;
29  import io.netty.handler.codec.http.HttpRequest;
30  import org.waarp.common.json.JsonHandler;
31  import org.waarp.common.logging.SysErrLogger;
32  import org.waarp.common.role.RoleDefault.ROLE;
33  import org.waarp.common.utility.ParametersChecker;
34  import org.waarp.openr66.context.task.SpooledInformTask;
35  import org.waarp.openr66.protocol.http.restv2.errors.RestError;
36  import org.waarp.openr66.protocol.http.restv2.errors.RestErrorException;
37  import org.waarp.openr66.protocol.http.restv2.utils.JsonUtils;
38  import org.waarp.openr66.protocol.http.restv2.utils.RestUtils;
39  
40  import javax.ws.rs.Consumes;
41  import javax.ws.rs.DefaultValue;
42  import javax.ws.rs.GET;
43  import javax.ws.rs.OPTIONS;
44  import javax.ws.rs.Path;
45  import javax.ws.rs.QueryParam;
46  import java.util.ArrayList;
47  import java.util.List;
48  
49  import static io.netty.handler.codec.http.HttpResponseStatus.*;
50  import static javax.ws.rs.core.HttpHeaders.*;
51  import static javax.ws.rs.core.MediaType.*;
52  import static org.waarp.openr66.protocol.http.restv2.RestConstants.*;
53  import static org.waarp.openr66.protocol.http.restv2.RestConstants.GetTransfersParams.*;
54  import static org.waarp.openr66.protocol.http.restv2.errors.RestErrors.*;
55  
56  /**
57   * This is the {@link AbstractHttpHandler} handling all requests made on the
58   * FileMonitor collection REST entry point.
59   */
60  @Path(FILE_MONITOR_HANDLER_URI)
61  public class SpooledHandler extends AbstractRestDbHandler {
62  
63    /**
64     * The content of the 'Allow' header sent when an 'OPTIONS' request is made
65     * on the handler.
66     */
67    private static final io.netty.handler.codec.http.HttpHeaders OPTIONS_HEADERS;
68  
69    static {
70      OPTIONS_HEADERS = new DefaultHttpHeaders();
71      final List<HttpMethod> allow = new ArrayList<HttpMethod>();
72      allow.add(HttpMethod.GET);
73      allow.add(HttpMethod.OPTIONS);
74      OPTIONS_HEADERS.add(ALLOW, allow);
75    }
76  
77    /**
78     * Initializes the handler with the given CRUD mask.
79     *
80     * @param crud the CRUD mask for this handler
81     */
82    public SpooledHandler(final byte crud) {
83      super(crud);
84    }
85  
86    /**
87     * Method called to obtain a list of FileMonitors entry matching the different
88     * filters given as parameters of the
89     * query. The response is sent as a JSON array containing all the requested
90     * entries, unless an unexpected
91     * error prevents it or if the request is invalid.
92     *
93     * @param request the HttpRequest made on the resource
94     * @param responder the HttpResponder which sends the reply to the request
95     * @param nameStr the name of the FileMonitor or empty for all
96     * @param statusStr 0 or empty for all, 1 for active ones, -1 for inactive
97     *     ones
98     * @param countOrder if true is specified, it turns out to be a "count"
99     *     request only of current files
100    */
101   @GET
102   @Consumes(APPLICATION_FORM_URLENCODED)
103   @RequiredRole(ROLE.READONLY)
104   public final void filterTransfer(final HttpRequest request,
105                                    final HttpResponder responder,
106                                    @QueryParam("name") @DefaultValue("")
107                                    final String nameStr,
108                                    @QueryParam(STATUS) @DefaultValue("")
109                                    final String statusStr,
110                                    @QueryParam(COUNT_ORDER) @DefaultValue("")
111                                    final String countOrder) {
112     checkSanity(nameStr, statusStr, countOrder);
113     boolean count = false;
114     try {
115       if (ParametersChecker.isNotEmpty(countOrder) &&
116           RestUtils.stringToBoolean(countOrder)) {
117         count = true;
118       }
119     } catch (final Exception ignore) {
120       // Ignore
121     }
122     final ArrayList<RestError> errors = new ArrayList<RestError>();
123     final String argName;
124     if (nameStr.trim().isEmpty()) {
125       argName = null;
126     } else {
127       argName = nameStr.trim();
128     }
129     int argStatus;
130     if (statusStr.trim().isEmpty()) {
131       argStatus = 0;
132     } else {
133       try {
134         argStatus = Integer.parseInt(statusStr.trim());
135       } catch (final NumberFormatException ignored) {
136         SysErrLogger.FAKE_LOGGER.ignoreLog(ignored);
137         errors.add(ILLEGAL_PARAMETER_VALUE(STATUS, statusStr));
138         argStatus = 0;
139       }
140     }
141     if (!errors.isEmpty()) {
142       throw new RestErrorException(errors);
143     }
144 
145     final ObjectNode responseObject = JsonHandler.createObjectNode();
146     if (count) {
147       final int nbFiles =
148           SpooledInformTask.buildSpooledJson(null, argStatus, argName);
149       final int nbEntries =
150           SpooledInformTask.getSpooledJsonEntriesNumber(argStatus, argName);
151       responseObject.put("totalResults", nbEntries);
152       responseObject.put("totalSubResults", nbFiles);
153     } else {
154       final ArrayNode arrayNode = JsonHandler.createArrayNode();
155       final int nbFiles =
156           SpooledInformTask.buildSpooledJson(arrayNode, argStatus, argName);
157       final ArrayNode resultList = responseObject.putArray("results");
158       resultList.addAll(arrayNode);
159       responseObject.put("totalResults", arrayNode.size());
160       responseObject.put("totalSubResults", nbFiles);
161     }
162     final String responseText = JsonUtils.nodeToString(responseObject);
163     responder.sendJson(OK, responseText);
164   }
165 
166   /**
167    * Method called to get a list of all allowed HTTP methods on this entry
168    * point. The HTTP methods are sent as
169    * an array in the reply's headers.
170    *
171    * @param request the HttpRequest made on the resource
172    * @param responder the HttpResponder which sends the reply to the
173    *     request
174    */
175   @OPTIONS
176   @Consumes(WILDCARD)
177   @RequiredRole(ROLE.NOACCESS)
178   public final void options(final HttpRequest request,
179                             final HttpResponder responder) {
180     responder.sendStatus(OK, OPTIONS_HEADERS);
181   }
182 }