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.client;
21  
22  import org.waarp.common.logging.SysErrLogger;
23  import org.waarp.common.logging.WaarpLogger;
24  import org.waarp.common.logging.WaarpLoggerFactory;
25  import org.waarp.common.logging.WaarpSlf4JLoggerFactory;
26  import org.waarp.common.utility.WaarpSystemUtil;
27  import org.waarp.openr66.client.utils.OutputFormat;
28  import org.waarp.openr66.client.utils.OutputFormat.FIELDS;
29  import org.waarp.openr66.configuration.FileBasedConfiguration;
30  import org.waarp.openr66.context.ErrorCode;
31  import org.waarp.openr66.context.R66FiniteDualStates;
32  import org.waarp.openr66.context.R66Result;
33  import org.waarp.openr66.context.authentication.R66Auth;
34  import org.waarp.openr66.database.data.DbHostAuth;
35  import org.waarp.openr66.database.data.DbTaskRunner;
36  import org.waarp.openr66.protocol.configuration.Configuration;
37  import org.waarp.openr66.protocol.configuration.Messages;
38  import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException;
39  import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException;
40  import org.waarp.openr66.protocol.localhandler.LocalChannelReference;
41  import org.waarp.openr66.protocol.localhandler.packet.InformationPacket;
42  import org.waarp.openr66.protocol.localhandler.packet.ValidPacket;
43  import org.waarp.openr66.protocol.networkhandler.NetworkTransaction;
44  import org.waarp.openr66.protocol.utils.ChannelUtils;
45  import org.waarp.openr66.protocol.utils.R66Future;
46  
47  import java.net.SocketAddress;
48  
49  import static org.waarp.common.database.DbConstant.*;
50  
51  /**
52   * Class to request information on remote files
53   */
54  public class RequestInformation implements Runnable {
55    /**
56     * Internal Logger
57     */
58    static volatile WaarpLogger logger;
59  
60    public static final byte REQUEST_CHECK = -1;
61  
62    protected static String infoArgs =
63        Messages.getString("RequestInformation.0") //$NON-NLS-1$
64        + Messages.getString("Message.OutputFormat");
65  
66    protected final NetworkTransaction networkTransaction;
67    final R66Future future;
68    final String requested;
69    final String filename;
70    final String rulename;
71    final byte code;
72    long id = ILLEGALVALUE;
73    boolean isTo = true;
74    boolean normalInfoAsWarn = true;
75  
76    static String srequested;
77    static String sfilename;
78    static String srulename;
79    static byte scode = REQUEST_CHECK;
80    static long sid = ILLEGALVALUE;
81    static boolean sisTo = true;
82    protected static boolean snormalInfoAsWarn = true;
83  
84    /**
85     * Parse the parameter and set current values
86     *
87     * @param args
88     *
89     * @return True if all parameters were found and correct
90     */
91    protected static boolean getParams(final String[] args) {
92      infoArgs = Messages.getString("RequestInformation.0") +
93                 Messages.getString("Message.OutputFormat"); //$NON-NLS-1$
94      if (args.length < 5) {
95        logger.error(infoArgs);
96        return false;
97      }
98      if (!FileBasedConfiguration.setClientConfigurationFromXml(
99          Configuration.configuration, args[0])) {
100       logger.error(
101           Messages.getString("Configuration.NeedCorrectConfig")); //$NON-NLS-1$
102       return false;
103     }
104     for (int i = 1; i < args.length; i++) {
105       if ("-to".equalsIgnoreCase(args[i])) {
106         i++;
107         srequested = args[i];
108         if (Configuration.configuration.getAliases().containsKey(srequested)) {
109           srequested = Configuration.configuration.getAliases().get(srequested);
110         }
111       } else if ("-file".equalsIgnoreCase(args[i])) {
112         i++;
113         sfilename = args[i];
114         sfilename = sfilename.replace('ยง', '*');
115       } else if ("-rule".equalsIgnoreCase(args[i])) {
116         i++;
117         srulename = args[i];
118       } else if ("-logWarn".equalsIgnoreCase(args[i])) {
119         snormalInfoAsWarn = true;
120       } else if ("-notlogWarn".equalsIgnoreCase(args[i])) {
121         snormalInfoAsWarn = false;
122       } else if ("-exist".equalsIgnoreCase(args[i])) {
123         scode = (byte) InformationPacket.ASKENUM.ASKEXIST.ordinal();
124       } else if ("-detail".equalsIgnoreCase(args[i])) {
125         scode = (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal();
126       } else if ("-list".equalsIgnoreCase(args[i])) {
127         scode = (byte) InformationPacket.ASKENUM.ASKLIST.ordinal();
128       } else if ("-mlsx".equalsIgnoreCase(args[i])) {
129         scode = (byte) InformationPacket.ASKENUM.ASKMLSLIST.ordinal();
130       } else if ("-id".equalsIgnoreCase(args[i])) {
131         i++;
132         sid = Long.parseLong(args[i]);
133       } else if ("-reqfrom".equalsIgnoreCase(args[i])) {
134         sisTo = true;
135       } else if ("-reqto".equalsIgnoreCase(args[i])) {
136         sisTo = false;
137       }
138     }
139     OutputFormat.getParams(args);
140     if (sfilename != null && scode == REQUEST_CHECK) {
141       scode = (byte) InformationPacket.ASKENUM.ASKEXIST.ordinal();
142     }
143     if (srulename == null && scode != REQUEST_CHECK || srequested == null) {
144       logger.error(
145           Messages.getString("RequestInformation.12") + infoArgs); //$NON-NLS-1$
146       return false;
147     }
148     if (scode != REQUEST_CHECK && sid != ILLEGALVALUE) {
149       logger.error(
150           Messages.getString("RequestInformation.13") + infoArgs); //$NON-NLS-1$
151       return false;
152     }
153     return true;
154   }
155 
156   /**
157    * @param future
158    * @param requested
159    * @param rulename
160    * @param filename
161    * @param request
162    * @param id Id of the request
163    * @param isTo request is To remote Host (true), or From remote host
164    *     (false)
165    * @param networkTransaction
166    */
167   public RequestInformation(final R66Future future, final String requested,
168                             final String rulename, final String filename,
169                             final byte request, final long id,
170                             final boolean isTo,
171                             final NetworkTransaction networkTransaction) {
172     this.future = future;
173     this.rulename = rulename;
174     this.requested = requested;
175     this.filename = filename;
176     code = request;
177     this.id = id;
178     this.isTo = isTo;
179     this.networkTransaction = networkTransaction;
180     if (logger == null) {
181       logger = WaarpLoggerFactory.getLogger(RequestInformation.class);
182     }
183   }
184 
185   @Override
186   public void run() {
187     final InformationPacket request;
188     if (code != REQUEST_CHECK) {
189       request = new InformationPacket(rulename, code, filename);
190     } else {
191       request =
192           new InformationPacket(String.valueOf(id), code, isTo? "1" : "0");
193     }
194 
195     // Connection
196     final DbHostAuth host = R66Auth.getServerAuth(requested);
197     if (host == null) {
198       logger.error(
199           Messages.getString("Message.HostNotFound") + requested); //$NON-NLS-1$
200       final R66Result result =
201           new R66Result(null, true, ErrorCode.ConnectionImpossible, null);
202       future.setResult(result);
203       future.cancel();
204       return;
205     }
206     if (host.isClient()) {
207       logger.error(
208           Messages.getString("Message.HostIsClient") + requested); //$NON-NLS-1$
209       final R66Result result =
210           new R66Result(null, true, ErrorCode.ConnectionImpossible, null);
211       future.setResult(result);
212       future.cancel();
213       return;
214     }
215     final SocketAddress socketAddress = host.getSocketAddress();
216     final boolean isSSL = host.isSsl();
217 
218     final LocalChannelReference localChannelReference =
219         networkTransaction.createConnectionWithRetry(socketAddress, isSSL,
220                                                      future);
221     if (localChannelReference == null) {
222       logger.error(Messages.getString("AdminR66OperationsGui.188") +
223                    requested); //$NON-NLS-1$
224       final R66Result result =
225           new R66Result(null, true, ErrorCode.ConnectionImpossible, null);
226       future.setResult(result);
227       future.cancel();
228       return;
229     }
230     localChannelReference.sessionNewState(R66FiniteDualStates.INFORMATION);
231     try {
232       ChannelUtils.writeAbstractLocalPacket(localChannelReference, request,
233                                             false);
234     } catch (final OpenR66ProtocolPacketException e) {
235       logger.error(Messages.getString("RequestInformation.20")); //$NON-NLS-1$
236       final R66Result result =
237           new R66Result(null, true, ErrorCode.TransferError, null);
238       future.setResult(result);
239       future.cancel();
240       return;
241     }
242     localChannelReference.getFutureRequest().awaitOrInterruptible();
243   }
244 
245   /**
246    * @param args
247    */
248   public static void main(final String[] args) {
249     WaarpLoggerFactory.setDefaultFactoryIfNotSame(
250         new WaarpSlf4JLoggerFactory(null));
251     if (logger == null) {
252       logger = WaarpLoggerFactory.getLogger(RequestInformation.class);
253     }
254     if (!getParams(args)) {
255       logger.error(Messages.getString("Configuration.WrongInit")); //$NON-NLS-1$
256       if (!OutputFormat.isQuiet()) {
257         SysErrLogger.FAKE_LOGGER.sysout(
258             Messages.getString("Configuration.WrongInit")); //$NON-NLS-1$
259       }
260       if (admin != null) {
261         admin.close();
262       }
263       WaarpSystemUtil.systemExit(1);
264       return;
265     }
266     NetworkTransaction networkTransaction = null;
267     int value = 3;
268     try {
269       Configuration.configuration.pipelineInit();
270       networkTransaction = new NetworkTransaction();
271       final R66Future result = new R66Future(true);
272       final RequestInformation requestInformation =
273           new RequestInformation(result, srequested, srulename, sfilename,
274                                  scode, sid, sisTo, networkTransaction);
275       requestInformation.normalInfoAsWarn = snormalInfoAsWarn;
276       requestInformation.run();
277       result.awaitOrInterruptible();
278       // if transfer information request (code = -1 = REQUEST_CHECK) => middle empty and
279       // header = Runner as XML
280       // if listing request => middle = nb of files, header = list of files in native/list/mlsx/exist (true/false)
281       // format, 1 file per line
282       final OutputFormat outputFormat =
283           new OutputFormat(RequestInformation.class.getSimpleName(), args);
284       if (result.isSuccess()) {
285         value = 0;
286         final R66Result r66result = result.getResult();
287         final ValidPacket info = (ValidPacket) r66result.getOther();
288         outputFormat.setValue(FIELDS.status.name(), 0);
289         outputFormat.setValue(FIELDS.statusTxt.name(), Messages.getString(
290             "RequestInformation.Success")); //$NON-NLS-1$
291         outputFormat.setValue(FIELDS.remote.name(), srequested);
292         if (requestInformation.code != REQUEST_CHECK) {
293           outputFormat.setValue("nb", Integer.parseInt(info.getSmiddle()));
294           final String[] files = info.getSheader().split("\n");
295           int i = 0;
296           for (final String file : files) {
297             i++;
298             outputFormat.setValue("file" + i, file);
299           }
300         } else {
301           try {
302             final DbTaskRunner runner =
303                 DbTaskRunner.fromStringXml(info.getSheader(), false);
304             outputFormat.setValueString(runner.getJson());
305           } catch (final OpenR66ProtocolBusinessException e) {
306             outputFormat.setValue("Id", requestInformation.id);
307             outputFormat.setValue(FIELDS.transfer.name(), info.getSheader());
308           }
309         }
310         if (requestInformation.normalInfoAsWarn) {
311           logger.warn(outputFormat.loggerOut());
312         } else if (logger.isInfoEnabled()) {
313           logger.info(outputFormat.loggerOut());
314         }
315         if (!OutputFormat.isQuiet()) {
316           outputFormat.sysout();
317         }
318       } else {
319         value = 2;
320         outputFormat.setValue(FIELDS.status.name(), 2);
321         outputFormat.setValue(FIELDS.statusTxt.name(), Messages.getString(
322             "RequestInformation.Failure")); //$NON-NLS-1$
323         outputFormat.setValue(FIELDS.remote.name(), srequested);
324         outputFormat.setValue(FIELDS.error.name(),
325                               result.getResult().toString());
326         logger.error(outputFormat.loggerOut());
327         if (!OutputFormat.isQuiet()) {
328           outputFormat.sysout();
329         }
330       }
331     } catch (final Throwable e) {
332       logger.error("Exception", e);
333     } finally {
334       if (!WaarpSystemUtil.isJunit()) {
335         if (networkTransaction != null) {
336           networkTransaction.closeAll();
337         }
338         if (admin != null) {
339           admin.close();
340         }
341         WaarpSystemUtil.systemExit(value);
342       }
343     }
344   }
345 
346 }