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.WaarpLogger;
23  import org.waarp.common.logging.WaarpLoggerFactory;
24  import org.waarp.common.logging.WaarpSlf4JLoggerFactory;
25  import org.waarp.common.utility.WaarpSystemUtil;
26  import org.waarp.openr66.client.utils.OutputFormat;
27  import org.waarp.openr66.configuration.FileBasedConfiguration;
28  import org.waarp.openr66.context.ErrorCode;
29  import org.waarp.openr66.context.R66FiniteDualStates;
30  import org.waarp.openr66.context.authentication.R66Auth;
31  import org.waarp.openr66.database.data.DbHostAuth;
32  import org.waarp.openr66.protocol.configuration.Configuration;
33  import org.waarp.openr66.protocol.configuration.Messages;
34  import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoConnectionException;
35  import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException;
36  import org.waarp.openr66.protocol.localhandler.LocalChannelReference;
37  import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket;
38  import org.waarp.openr66.protocol.networkhandler.NetworkTransaction;
39  import org.waarp.openr66.protocol.utils.ChannelUtils;
40  import org.waarp.openr66.protocol.utils.R66Future;
41  
42  import java.net.SocketAddress;
43  
44  import static org.waarp.openr66.database.DbConstantR66.*;
45  
46  /**
47   * Abstract class for internal Business Request
48   */
49  public abstract class AbstractBusinessRequest implements Runnable {
50    protected static final String ADMIN_R_66_OPERATIONS_GUI_188 =
51        "AdminR66OperationsGui.188";
52    /**
53     * Internal Logger
54     */
55    protected static volatile WaarpLogger logger;
56  
57    protected static final String INFO_ARGS =
58        Messages.getString("AbstractBusinessRequest.0") //$NON-NLS-1$
59        + Messages.getString("Message.OutputFormat");
60  
61    protected final R66Future future;
62  
63    protected final String remoteHost;
64  
65    protected final NetworkTransaction networkTransaction;
66  
67    private final BusinessRequestPacket businessPacket;
68  
69    private LocalChannelReference localChannelReference;
70  
71    protected AbstractBusinessRequest(final Class<?> clasz,
72                                      final R66Future future,
73                                      final String remoteHost,
74                                      final NetworkTransaction networkTransaction,
75                                      final BusinessRequestPacket packet) {
76      if (logger == null) {
77        logger = WaarpLoggerFactory.getLogger(clasz);
78      }
79      this.future = future;
80      this.remoteHost = remoteHost;
81      this.networkTransaction = networkTransaction;
82      businessPacket = packet;
83    }
84  
85    @Override
86    public void run() {
87      try {
88        initRequest();
89        sendRequest();
90      } catch (final OpenR66ProtocolNoConnectionException ignored) {
91        // notning
92      }
93    }
94  
95    public void initRequest() throws OpenR66ProtocolNoConnectionException {
96      final DbHostAuth host = R66Auth.getServerAuth(remoteHost);
97      if (host == null) {
98        future.setResult(null);
99        final OpenR66ProtocolNoConnectionException e2 =
100           new OpenR66ProtocolNoConnectionException(
101               Messages.getString(ADMIN_R_66_OPERATIONS_GUI_188) +
102               remoteHost); //$NON-NLS-1$
103       future.setFailure(e2);
104       throw e2;
105     }
106     final SocketAddress socketServerAddress;
107     try {
108       socketServerAddress = host.getSocketAddress();
109     } catch (final IllegalArgumentException e) {
110       future.setResult(null);
111       final OpenR66ProtocolNoConnectionException e2 =
112           new OpenR66ProtocolNoConnectionException(
113               Messages.getString(ADMIN_R_66_OPERATIONS_GUI_188) +
114               host); //$NON-NLS-1$
115       future.setFailure(e2);
116       throw e2;
117     }
118     final boolean isSSL = host.isSsl();
119     localChannelReference =
120         networkTransaction.createConnectionWithRetry(socketServerAddress, isSSL,
121                                                      future);
122     if (localChannelReference == null) {
123       future.setResult(null);
124       final OpenR66ProtocolNoConnectionException e =
125           new OpenR66ProtocolNoConnectionException(
126               Messages.getString(ADMIN_R_66_OPERATIONS_GUI_188) +
127               host); //$NON-NLS-1$
128       future.setFailure(e);
129       throw e;
130     }
131     localChannelReference.sessionNewState(R66FiniteDualStates.BUSINESSR);
132   }
133 
134   public void sendRequest() {
135     try {
136       ChannelUtils.writeAbstractLocalPacket(localChannelReference,
137                                             businessPacket, true);
138     } catch (final OpenR66ProtocolPacketException e) {
139       future.setResult(null);
140       future.setFailure(e);
141       localChannelReference.close();
142     }
143 
144   }
145 
146   /**
147    * Dummy Main method
148    *
149    * @param args
150    */
151   public static void main(final String[] args) {
152     WaarpLoggerFactory.setDefaultFactoryIfNotSame(
153         new WaarpSlf4JLoggerFactory(null));
154     if (logger == null) {
155       logger = WaarpLoggerFactory.getLogger(AbstractBusinessRequest.class);
156     }
157     if (!getParams(args)) {
158       logger.error("Wrong initialization");
159       if (admin != null) {
160         admin.close();
161       }
162       WaarpSystemUtil.systemExit(2);
163       return;
164     }
165 
166     Configuration.configuration.pipelineInit();
167     final NetworkTransaction networkTransaction = new NetworkTransaction();
168     final R66Future future = new R66Future(true);
169 
170     logger.info("Start Test of Transaction");
171     final long time1 = System.currentTimeMillis();
172 
173     new BusinessRequestPacket(classname + ' ' + classarg, 0);
174     // XXX FIXME this has to be adapted
175     /*
176      * AbstractBusinessRequest transaction = new AbstractBusinessRequest( AbstractBusinessRequest.class, future,
177      * rhost, networkTransaction, packet); transaction.run(); future.awaitUninterruptibly()
178      */
179     final long time2 = System.currentTimeMillis();
180     logger.debug("Finish Business Request: {}", future.isSuccess());
181     final long delay = time2 - time1;
182     if (future.isSuccess()) {
183       logger.info(
184           "Business Request in status: SUCCESS    <REMOTE>{}</REMOTE>    delay: {}",
185           rhost, delay);
186     } else {
187       logger.info(
188           "Business Request in status: FAILURE    <REMOTE>{}</REMOTE>    <ERROR>{}</ERROR>    delay: {}",
189           rhost, future.getCause(), delay);
190       if (WaarpSystemUtil.isJunit()) {
191         return;
192       }
193       WaarpSystemUtil.systemExit(ErrorCode.Unknown.ordinal());
194       return;
195     }
196     networkTransaction.closeAll();
197   }
198 
199   protected static String rhost;
200   protected static String classname;
201   protected static String classarg;
202   protected static boolean nolog;
203 
204   /**
205    * Parse the parameter and set current values
206    *
207    * @param args
208    *
209    * @return True if all parameters were found and correct
210    */
211   protected static boolean getParams(final String[] args) {
212     if (logger == null) {
213       logger = WaarpLoggerFactory.getLogger(AbstractBusinessRequest.class);
214     }
215     if (args.length < 3) {
216       logger.error(INFO_ARGS);
217       return false;
218     }
219     if (!FileBasedConfiguration.setClientConfigurationFromXml(
220         Configuration.configuration, args[0])) {
221       logger.error(
222           Messages.getString("Configuration.NeedCorrectConfig")); //$NON-NLS-1$
223       return false;
224     }
225     // Now set default values from configuration
226     for (int i = 1; i < args.length; i++) {
227       if ("-to".equalsIgnoreCase(args[i])) {
228         i++;
229         rhost = args[i];
230         if (Configuration.configuration.getAliases().containsKey(rhost)) {
231           rhost = Configuration.configuration.getAliases().get(rhost);
232         }
233       } else if ("-class".equalsIgnoreCase(args[i])) {
234         i++;
235         classname = args[i];
236       } else if ("-arg".equalsIgnoreCase(args[i])) {
237         i++;
238         classarg = args[i];
239       } else if ("-nolog".equalsIgnoreCase(args[i])) {
240         nolog = true;
241         i++;
242       }
243     }
244     OutputFormat.getParams(args);
245     if (rhost != null && classname != null) {
246       return true;
247     }
248     logger.error(Messages.getString("AbstractBusinessRequest.NeedMoreArgs",
249                                     "(-to -class)") + INFO_ARGS); //$NON-NLS-1$
250     return false;
251   }
252 
253 }