KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > datacopy > DataTransformation


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oña, 107 1º2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.datacopy;
34
35 import java.util.HashMap JavaDoc;
36 import java.util.Iterator JavaDoc;
37
38 import java.sql.Connection JavaDoc;
39 import java.sql.Statement JavaDoc;
40 import java.sql.PreparedStatement JavaDoc;
41 import java.sql.ResultSet JavaDoc;
42 import java.sql.SQLException JavaDoc;
43
44 import com.knowgate.debug.DebugFile;
45 import com.knowgate.misc.Gadgets;
46
47 public class DataTransformation {
48
49   public DataTransformation() {
50     Values = new HashMap JavaDoc();
51   }
52
53   public DataTransformation(String JavaDoc sOpDesc, String JavaDoc sOrTable, String JavaDoc sOrField,
54                                             String JavaDoc sTrTable, String JavaDoc sTrField) {
55     Values = new HashMap JavaDoc();
56
57     if (sOpDesc.equalsIgnoreCase("NEXTVAL") ||
58         sOpDesc.equalsIgnoreCase("REFER")) {
59       NextVals = new HashMap JavaDoc();
60       NextVals.put(sTrTable + "." + sTrField, new Integer JavaDoc(0));
61     }
62
63     setOperation (sOpDesc);
64     OriginTable = sOrTable;
65     OriginField = sOrField;
66     TargetTable = sTrTable;
67     TargetField = sTrField;
68   }
69
70   public DataTransformation(int iOpCode, String JavaDoc sOrTable, String JavaDoc sOrField,
71                                          String JavaDoc sTrTable, String JavaDoc sTrField,
72                                          String JavaDoc sRfTable, String JavaDoc sRfField,
73                                          String JavaDoc sIfNull) {
74     Values = new HashMap JavaDoc();
75
76     if (Operations.NEXTVAL==iOpCode || Operations.REFER==iOpCode) {
77       NextVals = new HashMap JavaDoc();
78       NextVals.put(sTrTable + "." + sTrField, new Integer JavaDoc(0));
79     }
80
81     OperationCode = iOpCode;
82     OriginTable = sOrTable;
83     OriginField = sOrField;
84     TargetTable = sTrTable;
85     TargetField = sTrField;
86     ReferedTable= sRfTable;
87     ReferedField= sRfField;
88     IfNullValue = sIfNull;
89   }
90
91   // ----------------------------------------------------------
92

93   private void setOperation(String JavaDoc sOpDesc) {
94     /* Establece el tipo de operación que realizará este servicio de
95       transformación de datos
96       Parámetros:
97         sOpDesc -> Descripción de la Operación.
98                    Puede ser uno de los siguientes valores:
99                    1) NEWGUID para que el campo en destino sea un nuevo GUID generado dinámicamente
100                    2) NEXTVAL el campo en destino será MAX(campo)+1
101                    3) IFNULL(valor) si el campo en origen es NULL se substituirá por el valor especificado
102                    4) REFER(tablaref.camporef) el campo se substituirá por el valor que tenga tablaref.camporef
103     */

104     int iLeft;
105     int iRight;
106     int iDot;
107
108     if (sOpDesc.equalsIgnoreCase("NEWGUID"))
109       OperationCode = Operations.NEWGUID;
110     else if (sOpDesc.equalsIgnoreCase("NEXTVAL")) {
111       OperationCode = Operations.NEXTVAL;
112     }
113     else if (sOpDesc.equalsIgnoreCase("REFERENCED")) {
114       OperationCode = Operations.REFERENCED;
115     }
116     else if (sOpDesc.startsWith("IFNULL")) {
117       OperationCode = Operations.IFNULL;
118       iLeft = sOpDesc.indexOf("(") + 1;
119       iRight = sOpDesc.lastIndexOf(")");
120       IfNullValue = sOpDesc.substring(iLeft, iRight).trim();
121     }
122     else if (sOpDesc.startsWith("REFER")) {
123       OperationCode = Operations.REFER;
124       iLeft = sOpDesc.indexOf("(") + 1;
125       iRight = sOpDesc.lastIndexOf(")");
126       iDot = sOpDesc.indexOf(".");
127       ReferedTable = sOpDesc.substring(iLeft , iDot);
128       ReferedField = sOpDesc.substring(iDot+1, iRight);
129     }
130   } // setOperation()
131

132   // ----------------------------------------------------------
133

134   public void setReferedValues(DataTransformation oDataTransf) {
135     ReferedValues = oDataTransf.Values;
136   }
137
138   // ----------------------------------------------------------
139

140   private String JavaDoc IncOffset(String JavaDoc sTrTable, String JavaDoc sTrField) {
141     String JavaDoc sKey = sTrTable + "." + sTrField;
142     Integer JavaDoc iOldOffset = (Integer JavaDoc) NextVals.get(sKey);
143     Integer JavaDoc iNewOffset = new Integer JavaDoc(iOldOffset.intValue()+1);
144
145     NextVals.remove(sKey);
146     NextVals.put(sKey, iNewOffset);
147
148     return iNewOffset.toString();
149   }
150
151   // ----------------------------------------------------------
152

153   private Integer JavaDoc getNextVal(Connection JavaDoc oTrConn) throws SQLException JavaDoc {
154     Integer JavaDoc oRetVal;
155     Object JavaDoc oMax;
156     Statement JavaDoc oStmt;
157     ResultSet JavaDoc oRSet;
158     Iterator JavaDoc oIter;
159
160     oStmt = oTrConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
161
162     oRSet = oStmt.executeQuery("SELECT MAX(" + TargetField + ")+" + IncOffset(TargetTable,TargetField) + " FROM " + TargetTable);
163
164     if (oRSet.next()) {
165       oMax = oRSet.getObject(1);
166       if (oRSet.wasNull())
167         oRetVal = new Integer JavaDoc(1);
168       else
169         oRetVal = new Integer JavaDoc(oMax.toString());
170     }
171     else {
172       oRetVal = new Integer JavaDoc(1);
173     }
174     oRSet.close();
175     oStmt.close();
176
177     // Asegurar que el nextVal no mapea un campo al mismo valor que tiene
178
// otro obtenido a través de referencia a otra tabla y no de autoincremento
179
if (Operations.REFER==OperationCode) {
180       oIter = ReferedValues.values().iterator();
181       while (oIter.hasNext())
182         if (((Integer JavaDoc) oIter.next()).intValue()==oRetVal.intValue()) {
183           if (DebugFile.trace) DebugFile.writeln("Remapping " + TargetTable + "." + TargetField);
184           oRetVal = getNextVal(oTrConn);
185           break;
186         }
187       // wend
188
oIter = null;
189     }
190
191     return oRetVal;
192   } // getNextVal()
193

194   // ----------------------------------------------------------
195

196   public Object JavaDoc transform(Connection JavaDoc oOrConn, Connection JavaDoc oTrConn, Object JavaDoc oInput) throws SQLException JavaDoc {
197     Object JavaDoc oNexVal;
198     Object JavaDoc oRetVal;
199     Iterator JavaDoc oIter;
200     PreparedStatement JavaDoc oStmt;
201     ResultSet JavaDoc oRSet;
202
203     switch(OperationCode) {
204      case Operations.NEWGUID:
205        oRetVal = Gadgets.generateUUID();
206        break;
207      case Operations.NEXTVAL:
208        oRetVal = getNextVal(oTrConn);
209        break;
210      case Operations.IFNULL:
211         if (null==oInput) {
212           if (IfNullValue.equalsIgnoreCase("SYSDATE") ||
213               IfNullValue.equalsIgnoreCase("GETDATE()") )
214             oRetVal = new java.sql.Date JavaDoc(new java.util.Date JavaDoc().getTime());
215           else
216             oRetVal = IfNullValue;
217         }
218         else if (oInput.getClass().getName().equals("java.lang.String"))
219           oRetVal = oInput.toString().length()>0 ? oInput : IfNullValue;
220         else
221           oRetVal = oInput;
222        break;
223      case Operations.REFER:
224        if (ReferedValues!=null) {
225          // Busca el valor en la tabla de referencia,
226
// si no lo encuentra, entonces crea un nuevo GUID
227
if (ReferedValues.containsKey(oInput))
228            oRetVal = ReferedValues.get(oInput);
229          else if (oInput!=null) {
230            // Si el campo no se encuentra en el mapa de memoria
231
// pero ya existía en la tabla de destino,
232
// entonces dejarlo tal cual en el mapeo.
233
oStmt = oTrConn.prepareStatement("SELECT NULL FROM " + TargetTable + " WHERE " + TargetField + "=?");
234            oStmt.setObject(1,oInput);
235            oRSet = oStmt.executeQuery();
236            if (oRSet.next())
237              oRetVal = oInput;
238            else
239              oRetVal = null;
240            oRSet.close();
241            oStmt.close();
242
243            if (null==oRetVal) {
244              oIter = ReferedValues.values().iterator();
245              if (oIter.hasNext()) {
246                oNexVal = oIter.next();
247                if (oNexVal.getClass().getName().equals("java.lang.String"))
248                  oRetVal = Gadgets.generateUUID();
249                else
250                  oRetVal = getNextVal(oTrConn);
251              }
252              else
253                oRetVal = Gadgets.generateUUID();
254              oIter = null;
255            }
256          } // fi(oInput)
257
else
258            oRetVal = null;
259        }
260        else {
261          throw new SQLException JavaDoc(this.OriginTable + " could not reference " + this.ReferedTable, "23000");
262        } // fi(ReferedValues)
263
break;
264      case Operations.REFERENCED:
265        oRetVal = oInput;
266        break;
267      default:
268        oRetVal = oInput;
269     }
270
271     if (!Values.containsKey(oInput)) Values.put(oInput, oRetVal);
272
273     return oRetVal;
274   } // transform()
275

276   // ----------------------------------------------------------
277

278   public int OperationCode; // Codigo de operacion
279
public String JavaDoc IfNullValue; // Valor para reemplazar si el campo es NULL
280
public String JavaDoc OriginField; // Nombre del campo origen
281
public String JavaDoc TargetField; // Nombre de campo destino
282
public String JavaDoc OriginTable; // Nombre de tabla origen
283
public String JavaDoc TargetTable; // Nombre de tabla destino
284
public String JavaDoc ReferedTable;
285   public String JavaDoc ReferedField;
286   public HashMap JavaDoc ReferedValues;
287   public HashMap JavaDoc Values;
288   public HashMap JavaDoc NextVals;
289
290   public class Operations {
291     public static final int NEWGUID = 1;
292     public static final int NEXTVAL = 2;
293     public static final int IFNULL = 4;
294     public static final int REFERENCED = 8;
295     public static final int REFER = 16;
296   }
297 }
Popular Tags