merge media InputStream changes from MIR_1_0 branch
[mir.git] / source / mir / storage / Database.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mir.storage;
33
34 import  java.sql.*;
35 import  java.lang.*;
36 import  java.io.*;
37 import  java.util.*;
38 import  java.text.SimpleDateFormat;
39 import  java.text.ParseException;
40 import  freemarker.template.*;
41 import  com.codestudio.sql.*;
42 import  com.codestudio.util.*;
43
44 import  mir.storage.StorageObject;
45 import  mir.storage.store.*;
46 import  mir.entity.*;
47 import  mir.misc.*;
48
49
50 /**
51  * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
52  * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
53  * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
54  * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
55  * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
56  * Datenbank erfolgt.
57  *
58  * @version $Id: Database.java,v 1.24 2002/11/04 04:35:21 mh Exp $
59  * @author rk
60  *
61  */
62 public class Database implements StorageObject {
63
64         protected String                    theTable;
65         protected String                    theCoreTable=null;
66         protected String                    thePKeyName="id";
67         protected int                       thePKeyType, thePKeyIndex;
68         protected boolean                   evaluatedMetaData=false;
69         protected ArrayList                 metadataFields,metadataLabels,
70                                                                                                                                                         metadataNotNullFields;
71         protected int[]                     metadataTypes;
72         protected Class                     theEntityClass;
73         protected StorageObject             myselfDatabase;
74         protected SimpleList                popupCache=null;
75         protected boolean                   hasPopupCache = false;
76         protected SimpleHash                hashCache=null;
77         protected boolean                   hasTimestamp=true;
78         private String                      database_driver, database_url;
79         private int                         defaultLimit;
80         protected DatabaseAdaptor           theAdaptor;
81         protected Logfile                   theLog;
82         private static Class                GENERIC_ENTITY_CLASS=null,
83                                       STORABLE_OBJECT_ENTITY_CLASS=null;
84   private static SimpleHash           POPUP_EMTYLINE=new SimpleHash();
85   protected static final ObjectStore  o_store=ObjectStore.getInstance();
86   private SimpleDateFormat _dateFormatterOut = 
87                                     new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
88   private SimpleDateFormat _dateFormatterIn = 
89                                     new SimpleDateFormat("yyyy-MM-dd HH:mm");
90   private Calendar _cal = new GregorianCalendar();
91
92   private static final int _millisPerHour = 60 * 60 * 1000;
93   private static final int _millisPerMinute = 60 * 1000;
94
95         static {
96                 // always same object saves a little space
97                 POPUP_EMTYLINE.put("key", ""); POPUP_EMTYLINE.put("value", "--");
98     try {
99       GENERIC_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
100       STORABLE_OBJECT_ENTITY_CLASS = Class.forName("mir.entity.StorableObjectEntity");
101     }
102     catch (Exception e) {
103       System.err.println("FATAL: Database.java could not initialize" + e.toString());
104     }
105   }
106
107
108         /**
109          * Kontruktor bekommt den Filenamen des Konfigurationsfiles übergeben.
110          * Aus diesem file werden <code>Database.Logfile</code>,
111          * <code>Database.Username</code>,<code>Database.Password</code>,
112          * <code>Database.Host</code> und <code>Database.Adaptor</code>
113          * ausgelesen und ein Broker für die Verbindugen zur Datenbank
114          * erzeugt.
115          *
116          * @param   String confFilename Dateiname der Konfigurationsdatei
117          */
118         public Database() throws StorageObjectException {
119                 theLog = Logfile.getInstance(MirConfig.getProp("Home")+
120                                                                                                                                 MirConfig.getProp("Database.Logfile"));
121                 String theAdaptorName=MirConfig.getProp("Database.Adaptor");
122                 defaultLimit = Integer.parseInt(MirConfig.getProp("Database.Limit"));
123                 try {
124                         theEntityClass = GENERIC_ENTITY_CLASS;
125                         theAdaptor = (DatabaseAdaptor)Class.forName(theAdaptorName).newInstance();
126                 } catch (Exception e){
127                         theLog.printError("Error in Database() constructor with "+
128                                                                                                 theAdaptorName + " -- " +e.toString());
129                         throw new StorageObjectException("Error in Database() constructor with "
130                                                                                                                                                          +e.toString());
131                 }
132                 /*String database_username=MirConfig.getProp("Database.Username");
133                 String database_password=MirConfig.getProp("Database.Password");
134                 String database_host=MirConfig.getProp("Database.Host");
135                 try {
136                         database_driver=theAdaptor.getDriver();
137                         database_url=theAdaptor.getURL(database_username,database_password,
138                                                                                                                                                 database_host);
139                         theLog.printDebugInfo("adding Broker with: " +database_driver+":"+
140                                                                                                                 database_url  );
141                         MirConfig.addBroker(database_driver,database_url);
142                         //myBroker=MirConfig.getBroker();
143                 }*/
144         }
145
146         /**
147          * Liefert die Entity-Klasse zurück, in der eine Datenbankzeile gewrappt
148          * wird. Wird die Entity-Klasse durch die erbende Klasse nicht überschrieben,
149          * wird eine mir.entity.GenericEntity erzeugt.
150          *
151          * @return Class-Objekt der Entity
152          */
153         public java.lang.Class getEntityClass () {
154                 return  theEntityClass;
155         }
156
157         /**
158          * Liefert die Standardbeschränkung von select-Statements zurück, also
159          * wieviel Datensätze per Default selektiert werden.
160          *
161          * @return Standard-Anzahl der Datensätze
162          */
163         public int getLimit () {
164                 return  defaultLimit;
165         }
166
167         /**
168          * Liefert den Namen des Primary-Keys zurück. Wird die Variable nicht von
169          * der erbenden Klasse überschrieben, so ist der Wert <code>PKEY</code>
170          * @return Name des Primary-Keys
171          */
172         public String getIdName () {
173                 return  thePKeyName;
174         }
175
176         /**
177          * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
178          *
179          * @return Name der Tabelle
180          */
181         public String getTableName () {
182                 return  theTable;
183         }
184
185         /*
186          *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS
187          *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
188          *   wird.
189          *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
190          *    the Table
191          */
192
193         public String getCoreTable(){
194                 if (theCoreTable!=null) return theCoreTable;
195                 else return theTable;
196         }
197
198         /**
199          * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
200          * @return int-Array mit den Typen der Felder
201          * @exception StorageObjectException
202          */
203         public int[] getTypes () throws StorageObjectException {
204                 if (metadataTypes == null)
205                         get_meta_data();
206                 return  metadataTypes;
207         }
208
209         /**
210          * Liefert eine Liste der Labels der Tabellenfelder
211          * @return ArrayListe mit Labeln
212          * @exception StorageObjectException
213          */
214         public ArrayList getLabels () throws StorageObjectException {
215                 if (metadataLabels == null)
216                         get_meta_data();
217                 return  metadataLabels;
218         }
219
220         /**
221          * Liefert eine Liste der Felder der Tabelle
222          * @return ArrayList mit Feldern
223          * @exception StorageObjectException
224          */
225         public ArrayList getFields () throws StorageObjectException {
226                 if (metadataFields == null)
227                         get_meta_data();
228                 return  metadataFields;
229         }
230
231
232         /*
233          *   Gets value out of ResultSet according to type and converts to String
234          *   @param inValue  Wert aus ResultSet.
235          *   @param aType  Datenbanktyp.
236          *   @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
237          *           dann /unsupported value/
238          */
239         private String getValueAsString (ResultSet rs, int valueIndex, int aType) throws StorageObjectException {
240                 String outValue = null;
241                 if (rs != null) {
242                         try {
243                                 switch (aType) {
244                                         case java.sql.Types.BIT:
245                                                 outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
246                                                 break;
247                                         case java.sql.Types.INTEGER:case java.sql.Types.SMALLINT:case java.sql.Types.TINYINT:case java.sql.Types.BIGINT:
248                                                 int out = rs.getInt(valueIndex);
249                                                 if (!rs.wasNull())
250                                                         outValue = new Integer(out).toString();
251                                                 break;
252                                         case java.sql.Types.NUMERIC:
253             /** @todo Numeric can be float or double depending upon
254              *  metadata.getScale() / especially with oracle */
255                                                 long outl = rs.getLong(valueIndex);
256                                                 if (!rs.wasNull())
257                                                         outValue = new Long(outl).toString();
258                                                 break;
259                                         case java.sql.Types.REAL:
260                                                 float tempf = rs.getFloat(valueIndex);
261                                                 if (!rs.wasNull()) {
262                                                         tempf *= 10;
263                                                         tempf += 0.5;
264                                                         int tempf_int = (int)tempf;
265                                                         tempf = (float)tempf_int;
266                                                         tempf /= 10;
267                                                         outValue = "" + tempf;
268                                                         outValue = outValue.replace('.', ',');
269                                                 }
270                                                 break;
271                                         case java.sql.Types.DOUBLE:
272                                                 double tempd = rs.getDouble(valueIndex);
273                                                 if (!rs.wasNull()) {
274                                                         tempd *= 10;
275                                                         tempd += 0.5;
276                                                         int tempd_int = (int)tempd;
277                                                         tempd = (double)tempd_int;
278                                                         tempd /= 10;
279                                                         outValue = "" + tempd;
280                                                         outValue = outValue.replace('.', ',');
281                                                 }
282                                                 break;
283                                         case java.sql.Types.CHAR:case java.sql.Types.VARCHAR:case java.sql.Types.LONGVARCHAR:
284                                                 outValue = rs.getString(valueIndex);
285                                                 //if (outValue != null)
286                                                         //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
287                                                 break;
288                                         case java.sql.Types.LONGVARBINARY:
289                                                 outValue = rs.getString(valueIndex);
290                                                 //if (outValue != null)
291                                                 //outValue = StringUtil.encodeHtml(StringUtil.unquote(outValue));
292                                                 break;
293                                         case java.sql.Types.TIMESTAMP:
294             // it's important to use Timestamp here as getting it
295             // as a string is undefined and is only there for debugging
296             // according to the API. we can make it a string through formatting.
297             // -mh
298                                           Timestamp timestamp = (rs.getTimestamp(valueIndex));
299             if(!rs.wasNull()) {
300               java.util.Date date = new java.util.Date(timestamp.getTime());
301               outValue = _dateFormatterOut.format(date);
302               _cal.setTime(date);
303               int offset = _cal.get(Calendar.ZONE_OFFSET)+
304                             _cal.get(Calendar.DST_OFFSET);
305               String tzOffset = StringUtil.zeroPaddingNumber(
306                                                      offset/_millisPerHour,2,2);
307               outValue = outValue+"+"+tzOffset;
308             }
309                                                 break;
310                                         default:
311                                                 outValue = "<unsupported value>";
312                                                 theLog.printWarning("Unsupported Datatype: at " + valueIndex +
313                                                                 " (" + aType + ")");
314                                 }
315                         } catch (SQLException e) {
316                                 throw  new StorageObjectException("Could not get Value out of Resultset -- "
317                                                 + e.toString());
318                         }
319                 }
320                 return  outValue;
321         }
322
323         /*
324          *   select-Operator um einen Datensatz zu bekommen.
325          *   @param id Primaerschluessel des Datensatzes.
326          *   @return liefert EntityObject des gefundenen Datensatzes oder null.
327          */
328         public Entity selectById(String id)     throws StorageObjectException
329   {
330                 if (id==null||id.equals(""))
331                         throw new StorageObjectException("id war null");
332
333     // ask object store for object
334     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
335       String uniqueId = id;
336       if ( theEntityClass.equals(StorableObjectEntity.class) )
337         uniqueId+="@"+theTable;
338       StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
339       theLog.printDebugInfo("CACHE: (dbg) looking for sid " + search_sid.toString());
340       Entity hit = (Entity)o_store.use(search_sid);
341       if ( hit!=null ) return hit;
342     }
343
344                 Statement stmt=null;Connection con=getPooledCon();
345                 Entity returnEntity=null;
346                 try {
347                         ResultSet rs;
348                         /** @todo better prepared statement */
349                         String selectSql = "select * from " + theTable + " where " + thePKeyName + "=" + id;
350                         stmt = con.createStatement();
351                         rs = executeSql(stmt, selectSql);
352                         if (rs != null) {
353                                 if (evaluatedMetaData==false) evalMetaData(rs.getMetaData());
354                                 if (rs.next())
355                                         returnEntity = makeEntityFromResultSet(rs);
356                                 else theLog.printDebugInfo("Keine daten fuer id: " + id + "in Tabelle" + theTable);
357                                 rs.close();
358                         }
359                         else {
360                                 theLog.printDebugInfo("No Data for Id " + id + " in Table " + theTable);
361                         }
362                 }
363                 catch (SQLException sqe){
364                         throwSQLException(sqe,"selectById"); return null;
365                 }
366                 catch (NumberFormatException e) {
367                         theLog.printError("ID ist keine Zahl: " + id);
368                 }
369                 finally { freeConnection(con,stmt); }
370
371                 /** @todo OS: Entity should be saved in ostore */
372                 return returnEntity;
373         }
374
375
376         /**
377          *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
378          *   @param key  Datenbankfeld der Bedingung.
379          *   @param value  Wert die der key anehmen muss.
380          *   @return EntityList mit den gematchten Entities
381          */
382         public EntityList selectByFieldValue(String aField, String aValue)
383                 throws StorageObjectException
384         {
385                 return selectByFieldValue(aField, aValue, 0);
386         }
387
388         /**
389          *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
390          *   @param key  Datenbankfeld der Bedingung.
391          *   @param value  Wert die der key anehmen muss.
392          *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
393          *   @return EntityList mit den gematchten Entities
394          */
395         public EntityList selectByFieldValue(String aField, String aValue, int offset)
396                 throws StorageObjectException
397         {
398                 return selectByWhereClause(aField + "=" + aValue, offset);
399         }
400
401
402         /**
403          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
404          * Also offset wird der erste Datensatz genommen.
405          *
406          * @param wc where-Clause
407          * @return EntityList mit den gematchten Entities
408          * @exception StorageObjectException
409          */
410         public EntityList selectByWhereClause(String where)
411                 throws StorageObjectException
412         {
413                 return selectByWhereClause(where, 0);
414         }
415
416
417         /**
418          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
419          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
420          *
421          * @param wc where-Clause
422          * @param offset ab welchem Datensatz.
423          * @return EntityList mit den gematchten Entities
424          * @exception StorageObjectException
425          */
426         public EntityList selectByWhereClause(String whereClause, int offset)
427                 throws StorageObjectException
428         {
429                 return selectByWhereClause(whereClause, null, offset);
430         }
431
432
433         /**
434          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
435          * Also offset wird der erste Datensatz genommen.
436          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
437          *
438          * @param wc where-Clause
439          * @param ob orderBy-Clause
440          * @return EntityList mit den gematchten Entities
441          * @exception StorageObjectException
442          */
443
444         public EntityList selectByWhereClause(String where, String order)
445                 throws StorageObjectException {
446                 return selectByWhereClause(where, order, 0);
447         }
448
449
450         /**
451          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
452          * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
453          *
454          * @param wc where-Clause
455          * @param ob orderBy-Clause
456          * @param offset ab welchem Datensatz
457          * @return EntityList mit den gematchten Entities
458          * @exception StorageObjectException
459          */
460
461         public EntityList selectByWhereClause(String whereClause, String orderBy, int offset)
462                 throws StorageObjectException {
463                 return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
464         }
465
466
467         /**
468          * select-Operator liefert eine EntityListe mit den gematchten Datensätzen zurück.
469          * @param wc where-Clause
470          * @param ob orderBy-Clause
471          * @param offset ab welchem Datensatz
472          * @param limit wieviele Datensätze
473          * @return EntityList mit den gematchten Entities
474          * @exception StorageObjectException
475          */
476
477         public EntityList selectByWhereClause(String wc, String ob, int offset, int limit)
478                 throws StorageObjectException
479   {
480
481     // check o_store for entitylist
482     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
483       StoreIdentifier search_sid =
484         new StoreIdentifier( theEntityClass,
485                              StoreContainerType.STOC_TYPE_ENTITYLIST,
486                              StoreUtil.getEntityListUniqueIdentifierFor(theTable,wc,ob,offset,limit) );
487       EntityList hit = (EntityList)o_store.use(search_sid);
488       if ( hit!=null ) {
489         theLog.printDebugInfo("CACHE (hit): " + search_sid.toString());
490         return hit;
491       }
492     }
493
494                 // local
495                 EntityList    theReturnList=null;
496                 Connection    con=null; Statement stmt=null;
497                 ResultSet     rs;
498                 int           offsetCount = 0, count=0;
499
500                 // build sql-statement
501
502                 /** @todo count sql string should only be assembled if we really count
503                  *  see below at the end of method //rk */
504
505                 if (wc != null && wc.length() == 0) {
506                         wc = null;
507                 }
508                 StringBuffer countSql = new StringBuffer("select count(*) from ").append(theTable);
509                 StringBuffer selectSql = new StringBuffer("select * from ").append(theTable);
510                 if (wc != null) {
511                         selectSql.append(" where ").append(wc);
512                         countSql.append(" where ").append(wc);
513                 }
514                 if (ob != null && !(ob.length() == 0)) {
515                         selectSql.append(" order by ").append(ob);
516                 }
517                 if (theAdaptor.hasLimit()) {
518                         if (limit > -1 && offset > -1) {
519                                 selectSql.append(" limit ");
520                                 if (theAdaptor.reverseLimit()) {
521                                         selectSql.append(limit).append(",").append(offset);
522                                 }
523                                 else {
524                                         selectSql.append(offset).append(",").append(limit);
525                                 }
526                         }
527                 }
528
529                 // execute sql
530                 try {
531                         con = getPooledCon();
532                         stmt = con.createStatement();
533
534                         // selecting...
535                         rs = executeSql(stmt, selectSql.toString());
536                         if (rs != null) {
537                                 if (!evaluatedMetaData) evalMetaData(rs.getMetaData());
538
539                                 theReturnList = new EntityList();
540                                 Entity theResultEntity;
541                                 while (rs.next()) {
542                                         theResultEntity = makeEntityFromResultSet(rs);
543                                         theReturnList.add(theResultEntity);
544                                         offsetCount++;
545                                 }
546                                 rs.close();
547                         }
548
549                         // making entitylist infos
550                         if (!(theAdaptor.hasLimit())) count = offsetCount;
551
552                         if (theReturnList != null) {
553                                 // now we decide if we have to know an overall count...
554                                 count=offsetCount;
555                                 if (limit > -1 && offset > -1) {
556                                         if (offsetCount==limit) {
557                                                 /** @todo counting should be deffered to entitylist
558                                                  *  getSize() should be used */
559                                                 rs = executeSql(stmt, countSql.toString());
560                                                 if (rs != null) {
561                                                         if ( rs.next() ) count = rs.getInt(1);
562                                                         rs.close();
563                                                 }
564                                                 else theLog.printError("Could not count: " + countSql);
565                                         }
566                                 }
567                                 theReturnList.setCount(count);
568                                 theReturnList.setOffset(offset);
569                                 theReturnList.setWhere(wc);
570                                 theReturnList.setOrder(ob);
571         theReturnList.setStorage(this);
572         theReturnList.setLimit(limit);
573                                 if ( offset >= limit )
574                                         theReturnList.setPrevBatch(offset - limit);
575                                 if ( offset+offsetCount < count )
576                                         theReturnList.setNextBatch(offset + limit);
577         if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
578           StoreIdentifier sid=theReturnList.getStoreIdentifier();
579           theLog.printDebugInfo("CACHE (add): " + sid.toString());
580           o_store.add(sid);
581         }
582                         }
583                 }
584                 catch (SQLException sqe) { throwSQLException(sqe, "selectByWhereClause"); }
585                 finally { freeConnection(con, stmt); }
586
587                 return  theReturnList;
588         }
589
590
591         /**
592          *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
593          *
594          *  @param rs Das ResultSetObjekt.
595          *  @return Entity Die Entity.
596          */
597         private Entity makeEntityFromResultSet (ResultSet rs)
598                 throws StorageObjectException
599         {
600                 /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
601                 HashMap theResultHash = new HashMap();
602                 String theResult = null;
603                 int theType;
604                 Entity returnEntity = null;
605                 try {
606                         int size = metadataFields.size();
607                         for (int i = 0; i < size; i++) {
608                                 // alle durchlaufen bis nix mehr da
609
610                                 theType = metadataTypes[i];
611                                 if (theType == java.sql.Types.LONGVARBINARY) {
612                                         InputStreamReader is = (InputStreamReader)rs.getCharacterStream(i + 1);
613                                         if (is != null) {
614                                                 char[] data = new char[32768];
615                                                 StringBuffer theResultString = new StringBuffer();
616                                                 int len;
617                                                 while ((len = is.read(data)) > 0) {
618                                                         theResultString.append(data, 0, len);
619                                                 }
620                                                 is.close();
621                                                 theResult = theResultString.toString();
622                                         }
623                                         else {
624                                                 theResult = null;
625                                         }
626                                 }
627                                 else {
628                                         theResult = getValueAsString(rs, (i + 1), theType);
629                                 }
630                                 if (theResult != null) {
631                                         theResultHash.put(metadataFields.get(i), theResult);
632                                 }
633                         }
634       if (theEntityClass != null) {
635         returnEntity = (Entity)theEntityClass.newInstance();
636         returnEntity.setValues(theResultHash);
637         returnEntity.setStorage(myselfDatabase);
638         if ( returnEntity instanceof StorableObject ) {
639           theLog.printDebugInfo("CACHE: ( in) " + returnEntity.getId() + " :"+theTable);
640           o_store.add(((StorableObject)returnEntity).getStoreIdentifier());
641         }
642       } else {
643         throwStorageObjectException("Internal Error: theEntityClass not set!");
644       }
645                 } catch (IllegalAccessException e) {
646                         throwStorageObjectException("Kein Zugriff! -- " + e.toString());
647                 } catch (IOException e) {
648                         throwStorageObjectException("IOException! -- " + e.toString());
649                 } catch (InstantiationException e) {
650                         throwStorageObjectException("Keine Instantiiierung! -- " + e.toString());
651                 } catch (SQLException sqe) {
652                         throwSQLException(sqe, "makeEntityFromResultSet");
653                         return  null;
654                 }
655                 return  returnEntity;
656         }
657
658         /**
659          * insert-Operator: fügt eine Entity in die Tabelle ein. Eine Spalte WEBDB_CREATE
660          * wird automatisch mit dem aktuellen Datum gefuellt.
661          *
662          * @param theEntity
663          * @return der Wert des Primary-keys der eingefügten Entity
664          */
665         public String insert (Entity theEntity) throws StorageObjectException {
666                 //cache
667                 invalidatePopupCache();
668
669     // invalidating all EntityLists corresponding with theEntityClass
670     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
671       StoreContainerType stoc_type =
672         StoreContainerType.valueOf( theEntityClass,
673                                     StoreContainerType.STOC_TYPE_ENTITYLIST);
674       o_store.invalidate(stoc_type);
675     }
676
677                 String returnId = null;
678                 Connection con = null; PreparedStatement pstmt = null;
679
680     try {
681                         ArrayList streamedInput = theEntity.streamedInput();
682                         StringBuffer f = new StringBuffer();
683                         StringBuffer v = new StringBuffer();
684                         String aField, aValue;
685                         boolean firstField = true;
686                         // make sql-string
687                         for (int i = 0; i < getFields().size(); i++) {
688                                 aField = (String)getFields().get(i);
689                                 if (!aField.equals(thePKeyName)) {
690                                         aValue = null;
691                                         // sonderfaelle
692                                         if (aField.equals("webdb_create") ||
693               aField.equals("webdb_lastchange")) {
694                                                 aValue = "NOW()";
695                                         }
696                                         else {
697                                                 if (streamedInput != null && streamedInput.contains(aField)) {
698                                                         aValue = "?";
699                                                 }
700                                                 else {
701                                                         if (theEntity.hasValueForField(aField)) {
702                                                                 aValue = "'" + StringUtil.quote((String)theEntity.getValue(aField))
703                                                                                 + "'";
704                                                         }
705                                                 }
706                                         }
707                                         // wenn Wert gegeben, dann einbauen
708                                         if (aValue != null) {
709                                                 if (firstField == false) {
710                                                         f.append(",");
711                                                         v.append(",");
712                                                 }
713                                                 else {
714                                                         firstField = false;
715                                                 }
716                                                 f.append(aField);
717                                                 v.append(aValue);
718                                         }
719                                 }
720                         }         // end for
721                         // insert into db
722                         StringBuffer sqlBuf = new StringBuffer("insert into ").append(theTable).append("(").append(f).append(") values (").append(v).append(")");
723                         String sql = sqlBuf.toString();
724                         theLog.printInfo("INSERT: " + sql);
725                         con = getPooledCon();
726                         con.setAutoCommit(false);
727                         pstmt = con.prepareStatement(sql);
728                         if (streamedInput != null) {
729                                 for (int i = 0; i < streamedInput.size(); i++) {
730                                         String inputString = (String)theEntity.getValue((String)streamedInput.get(i));
731                                         pstmt.setBytes(i + 1, inputString.getBytes());
732                                 }
733                         }
734                         int ret = pstmt.executeUpdate();
735                         if(ret == 0){
736                                 //insert failed
737                                 return null;
738                         }
739                         pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL((Database)myselfDatabase));
740                         ResultSet rs = pstmt.executeQuery();
741                         rs.next();
742                         returnId = rs.getString(1);
743                         theEntity.setId(returnId);
744                 } catch (SQLException sqe) {
745                         throwSQLException(sqe, "insert");
746                 } finally {
747                         try {
748                                 con.setAutoCommit(true);
749                         } catch (Exception e) {
750                                 ;
751                         }
752                         freeConnection(con, pstmt);
753                 }
754     /** @todo store entity in o_store */
755                 return  returnId;
756         }
757
758         /**
759          * update-Operator: aktualisiert eine Entity. Eine Spalte WEBDB_LASTCHANGE
760          * wird automatisch mit dem aktuellen Datum gefuellt.
761          *
762          * @param theEntity
763          */
764         public void update (Entity theEntity) throws StorageObjectException
765   {
766                 Connection con = null; PreparedStatement pstmt = null;
767                 /** @todo this is stupid: why do we prepare statement, when we
768                  *  throw it away afterwards. should be regular statement
769                  *  update/insert could better be one routine called save()
770                  *  that chooses to either insert or update depending if we
771                  *  have a primary key in the entity. i don't know if we
772                  *  still need the streamed input fields. // rk  */
773
774                 /** @todo extension: check if Entity did change, otherwise we don't need
775      *  the roundtrip to the database */
776
777                 /** invalidating corresponding entitylists in o_store*/
778     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
779       StoreContainerType stoc_type =
780         StoreContainerType.valueOf( theEntityClass,
781                                     StoreContainerType.STOC_TYPE_ENTITYLIST);
782       o_store.invalidate(stoc_type);
783     }
784
785                 ArrayList streamedInput = theEntity.streamedInput();
786                 String id = theEntity.getId();
787                 String aField;
788                 StringBuffer fv = new StringBuffer();
789                 boolean firstField = true;
790                 //cache
791                 invalidatePopupCache();
792                 // build sql statement
793                 for (int i = 0; i < getFields().size(); i++) {
794                         aField = (String)metadataFields.get(i);
795                         // only normal cases
796                         if (!(aField.equals(thePKeyName) || aField.equals("webdb_create") ||
797                                         aField.equals("webdb_lastchange") || (streamedInput != null && streamedInput.contains(aField)))) {
798                                 if (theEntity.hasValueForField(aField)) {
799                                         if (firstField == false) {
800                                                 fv.append(", ");
801                                         }
802                                         else {
803                                                 firstField = false;
804                                         }
805                                         fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
806                                 }
807                         }
808                 }
809                 StringBuffer sql = new StringBuffer("update ").append(theTable).append(" set ").append(fv);
810                 // exceptions
811                 if (metadataFields.contains("webdb_lastchange")) {
812                         sql.append(",webdb_lastchange=NOW()");
813                 }
814     // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
815     // format so anything extra will be ignored. -mh
816                 if (metadataFields.contains("webdb_create") &&
817         theEntity.hasValueForField("webdb_create")) {
818       // minimum of 10 (yyyy-mm-dd)...
819       if (theEntity.getValue("webdb_create").length() >= 10) {
820         String dateString = theEntity.getValue("webdb_create");
821         // if only 10, then add 00:00 so it doesn't throw a ParseException
822         if (dateString.length() == 10)
823           dateString=dateString+" 00:00";
824
825         // TimeStamp stuff
826         try {
827           java.util.Date d = _dateFormatterIn.parse(dateString);
828           Timestamp tStamp = new Timestamp(d.getTime());
829           sql.append(",webdb_create='"+tStamp.toString()+"'");
830         } catch (ParseException e) {
831           throw new StorageObjectException(e.toString());
832         }
833       }
834                 }
835                 if (streamedInput != null) {
836                         for (int i = 0; i < streamedInput.size(); i++) {
837                                 sql.append(",").append(streamedInput.get(i)).append("=?");
838                         }
839                 }
840                 sql.append(" where id=").append(id);
841                 theLog.printInfo("UPDATE: " + sql);
842                 // execute sql
843                 try {
844                         con = getPooledCon();
845                         con.setAutoCommit(false);
846                         pstmt = con.prepareStatement(sql.toString());
847                         if (streamedInput != null) {
848                                 for (int i = 0; i < streamedInput.size(); i++) {
849                                         String inputString = theEntity.getValue((String)streamedInput.get(i));
850                                         pstmt.setBytes(i + 1, inputString.getBytes());
851                                 }
852                         }
853                         pstmt.executeUpdate();
854                 } catch (SQLException sqe) {
855                         throwSQLException(sqe, "update");
856                 } finally {
857                         try {
858                                 con.setAutoCommit(true);
859                         } catch (Exception e) {
860                                 ;
861                         }
862                         freeConnection(con, pstmt);
863                 }
864         }
865
866         /*
867          *   delete-Operator
868          *   @param id des zu loeschenden Datensatzes
869          *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
870          */
871         public boolean delete (String id) throws StorageObjectException {
872
873                 invalidatePopupCache();
874     // ostore send notification
875     if ( StoreUtil.implementsStorableObject(theEntityClass) ) {
876       String uniqueId = id;
877       if ( theEntityClass.equals(StorableObjectEntity.class) )
878         uniqueId+="@"+theTable;
879                         theLog.printInfo("CACHE: (del) " + id);
880                         StoreIdentifier search_sid =
881         new StoreIdentifier(theEntityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
882       o_store.invalidate(search_sid);
883                 }
884
885                 /** @todo could be prepared Statement */
886                 Statement stmt = null; Connection con = null;
887                 int res = 0;
888                 String sql="delete from "+theTable+" where "+thePKeyName+"='"+id+"'";
889                 theLog.printInfo("DELETE " + sql);
890                 try {
891                         con = getPooledCon(); stmt = con.createStatement();
892                         res = stmt.executeUpdate(sql);
893                 }
894     catch (SQLException sqe) { throwSQLException(sqe, "delete"); }
895     finally { freeConnection(con, stmt); }
896
897                 return  (res > 0) ? true : false;
898         }
899
900         /* noch nicht implementiert.
901          * @return immer false
902          */
903         public boolean delete (EntityList theEntityList) {
904                 invalidatePopupCache();
905                 return  false;
906         }
907
908         /**
909          * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
910          * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
911          * @return null
912          */
913         public SimpleList getPopupData () throws StorageObjectException {
914                 return  null;
915         }
916
917         /**
918          *  Holt Daten fuer Popups.
919          *  @param name  Name des Feldes.
920          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
921          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
922          */
923         public SimpleList getPopupData (String name, boolean hasNullValue)
924                 throws StorageObjectException {
925                 return  getPopupData(name, hasNullValue, null);
926         }
927
928         /**
929          *  Holt Daten fuer Popups.
930          *  @param name  Name des Feldes.
931          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
932          *  @param where  Schraenkt die Selektion der Datensaetze ein.
933          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
934          */
935         public SimpleList getPopupData (String name, boolean hasNullValue, String where) throws StorageObjectException {
936          return  getPopupData(name, hasNullValue, where, null);
937         }
938
939         /**
940          *  Holt Daten fuer Popups.
941          *  @param name  Name des Feldes.
942          *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
943          *  @param where  Schraenkt die Selektion der Datensaetze ein.
944          *  @param order  Gibt ein Feld als Sortierkriterium an.
945          *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
946          */
947         public SimpleList getPopupData (String name, boolean hasNullValue, String where, String order) throws StorageObjectException {
948                 // caching
949                 if (hasPopupCache && popupCache != null)
950                         return  popupCache;
951                 SimpleList simpleList = null;
952                 Connection con = null;
953                 Statement stmt = null;
954                 // build sql
955                 StringBuffer sql = new StringBuffer("select ").append(thePKeyName)
956                                                                                                                                                                 .append(",").append(name).append(" from ")
957                                                                                                                                                                 .append(theTable);
958                 if (where != null && !(where.length() == 0))
959                         sql.append(" where ").append(where);
960                 sql.append(" order by ");
961                 if (order != null && !(order.length() == 0))
962                         sql.append(order);
963                 else
964                         sql.append(name);
965                 // execute sql
966                 try {
967                         con = getPooledCon();
968                 } catch (Exception e) {
969                         throw new StorageObjectException(e.toString());
970                 }
971                 try {
972                         stmt = con.createStatement();
973                         ResultSet rs = executeSql(stmt, sql.toString());
974
975                         if (rs != null) {
976                                 if (!evaluatedMetaData) get_meta_data();
977                                 simpleList = new SimpleList();
978                                 // if popup has null-selector
979                                 if (hasNullValue) simpleList.add(POPUP_EMTYLINE);
980
981                                 SimpleHash popupDict;
982                                 while (rs.next()) {
983                                         popupDict = new SimpleHash();
984                                         popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
985                                         popupDict.put("value", rs.getString(2));
986                                         simpleList.add(popupDict);
987                                 }
988                                 rs.close();
989                         }
990                 } catch (Exception e) {
991                         theLog.printError("getPopupData: "+e.toString());
992                         throw new StorageObjectException(e.toString());
993                 } finally {
994                         freeConnection(con, stmt);
995                 }
996
997                 if (hasPopupCache) popupCache = simpleList;
998                 return  simpleList;
999         }
1000
1001         /**
1002          * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
1003          * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
1004          * Tabellen Verwendung finden.
1005          * @return SimpleHash mit den Tabellezeilen.
1006          */
1007         public SimpleHash getHashData () {
1008                 /** @todo dangerous! this should have a flag to be enabled, otherwise
1009                  *  very big Hashes could be returned */
1010                 if (hashCache == null) {
1011                         try {
1012                                 hashCache = HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("",
1013                                                 -1));
1014                         } catch (StorageObjectException e) {
1015                                 theLog.printDebugInfo(e.toString());
1016                         }
1017                 }
1018                 return  hashCache;
1019         }
1020
1021         /* invalidates the popupCache
1022          */
1023         protected void invalidatePopupCache () {
1024                 /** @todo  invalidates toooo much */
1025                 popupCache = null;
1026                 hashCache = null;
1027         }
1028
1029         /**
1030          * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
1031          * @param stmt Statemnt
1032          * @param sql Sql-String
1033          * @return ResultSet
1034          * @exception StorageObjectException
1035          */
1036         public ResultSet executeSql (Statement stmt, String sql)
1037                 throws StorageObjectException, SQLException
1038         {
1039                 long startTime = System.currentTimeMillis();
1040                 ResultSet rs;
1041                 try {
1042                         rs = stmt.executeQuery(sql);
1043                         theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1044                                 + sql);
1045                 }
1046                 catch (SQLException e)
1047                 {
1048                         theLog.printDebugInfo("Failed: " + (System.currentTimeMillis()
1049                                                                                                                 - startTime) + "ms. for: "+ sql);
1050                         throw e;
1051                 }
1052
1053                 return  rs;
1054         }
1055
1056         /**
1057          * Fuehrt Statement stmt aus und liefert Resultset zurueck. Das SQL-Statment wird
1058          * getimed und geloggt.
1059          * @param stmt PreparedStatement mit der SQL-Anweisung
1060          * @return Liefert ResultSet des Statements zurueck.
1061          * @exception StorageObjectException, SQLException
1062          */
1063         public ResultSet executeSql (PreparedStatement stmt)
1064                 throws StorageObjectException, SQLException {
1065
1066                 long startTime = (new java.util.Date()).getTime();
1067                 ResultSet rs = stmt.executeQuery();
1068                 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms.");
1069                 return  rs;
1070         }
1071
1072                 /**
1073          * returns the number of rows in the table
1074          */
1075         public int getSize(String where)
1076                 throws SQLException,StorageObjectException
1077         {
1078                 long  startTime = System.currentTimeMillis();
1079                 String sql = "SELECT Count(*) FROM "+ theTable;
1080                 if (where != null && !(where.length() == 0))
1081                   sql = sql + " where " + where;
1082                 Connection con = null;
1083                 Statement stmt = null;
1084                 int result = 0;
1085
1086                 try {
1087                         con = getPooledCon();
1088                         stmt = con.createStatement();
1089                         ResultSet rs = executeSql(stmt,sql);
1090                         while(rs.next()){
1091                                 result = rs.getInt(1);
1092                         }
1093                 } catch (SQLException e) {
1094                         theLog.printError(e.toString());
1095                 } finally {
1096                         freeConnection(con,stmt);
1097                 }
1098                 //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
1099                 theLog.printInfo((System.currentTimeMillis() - startTime) + "ms. for: "
1100                                                                                 + sql);
1101                 return result;
1102         }
1103
1104         public int executeUpdate(Statement stmt, String sql)
1105                 throws StorageObjectException, SQLException
1106         {
1107                 int rs;
1108                 long  startTime = (new java.util.Date()).getTime();
1109                 try
1110                 {
1111                         rs = stmt.executeUpdate(sql);
1112                         theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1113                                                                                                 + sql);
1114                 }
1115                 catch (SQLException e)
1116                 {
1117                         theLog.printDebugInfo("Failed: " + (new java.util.Date().getTime()
1118                                                                                                                 - startTime) + "ms. for: "+ sql);
1119                         throw e;
1120                 }
1121                 return rs;
1122         }
1123
1124         public int executeUpdate(String sql)
1125                 throws StorageObjectException, SQLException
1126         {
1127                 int result=-1;
1128                 long  startTime = (new java.util.Date()).getTime();
1129                 Connection con=null;PreparedStatement pstmt=null;
1130                 try {
1131                         con=getPooledCon();
1132                         pstmt = con.prepareStatement(sql);
1133                         result = pstmt.executeUpdate();
1134                 }
1135                 catch (Exception e) {
1136                         theLog.printDebugInfo("settimage :: setImage gescheitert: "+e.toString());
1137                         throw new StorageObjectException("executeUpdate failed: "+e.toString());
1138                 }
1139                 finally { freeConnection(con,pstmt); }
1140                 theLog.printInfo((new java.util.Date().getTime() - startTime) + "ms. for: "
1141                                                                                 + sql);
1142                 return result;
1143         }
1144
1145         /**
1146          * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
1147          * @param md ResultSetMetaData
1148          * @exception StorageObjectException
1149          */
1150         private void evalMetaData (ResultSetMetaData md)
1151                 throws StorageObjectException {
1152
1153                 this.evaluatedMetaData = true;
1154                 this.metadataFields = new ArrayList();
1155                 this.metadataLabels = new ArrayList();
1156                 this.metadataNotNullFields = new ArrayList();
1157                 try {
1158                         int numFields = md.getColumnCount();
1159                         this.metadataTypes = new int[numFields];
1160                         String aField;
1161                         int aType;
1162                         for (int i = 1; i <= numFields; i++) {
1163                                 aField = md.getColumnName(i);
1164                                 metadataFields.add(aField);
1165                                 metadataLabels.add(md.getColumnLabel(i));
1166                                 aType = md.getColumnType(i);
1167                                 metadataTypes[i - 1] = aType;
1168                                 if (aField.equals(thePKeyName)) {
1169                                         thePKeyType = aType; thePKeyIndex = i;
1170                                 }
1171                                 if (md.isNullable(i) == md.columnNullable) {
1172                                         metadataNotNullFields.add(aField);
1173                                 }
1174                         }
1175                 } catch (SQLException e) {
1176                         throwSQLException(e, "evalMetaData");
1177                 }
1178         }
1179
1180         /**
1181          *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
1182          *  um die alle Columns und Typen einer Tabelle zu ermitteln.
1183          */
1184         private void get_meta_data () throws StorageObjectException {
1185                 Connection con = null;
1186                 PreparedStatement pstmt = null;
1187                 String sql = "select * from " + theTable + " where 0=1";
1188                 try {
1189                         con = getPooledCon();
1190                         pstmt = con.prepareStatement(sql);
1191                         theLog.printInfo("METADATA: " + sql);
1192                         ResultSet rs = pstmt.executeQuery();
1193                         evalMetaData(rs.getMetaData());
1194                         rs.close();
1195                 } catch (SQLException e) {
1196                         throwSQLException(e, "get_meta_data");
1197                 } finally {
1198                         freeConnection(con, pstmt);
1199                 }
1200         }
1201
1202
1203         public Connection getPooledCon() throws StorageObjectException {
1204                 /* @todo , doublecheck but I'm pretty sure that this is unnecessary. -mh
1205                         try{
1206                         Class.forName("com.codestudio.sql.PoolMan").newInstance();
1207                 } catch (Exception e){
1208                         throw new StorageObjectException("Could not find the PoolMan Driver"
1209                                                                                                                                                                 +e.toString());
1210                 }*/
1211                 Connection con = null;
1212                 try{
1213                         con = SQLManager.getInstance().requestConnection();
1214                 } catch(SQLException e){
1215                         theLog.printError("could not connect to the database "+e.toString());
1216                         System.err.println("could not connect to the database "+e.toString());
1217                         throw new StorageObjectException("Could not connect to the database"+
1218                                                                                                                                                                 e.toString());
1219                 }
1220                 return con;
1221         }
1222
1223         public void freeConnection (Connection con, Statement stmt)
1224                 throws StorageObjectException {
1225                 SQLManager.getInstance().closeStatement(stmt);
1226                 SQLManager.getInstance().returnConnection(con);
1227         }
1228
1229         /**
1230          * Wertet SQLException aus und wirft dannach eine StorageObjectException
1231          * @param sqe SQLException
1232          * @param wo Funktonsname, in der die SQLException geworfen wurde
1233          * @exception StorageObjectException
1234          */
1235         protected void throwSQLException (SQLException sqe, String wo)
1236                 throws StorageObjectException {
1237                 String state = "";
1238                 String message = "";
1239                 int vendor = 0;
1240                 if (sqe != null) {
1241                         state = sqe.getSQLState();
1242                         message = sqe.getMessage();
1243                         vendor = sqe.getErrorCode();
1244                 }
1245                 theLog.printError(state + ": " + vendor + " : " + message + " Funktion: "
1246                                 + wo);
1247                 throw  new StorageObjectException((sqe == null) ? "undefined sql exception" :
1248                                 sqe.toString());
1249         }
1250
1251         protected void _throwStorageObjectException (Exception e, String wo)
1252                 throws StorageObjectException {
1253                 if (e != null) {
1254                                 theLog.printError(e.toString()+ wo);
1255                                 throw  new StorageObjectException(wo + e.toString());
1256                 } else {
1257                                 theLog.printError(wo);
1258                                 throw  new StorageObjectException(wo);
1259                 }
1260
1261         }
1262
1263         /**
1264          * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
1265          * eine StorageObjectException
1266          * @param message Nachricht mit dem Fehler
1267          * @exception StorageObjectException
1268          */
1269         void throwStorageObjectException (String message)
1270                 throws StorageObjectException {
1271                 _throwStorageObjectException(null, message);
1272         }
1273
1274 }
1275
1276
1277