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.database.data;
21  
22  import com.fasterxml.jackson.databind.JsonNode;
23  import com.fasterxml.jackson.databind.node.ObjectNode;
24  import org.waarp.common.database.DbConstant;
25  import org.waarp.common.database.DbPreparedStatement;
26  import org.waarp.common.database.DbSession;
27  import org.waarp.common.database.exception.WaarpDatabaseException;
28  import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException;
29  import org.waarp.common.database.exception.WaarpDatabaseSqlException;
30  import org.waarp.common.utility.ParametersChecker;
31  import org.waarp.openr66.dao.AbstractDAO;
32  import org.waarp.openr66.dao.DAOFactory;
33  import org.waarp.openr66.dao.Filter;
34  import org.waarp.openr66.dao.LimitDAO;
35  import org.waarp.openr66.dao.database.DBLimitDAO;
36  import org.waarp.openr66.dao.database.StatementExecutor;
37  import org.waarp.openr66.dao.exception.DAOConnectionException;
38  import org.waarp.openr66.dao.exception.DAONoDataException;
39  import org.waarp.openr66.pojo.Limit;
40  import org.waarp.openr66.protocol.configuration.Configuration;
41  
42  import java.sql.SQLException;
43  import java.sql.Types;
44  import java.util.ArrayList;
45  import java.util.List;
46  
47  /**
48   * Configuration Table object
49   */
50  public class DbConfiguration extends AbstractDbDataDao<Limit> {
51  
52    public enum Columns {
53      READGLOBALLIMIT, WRITEGLOBALLIMIT, READSESSIONLIMIT, WRITESESSIONLIMIT,
54      DELAYLIMIT, UPDATEDINFO, HOSTID
55    }
56  
57    public static final int[] dbTypes = {
58        Types.BIGINT, Types.BIGINT, Types.BIGINT, Types.BIGINT, Types.BIGINT,
59        Types.INTEGER, Types.NVARCHAR
60    };
61  
62    public static final String table = " CONFIGURATION ";
63  
64    protected static final String selectAllFields =
65        Columns.READGLOBALLIMIT.name() + ',' + Columns.WRITEGLOBALLIMIT.name() +
66        ',' + Columns.READSESSIONLIMIT.name() + ',' +
67        Columns.WRITESESSIONLIMIT.name() + ',' + Columns.DELAYLIMIT.name() + ',' +
68        Columns.UPDATEDINFO.name() + ',' + Columns.HOSTID.name();
69  
70    public static final Columns[] indexes = {
71        Columns.HOSTID, Columns.UPDATEDINFO
72    };
73  
74    @Override
75    protected final String getTable() {
76      return table;
77    }
78  
79    @Override
80    protected final AbstractDAO<Limit> getDao(final boolean isCacheable)
81        throws DAOConnectionException {
82      return DAOFactory.getInstance().getLimitDAO(isCacheable);
83    }
84  
85    @Override
86    protected final String getPrimaryKey() {
87      if (pojo != null) {
88        return pojo.getHostid();
89      }
90      throw new IllegalArgumentException("pojo is null");
91    }
92  
93    @Override
94    protected final String getPrimaryField() {
95      return Columns.HOSTID.name();
96    }
97  
98  
99    /**
100    * @param hostid
101    * @param rg Read Global Limit
102    * @param wg Write Global Limit
103    * @param rs Read Session Limit
104    * @param ws Write Session Limit
105    * @param del Delay Limit
106    */
107   public DbConfiguration(final String hostid, final long rg, final long wg,
108                          final long rs, final long ws, final long del)
109       throws WaarpDatabaseSqlException {
110     pojo = new Limit(hostid, rg, wg, rs, ws, del);
111   }
112 
113   public DbConfiguration(final Limit limit) {
114     if (limit == null) {
115       throw new IllegalArgumentException(
116           "Argument in constructor cannot be null");
117     }
118     this.pojo = limit;
119   }
120 
121   /**
122    * Constructor from Json
123    *
124    * @param source
125    *
126    * @throws WaarpDatabaseSqlException
127    */
128   public DbConfiguration(final ObjectNode source)
129       throws WaarpDatabaseSqlException {
130     pojo = new Limit();
131     setFromJson(source, false);
132     if (ParametersChecker.isEmpty(pojo.getHostid())) {
133       throw new WaarpDatabaseSqlException(
134           "Not enough argument to create the object");
135     }
136   }
137 
138   @Override
139   protected final void checkValues() throws WaarpDatabaseSqlException {
140     pojo.checkValues();
141   }
142 
143   /**
144    * Read json object into Array then setFromArray
145    *
146    * @param node
147    * @param ignorePrimaryKey
148    *
149    * @throws WaarpDatabaseSqlException
150    */
151   @Override
152   public final void setFromJson(final ObjectNode node,
153                                 final boolean ignorePrimaryKey)
154       throws WaarpDatabaseSqlException {
155     super.setFromJson(node, ignorePrimaryKey);
156     if (ParametersChecker.isEmpty(pojo.getHostid())) {
157       throw new WaarpDatabaseSqlException(
158           "Not enough argument to create the object");
159     }
160   }
161 
162   /**
163    * @param hostid
164    *
165    * @throws WaarpDatabaseException
166    */
167   public DbConfiguration(final String hostid) throws WaarpDatabaseException {
168     LimitDAO limitAccess = null;
169     try {
170       limitAccess = DAOFactory.getInstance().getLimitDAO(true);
171       pojo = limitAccess.select(hostid);
172     } catch (final DAOConnectionException e) {
173       throw new WaarpDatabaseException(e);
174     } catch (final DAONoDataException e) {
175       pojo = new Limit(hostid, 0L);
176     } finally {
177       DAOFactory.closeDAO(limitAccess);
178     }
179   }
180 
181   /**
182    * Private constructor for Commander only
183    */
184   private DbConfiguration() {
185     pojo = new Limit();
186   }
187 
188   @Override
189   protected final void setFromJson(final String field, final JsonNode value) {
190     if (value == null) {
191       return;
192     }
193     for (final Columns column : Columns.values()) {
194       if (column.name().equalsIgnoreCase(field)) {
195         switch (column) {
196           case READGLOBALLIMIT:
197             pojo.setReadGlobalLimit(value.asLong());
198             break;
199           case WRITEGLOBALLIMIT:
200             pojo.setWriteGlobalLimit(value.asLong());
201             break;
202           case READSESSIONLIMIT:
203             pojo.setReadSessionLimit(value.asLong());
204             break;
205           case WRITESESSIONLIMIT:
206             pojo.setWriteSessionLimit(value.asLong());
207             break;
208           case DELAYLIMIT:
209             pojo.setDelayLimit(value.asLong());
210             break;
211           case UPDATEDINFO:
212             pojo.setUpdatedInfo(
213                 org.waarp.openr66.pojo.UpdatedInfo.valueOf(value.asInt()));
214             break;
215           case HOSTID:
216             pojo.setHostid(value.asText());
217             break;
218         }
219       }
220     }
221   }
222 
223   /**
224    * @return the array of DbConfiguration from Updated status
225    *
226    * @throws WaarpDatabaseNoConnectionException
227    */
228   public static DbConfiguration[] getUpdatedPrepareStament()
229       throws WaarpDatabaseNoConnectionException {
230     final List<Filter> filters = new ArrayList<Filter>();
231     filters.add(new Filter(DBLimitDAO.HOSTID_FIELD, "=",
232                            Configuration.configuration.getHostId()));
233     filters.add(new Filter(DBLimitDAO.UPDATED_INFO_FIELD, "=",
234                            UpdatedInfo.TOSUBMIT.ordinal()));
235 
236     LimitDAO limitAccess = null;
237     List<Limit> limits;
238     try {
239       limitAccess = DAOFactory.getInstance().getLimitDAO(false);
240       limits = limitAccess.find(filters);
241     } catch (final DAOConnectionException e) {
242       throw new WaarpDatabaseNoConnectionException(e);
243     } finally {
244       DAOFactory.closeDAO(limitAccess);
245     }
246     final DbConfiguration[] res = new DbConfiguration[limits.size()];
247     int i = 0;
248     for (final Limit limit : limits) {
249       res[i] = new DbConfiguration(limit);
250       res[i].isSaved = true;
251       i++;
252     }
253     return res;
254   }
255 
256   /**
257    * @param session
258    * @param hostid
259    * @param limitBandwith 0 for no limit, > 0 for one limit, < 0 for
260    *     no
261    *     filter
262    *
263    * @return the preparedStatement with the filter
264    *
265    * @throws WaarpDatabaseNoConnectionException
266    * @throws WaarpDatabaseSqlException
267    */
268   public static DbPreparedStatement getFilterPrepareStament(
269       final DbSession session, final String hostid, final long limitBandwith)
270       throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException {
271     final DbPreparedStatement preparedStatement =
272         new DbPreparedStatement(session);
273     final String request = "SELECT " + selectAllFields + " FROM " + table;
274     String condition = null;
275     if (ParametersChecker.isNotEmpty(hostid)) {
276       condition = " WHERE " + Columns.HOSTID.name() + " = '" + hostid + "' ";
277     }
278     if (limitBandwith >= 0) {
279       if (condition == null) {
280         condition = " WHERE ";
281       } else {
282         condition += " AND ";
283       }
284       if (limitBandwith == 0) {
285         condition += "(" + Columns.READGLOBALLIMIT + " == 0 AND " +
286                      Columns.READSESSIONLIMIT + " == 0 AND " +
287                      Columns.WRITEGLOBALLIMIT + " == 0 AND " +
288                      Columns.WRITESESSIONLIMIT + " == 0)";
289       } else {
290         condition +=
291             "(" + Columns.READGLOBALLIMIT + " > " + limitBandwith + " OR " +
292             Columns.READSESSIONLIMIT + " > " + limitBandwith + " OR " +
293             Columns.WRITEGLOBALLIMIT + " > " + limitBandwith + " OR " +
294             Columns.WRITESESSIONLIMIT + " > " + limitBandwith + ')';
295       }
296     }
297     if (condition != null) {
298       preparedStatement.createPrepareStatement(
299           request + condition + " ORDER BY " + Columns.HOSTID.name());
300     } else {
301       preparedStatement.createPrepareStatement(
302           request + " ORDER BY " + Columns.HOSTID.name());
303     }
304     return preparedStatement;
305   }
306 
307   public static DbConfiguration getFromStatement(
308       final DbPreparedStatement statement)
309       throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException {
310     final DbConfiguration dbConfiguration = new DbConfiguration();
311     AbstractDAO<Limit> limitDAO = null;
312     try {
313       limitDAO = dbConfiguration.getDao(false);
314       dbConfiguration.pojo =
315           ((StatementExecutor<Limit>) limitDAO).getFromResultSet(
316               statement.getResultSet());
317       return dbConfiguration;
318     } catch (final SQLException e) {
319       DbConstant.error(e);
320       throw new WaarpDatabaseSqlException("Getting values in error", e);
321     } catch (final DAOConnectionException e) {
322       throw new WaarpDatabaseSqlException("Getting values in error", e);
323     } finally {
324       DAOFactory.closeDAO(limitDAO);
325     }
326   }
327 
328   @Override
329   public final void changeUpdatedInfo(final UpdatedInfo info) {
330     isSaved = false;
331     pojo.setUpdatedInfo(org.waarp.openr66.pojo.UpdatedInfo.fromLegacy(info));
332   }
333 
334   /**
335    * Update configuration according to new value of limits
336    */
337   public final void updateConfiguration() {
338     Configuration.configuration.changeNetworkLimit(pojo.getWriteGlobalLimit(),
339                                                    pojo.getReadGlobalLimit(),
340                                                    pojo.getWriteSessionLimit(),
341                                                    pojo.getReadSessionLimit(),
342                                                    pojo.getDelayLimit());
343   }
344 
345   /**
346    * @return True if this Configuration refers to the current host
347    */
348   public final boolean isOwnConfiguration() {
349     return pojo.getHostid().equals(Configuration.configuration.getHostId());
350   }
351 
352 }