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.http.protocol;
22  
23  import org.waarp.common.command.exception.CommandAbstractException;
24  import org.waarp.common.database.data.AbstractDbData.UpdatedInfo;
25  import org.waarp.common.database.exception.WaarpDatabaseException;
26  import org.waarp.common.database.exception.WaarpDatabaseNoDataException;
27  import org.waarp.common.logging.WaarpLogger;
28  import org.waarp.common.logging.WaarpLoggerFactory;
29  import org.waarp.http.protocol.servlet.HttpAuthent;
30  import org.waarp.openr66.context.ErrorCode;
31  import org.waarp.openr66.context.R66BusinessInterface;
32  import org.waarp.openr66.context.R66FiniteDualStates;
33  import org.waarp.openr66.context.R66Session;
34  import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException;
35  import org.waarp.openr66.database.data.DbRule;
36  import org.waarp.openr66.database.data.DbTaskRunner;
37  import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP;
38  import org.waarp.openr66.pojo.Transfer;
39  import org.waarp.openr66.protocol.configuration.Configuration;
40  
41  import static org.waarp.openr66.context.R66FiniteDualStates.*;
42  
43  /**
44   * Common part for HttpSession for both download and upload
45   */
46  public class HttpSessionAbstract implements HttpSession {
47    private static final WaarpLogger logger =
48        WaarpLoggerFactory.getLogger(HttpSessionAbstract.class);
49  
50    protected final R66Session session;
51    protected final HttpAuthent authent;
52  
53    public HttpSessionAbstract(final HttpAuthent authent) {
54      this.session = new R66Session(false);
55      this.authent = authent;
56    }
57  
58  
59    /**
60     * Method to check authentication
61     *
62     * @param httpSession
63     * @param session
64     * @param authent
65     *
66     * @return the Business associated with this Authent
67     *
68     * @throws IllegalArgumentException
69     */
70    protected R66BusinessInterface checkAuthentR66Business(
71        final HttpSession httpSession, final R66Session session,
72        final HttpAuthent authent) throws IllegalArgumentException {
73      session.setBusinessObject(
74          Configuration.configuration.getR66BusinessFactory()
75                                     .getBusinessInterface(session));
76      final R66BusinessInterface business = session.getBusinessObject();
77      session.newState(R66FiniteDualStates.STARTUP);
78      try {
79        if (business != null) {
80          business.checkAtStartup(session);
81        }
82      } catch (final OpenR66RunnerErrorException e) {
83        httpSession.error(e, business);
84      }
85      authent.checkAuthent(this, session);
86      try {
87        if (business != null) {
88          business.checkAtAuthentication(session);
89        }
90      } catch (final OpenR66RunnerErrorException e) {
91        httpSession.error(e, business);
92      }
93      session.newState(R66FiniteDualStates.AUTHENTR);
94      session.newState(R66FiniteDualStates.AUTHENTD);
95      return business;
96    }
97  
98    /**
99     * Initialize the DbTaskRunner for this user and rulename
100    *
101    * @param user
102    * @param filename
103    * @param rulename
104    * @param identifier
105    * @param comment
106    * @param chunkSize
107    * @param business
108    * @param uploadMode
109    *
110    * @return the DbTaskRunner, potentially new
111    *
112    * @throws IllegalArgumentException
113    */
114   protected final DbTaskRunner getDbTaskRunner(final String user,
115                                                final String filename,
116                                                final String rulename,
117                                                final long identifier,
118                                                final String comment,
119                                                final int chunkSize,
120                                                final R66BusinessInterface business,
121                                                final boolean uploadMode)
122       throws IllegalArgumentException {
123     session.newState(REQUESTR);
124     session.setBlockSize(chunkSize);
125 
126     DbRule rule = null;
127     try {
128       rule = new DbRule(rulename);
129     } catch (final WaarpDatabaseException e) {
130       error(e, business);
131       throw new IllegalArgumentException(e);
132     }
133     final String requested = Configuration.configuration.getHostId();
134     DbTaskRunner runner = null;
135     try {
136       // Try to reload it
137       runner = new DbTaskRunner(session, rule, identifier, user, requested);
138       runner.setSender(!uploadMode);
139       logger.debug("{} {} {}", identifier, user, requested);
140       if (runner.isAllDone()) {
141         error(new IllegalArgumentException("Already finished"), business);
142       }
143     } catch (final WaarpDatabaseNoDataException e) {
144       // Not found so create it
145       try {
146         final Transfer transfer =
147             new Transfer(user, rulename, rule.getMode(), !uploadMode, filename,
148                          comment, chunkSize);
149         transfer.setRequested(requested);
150         transfer.setRequester(user);
151         transfer.setId(identifier);
152         runner = new DbTaskRunner(transfer);
153         runner.insert();
154         runner.select();
155         runner.setSender(!uploadMode);
156         logger.debug("{} {} {}", identifier, user, requested);
157       } catch (final WaarpDatabaseException ex) {
158         error(ex, business);
159         throw new IllegalArgumentException(e);
160       }
161     } catch (final WaarpDatabaseException e) {
162       error(e, business);
163       throw new IllegalArgumentException(e);
164     }
165     runner.setOriginalFilename(filename);
166     runner.setFilename(filename);
167     runner.restart(false);
168     try {
169       session.setRunner(runner);
170       session.setFileBeforePreRunner();
171     } catch (final OpenR66RunnerErrorException e) {
172       if (runner.getErrorInfo() == ErrorCode.InitOk ||
173           runner.getErrorInfo() == ErrorCode.PreProcessingOk ||
174           runner.getErrorInfo() == ErrorCode.TransferOk) {
175         runner.setErrorExecutionStatus(ErrorCode.ExternalOp);
176       }
177       try {
178         runner.saveStatus();
179       } catch (final OpenR66RunnerErrorException e1) {
180         logger.error("Cannot save Status: " + runner + ": {}", e1.getMessage());
181       }
182       runner.clean();
183       error(e, business);
184     }
185     session.setReady(true);
186     session.newState(REQUESTD);
187     try {
188       runner.saveStatus();
189     } catch (final OpenR66RunnerErrorException e1) {
190       logger.error("Cannot save Status: " + runner + ": {}", e1.getMessage());
191     }
192     return runner;
193   }
194 
195   @Override
196   public void error(final Exception e, final R66BusinessInterface business)
197       throws IllegalArgumentException {
198     logger.error(e.getMessage());
199     if (business != null) {
200       business.checkAtError(session);
201     }
202     session.newState(R66FiniteDualStates.ERROR);
203     if (session.getRunner() != null) {
204       final DbTaskRunner runner = session.getRunner();
205       runner.setErrorExecutionStatus(ErrorCode.TransferError);
206       runner.setErrorTask();
207       try {
208         runner.run();
209         runner.saveStatus();
210       } catch (final OpenR66RunnerErrorException e1) {
211         logger.debug(e1);
212       }
213     }
214     throw new IllegalArgumentException(e);
215   }
216 
217   /**
218    * Runs pre tasks
219    *
220    * @param business
221    * @param runner
222    *
223    * @throws IllegalArgumentException
224    */
225   protected final void preTasks(final R66BusinessInterface business,
226                                 final DbTaskRunner runner)
227       throws IllegalArgumentException {
228     runner.reset();
229     runner.changeUpdatedInfo(UpdatedInfo.RUNNING);
230     try {
231       runner.saveStatus();
232     } catch (final OpenR66RunnerErrorException e) {
233       error(e, business);
234     }
235     // Now create the associated file
236     try {
237       session.setFileBeforePreRunner();
238       if (runner.getStep() <= TASKSTEP.PRETASK.ordinal()) {
239         runner.setPreTask();
240         runner.saveStatus();
241         runner.run();
242         session.setFileAfterPreRunner(true);
243       }
244     } catch (final OpenR66RunnerErrorException e) {
245       error(e, business);
246     } catch (final CommandAbstractException e) {
247       error(e, business);
248     }
249     session.newState(DATAR);
250     try {
251       runner.saveStatus();
252     } catch (final OpenR66RunnerErrorException e1) {
253       logger.error("Cannot save Status: " + runner + ": {}", e1.getMessage());
254     }
255   }
256 
257   /**
258    * Set the transfer to be starting
259    *
260    * @param runner
261    */
262   protected final void startTransfer(final DbTaskRunner runner) {
263     runner.setTransferTask(0);
264     try {
265       runner.saveStatus();
266     } catch (final OpenR66RunnerErrorException e1) {
267       logger.error("Cannot save Status: " + runner + ": {}", e1.getMessage());
268     }
269   }
270 
271   /**
272    * Run post tasks on finished transfer
273    */
274   protected final void runPostTask() {
275     final DbTaskRunner runner = session.getRunner();
276     runner.setPostTask();
277     try {
278       session.newState(ENDTRANSFERR);
279       logger.debug("Post actions {}", session);
280       runner.run();
281       runner.saveStatus();
282       session.newState(ENDREQUESTS);
283     } catch (final OpenR66RunnerErrorException e) {
284       error(e, session.getBusinessObject());
285     }
286     session.newState(CLOSEDCHANNEL);
287     session.partialClear();
288     runner.setAllDone();
289     try {
290       runner.saveStatus();
291     } catch (final OpenR66RunnerErrorException ignored) {
292       // nothing
293     }
294     runner.clean();
295   }
296 
297   /**
298    * @return the current DbTaskRunner if any (null if not)
299    */
300   public final DbTaskRunner getDbTaskRunner() {
301     return session.getRunner();
302   }
303 }