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  package org.waarp.openr66.protocol.http.rest.handler;
21  
22  import com.fasterxml.jackson.core.JsonParseException;
23  import com.fasterxml.jackson.databind.JsonMappingException;
24  import io.netty.buffer.ByteBuf;
25  import io.netty.buffer.Unpooled;
26  import io.netty.channel.ChannelFuture;
27  import io.netty.channel.ChannelHandlerContext;
28  import io.netty.handler.codec.http.HttpHeaderNames;
29  import io.netty.handler.codec.http.HttpResponse;
30  import io.netty.handler.codec.http.HttpResponseStatus;
31  import io.netty.handler.codec.http.multipart.FileUpload;
32  import org.waarp.common.exception.InvalidArgumentException;
33  import org.waarp.common.logging.WaarpLogger;
34  import org.waarp.common.logging.WaarpLoggerFactory;
35  import org.waarp.common.utility.ParametersChecker;
36  import org.waarp.common.utility.WaarpStringUtils;
37  import org.waarp.gateway.kernel.exception.HttpForbiddenRequestException;
38  import org.waarp.gateway.kernel.exception.HttpIncorrectRequestException;
39  import org.waarp.gateway.kernel.rest.HttpRestHandler;
40  import org.waarp.gateway.kernel.rest.HttpRestHandler.METHOD;
41  import org.waarp.gateway.kernel.rest.RestArgument;
42  import org.waarp.gateway.kernel.rest.RestConfiguration;
43  import org.waarp.gateway.kernel.rest.RestMethodHandler;
44  import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException;
45  import org.waarp.openr66.protocol.http.rest.HttpRestR66Handler;
46  import org.waarp.openr66.protocol.localhandler.packet.json.JsonPacket;
47  
48  import java.io.IOException;
49  import java.nio.charset.UnsupportedCharsetException;
50  
51  import static org.waarp.openr66.context.R66FiniteDualStates.*;
52  
53  /**
54   * Common method implementation for Action Rest R66 handlers
55   */
56  public abstract class HttpRestAbstractR66Handler extends RestMethodHandler {
57  
58    /**
59     * Internal Logger
60     */
61    private static final WaarpLogger logger =
62        WaarpLoggerFactory.getLogger(HttpRestAbstractR66Handler.class);
63  
64    public enum ACTIONS_TYPE {
65      OPTIONS, GetBandwidth, SetBandwidth, ExecuteBusiness, ExportConfig,
66      ImportConfig, GetInformation, GetTransferInformation, GetLog,
67      ShutdownOrBlock, GetStatus, RestartTransfer, StopOrCancelTransfer,
68      CreateTransfer
69    }
70  
71    /**
72     * @param path
73     * @param method
74     */
75    protected HttpRestAbstractR66Handler(final String path,
76                                         final RestConfiguration config,
77                                         final METHOD... method) {
78      super(path, path, true, config, method);
79    }
80  
81    @Override
82    public final void checkHandlerSessionCorrectness(
83        final HttpRestHandler handler, final RestArgument arguments,
84        final RestArgument result) throws HttpForbiddenRequestException {
85      try {
86        HttpRestV1Utils.checkSanity(arguments);
87      } catch (final InvalidArgumentException e) {
88        throw new HttpForbiddenRequestException("Issue on values", e);
89      }
90      logger.debug("debug");
91    }
92  
93    @Override
94    public final void getFileUpload(final HttpRestHandler handler,
95                                    final FileUpload data,
96                                    final RestArgument arguments,
97                                    final RestArgument result) {
98      // should not be
99      logger.debug("debug: {}:{}", data.getName(), data.getHttpDataType().name());
100   }
101 
102   protected final void setError(final HttpRestHandler handler,
103                                 final RestArgument result,
104                                 final HttpResponseStatus code) {
105     handler.setStatus(HttpResponseStatus.BAD_REQUEST);
106     handler.setWillClose(false);
107     result.setResult(code);
108   }
109 
110   protected final void setError(final HttpRestHandler handler,
111                                 final RestArgument result,
112                                 final JsonPacket packet,
113                                 final HttpResponseStatus code) {
114     handler.setStatus(HttpResponseStatus.BAD_REQUEST);
115     result.setResult(code);
116     if (packet != null) {
117       try {
118         result.addResult(packet.createObjectNode());
119       } catch (final OpenR66ProtocolPacketException ignored) {
120         // ignore
121       }
122     }
123   }
124 
125   protected final void setOk(final HttpRestHandler handler,
126                              final RestArgument result, final JsonPacket packet,
127                              final HttpResponseStatus code) {
128     handler.setStatus(HttpResponseStatus.OK);
129     result.setResult(code);
130     if (packet != null) {
131       try {
132         result.addResult(packet.createObjectNode());
133       } catch (final OpenR66ProtocolPacketException e) {
134         result.setDetail("serialization impossible");
135       }
136     }
137   }
138 
139   @Override
140   public HttpResponseStatus handleException(final HttpRestHandler handler,
141                                             final RestArgument arguments,
142                                             final RestArgument result,
143                                             final Object body,
144                                             final Exception exception) {
145     ((HttpRestR66Handler) handler).getServerHandler().getSession()
146                                   .newState(ERROR);
147     return super.handleException(handler, arguments, result, body, exception);
148   }
149 
150   @Override
151   public final ChannelFuture sendResponse(final HttpRestHandler handler,
152                                           final ChannelHandlerContext ctx,
153                                           final RestArgument arguments,
154                                           final RestArgument result,
155                                           final Object body,
156                                           final HttpResponseStatus status) {
157     final String answer = result.toString();
158     final ByteBuf buffer =
159         Unpooled.wrappedBuffer(answer.getBytes(WaarpStringUtils.UTF8));
160     final HttpResponse response = handler.getResponse(buffer);
161     response.headers()
162             .set(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
163     if (status == HttpResponseStatus.UNAUTHORIZED) {
164       return ctx.writeAndFlush(response);
165     }
166     response.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json");
167     response.headers().add(HttpHeaderNames.REFERER, handler.getRequest().uri());
168     logger.debug("Will write: {}", body);
169     final ChannelFuture future = ctx.writeAndFlush(response);
170     if (handler.isWillClose()) {
171       logger.debug("Will close session in HttpRestAbstractR66Handler");
172       return future;
173     }
174     return null;
175   }
176 
177   @Override
178   public final Object getBody(final HttpRestHandler handler, final ByteBuf body,
179                               final RestArgument arguments,
180                               final RestArgument result)
181       throws HttpIncorrectRequestException {
182     final JsonPacket packet;
183     try {
184       final String json = body.toString(WaarpStringUtils.UTF8);
185       try {
186         ParametersChecker.checkSanityString(json);
187       } catch (final InvalidArgumentException e) {
188         throw new HttpIncorrectRequestException("Issue on values", e);
189       }
190       packet = JsonPacket.createFromBuffer(json);
191     } catch (final JsonParseException e) {
192       logger.warn("Error: " + body.toString(WaarpStringUtils.UTF8) + " : {}",
193                   e.getMessage());
194       throw new HttpIncorrectRequestException(e);
195     } catch (final JsonMappingException e) {
196       logger.warn("Error" + " : {}", e.getMessage());
197       throw new HttpIncorrectRequestException(e);
198     } catch (final IOException e) {
199       logger.warn("Error" + " : {}", e.getMessage());
200       throw new HttpIncorrectRequestException(e);
201     } catch (final UnsupportedCharsetException e) {
202       logger.warn("Error" + " : {}", e.getMessage());
203       throw new HttpIncorrectRequestException(e);
204     }
205     return packet;
206   }
207 }