pax_global_header00006660000000000000000000000064132761005100014505gustar00rootroot0000000000000052 comment=dda4655140ff01862221fdfe90a6a1047338c9ce jameica-datasource-2.8.1+dfsg/000077500000000000000000000000001327610051000161555ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/.classpath000077500000000000000000000007571327610051000201540ustar00rootroot00000000000000 jameica-datasource-2.8.1+dfsg/.cvsignore000077500000000000000000000000151327610051000201540ustar00rootroot00000000000000releases bin jameica-datasource-2.8.1+dfsg/.gitignore000066400000000000000000000000421327610051000201410ustar00rootroot00000000000000/releases /test-bin /bin/ /target jameica-datasource-2.8.1+dfsg/.project000077500000000000000000000005611327610051000176310ustar00rootroot00000000000000 datasource org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature jameica-datasource-2.8.1+dfsg/.settings/000077500000000000000000000000001327610051000200735ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/.settings/org.eclipse.core.resources.prefs000066400000000000000000000001341327610051000263040ustar00rootroot00000000000000#Tue Jul 24 17:11:24 CEST 2007 eclipse.preferences.version=1 encoding/=ISO-8859-15 jameica-datasource-2.8.1+dfsg/LICENSE000066400000000000000000000636361327610051000172000ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! jameica-datasource-2.8.1+dfsg/build/000077500000000000000000000000001327610051000172545ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/build/BUILD000077500000000000000000000001241327610051000200360ustar00rootroot00000000000000#Build Number for ANT. Do not edit! #Mon Apr 30 10:59:50 CEST 2018 build.number=219 jameica-datasource-2.8.1+dfsg/build/README000077500000000000000000000001151327610051000201340ustar00rootroot00000000000000An object relational mapper with RMI support Copyright (C) 2004 Olaf Willuhn jameica-datasource-2.8.1+dfsg/build/RELEASE000077500000000000000000000000051327610051000202550ustar00rootroot000000000000002.8.0jameica-datasource-2.8.1+dfsg/build/build.properties000077500000000000000000000004001327610051000224660ustar00rootroot00000000000000define.util.dir = ../util define.compilepath = ${define.util.dir}/bin/; define.javadoc.package = de.willuhn define.java.version = 1.7 define.encoding = ISO-8859-15 define.lib.name = de_willuhn_ds jameica-datasource-2.8.1+dfsg/build/build.xml000077500000000000000000000133741327610051000211100ustar00rootroot00000000000000 jameica-datasource-2.8.1+dfsg/pom.xml000066400000000000000000000063621327610051000175010ustar00rootroot00000000000000 4.0.0 de.willuhn.jameica jameica-datasource 2.6.7-SNAPSHOT Jameica Datasource ORM Mapper ISO-8859-1 ISO-8859-1 ISO-8859-1 1.7 1.7 src/ de.willuhn.jameica jameica-util 2.6.7-SNAPSHOT com.mckoi mckoisqldb 1.0.5 junit junit 4.12 test ${project.build.sourceDirectory} ${basedir}/test org.apache.maven.plugins maven-compiler-plugin 3.5.1 ${project.build.sourceEncoding} ${maven.compiler.source} ${maven.compiler.source} org.apache.maven.plugins maven-source-plugin attach-sources jar org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar doclint-java8-disable [1.8,) org.apache.maven.plugins maven-javadoc-plugin -Xdoclint:none jameica-datasource-2.8.1+dfsg/src/000077500000000000000000000000001327610051000167445ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/000077500000000000000000000000001327610051000173345ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/willuhn/000077500000000000000000000000001327610051000210165ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/000077500000000000000000000000001327610051000231505ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/BeanUtil.java000066400000000000000000000204601327610051000255200ustar00rootroot00000000000000/********************************************************************** * * Copyright (c) by Olaf Willuhn * All rights reserved * **********************************************************************/ package de.willuhn.datasource; import java.beans.Expression; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.willuhn.logging.Logger; /** * Hilfsklasse, um auf gemeinsame Weise sowhl GenericObjects als auch regulaere Beans generisch nutzen zu koennen. */ public class BeanUtil { /** * Liefert die Property-Namen einer Bean. * @param bean die Bean. * @return die Property-Namen gemaess Bean-Spec. Das sind die Namen der Properties basierend auf * den gefundenen public Getter-Methoden. * @throws RemoteException */ public static List getProperties(Object bean) throws RemoteException { List result = new ArrayList(); if (bean == null) return result; if (bean instanceof GenericObject) { GenericObject o = (GenericObject) bean; result.addAll(Arrays.asList(o.getAttributeNames())); return result; } Method[] methods = bean.getClass().getMethods(); if (methods == null || methods.length == 0) return result; for (Method m:methods) { String name = m.getName(); if (name.startsWith("get") && name.length() > 3) result.add(toProperty(name)); } return result; } /** * Fuehrt auf der uebergebenen Bean die zugehoerige Getter-Methode zum genannten Attibut aus. * @param bean die Bean. * @param attribute Name des Attributes. Ein "get" wird automatisch vorangestellt. * @return der Rueckgabe-Wert der Methode. * @throws RemoteException */ public static Object get(Object bean, String attribute) throws RemoteException { if (bean == null) return null; if (attribute == null) return toString(bean); for (int i=0;i<10;++i) // Rekursion in die Kind-Beans - maximal aber 10 Stufen. Wenn es mehr sind, ist irgendwas faul ;) { int dot = attribute.indexOf("."); if (dot == -1) break; String s = attribute.substring(0,dot); bean = get(bean,s); if (bean == null) return null; // Hier gehts nicht mehr weiter attribute = attribute.substring(dot+1); } if (bean instanceof GenericObject) return ((GenericObject)bean).getAttribute(attribute); try { return invoke(bean,toGetMethod(attribute),null); } catch (RemoteException re) { throw re; } catch (NoSuchMethodException nme) { // Fallback: try { return invoke(bean,attribute,null); } catch (RemoteException re) { throw re; } catch (NoSuchMethodException nme2) { Logger.trace(nme.getMessage()); return null; } catch (Exception e) { throw new RemoteException("unable to get attribute " + attribute,e); } } catch (Exception e) { throw new RemoteException("unable to get attribute " + attribute,e); } } /** * Fuehrt auf der uebergebenen Bean die zugehoerige Setter-Methode zum genannten Attibut aus. * @param bean die Bean. * @param attribute Name des Attributes. Ein "set" wird automatisch vorangestellt. * @param param der zu uebergebende Parameter. * @throws RemoteException */ public static void set(Object bean, String attribute, Object param) throws RemoteException { set(bean,attribute, new Object[]{param}); } /** * Fuehrt auf der uebergebenen Bean die zugehoerige Setter-Methode zum genannten Attibut aus. * @param bean die Bean. * @param attribute Name des Attributes. Ein "set" wird automatisch vorangestellt. * @param params die zu uebergebenden Parameter. * @throws RemoteException */ public static void set(Object bean, String attribute, Object params[]) throws RemoteException { try { invoke(bean,toSetMethod(attribute),params); } catch (RemoteException re) { throw re; } catch (Exception e) { throw new RemoteException("unable to set attribute " + attribute,e); } } /** * Liefert eine toString-Repraesentation des Objektes. * Handelt es sich um ein GenericObject, wird der Wert des Primaer-Attributes zurueckgeliefert. * @param bean die Bean. * @return die String-Repraesentation. * @throws RemoteException */ public static String toString(Object bean) throws RemoteException { if (bean == null) return null; if (bean instanceof GenericObject) { GenericObject gb = (GenericObject) bean; Object value = gb.getAttribute(gb.getPrimaryAttribute()); return value == null ? null : value.toString(); } return bean.toString(); } /** * Vergleicht zwei Objekte. * Handelt es sich um Objekte des Typs GenericObject, werden deren equals-Methoden verwendet. * @param a Objekt a. * @param b Objekt b. * @return True, wenn beide Objekte gleich sind. * @throws RemoteException */ public static boolean equals(Object a, Object b) throws RemoteException { if (a == b) return true; if (a == null || b == null) return false; if ((a instanceof GenericObject) && (b instanceof GenericObject)) return ((GenericObject)a).equals((GenericObject)b); return a.equals(b); } /** * Macht aus einem Attribut-Namen einen Getter. * @param attribute Name des Attributes. * @return der erzeugte Methodenname. */ public static String toGetMethod(String attribute) { return "get" + attribute.substring(0,1).toUpperCase() + attribute.substring(1); } /** * Macht aus einem Attribut-Namen einen Setter. * @param attribute Name des Attributes. * @return der erzeugte Methodenname. */ public static String toSetMethod(String attribute) { return "set" + attribute.substring(0,1).toUpperCase() + attribute.substring(1); } /** * Macht aus einem Getter/Setter den Attribut-Namen. * @param method der Methoden-Name. * @return der Attribut-Name. */ public static String toProperty(String method) { if (method.length() > 3 && (method.startsWith("get") || method.startsWith("set"))) return method.substring(3,4).toLowerCase() + method.substring(4); return method; } /** * Fuehrt auf der uebergebenen Bean genannte Methode aus. * @param bean die Bean. * @param method der Methodenname. * @param params die zu uebergebenden Parameter. * @return der Rueckgabe-Wert der Methode. * @throws Exception */ public static Object invoke(Object bean, String method, Object params[]) throws Exception { Expression ex = new Expression(bean,method,params); return ex.getValue(); } /** * Liefert die Typisierung einer Klasse. * @param c die Klasse, deren Typisierung ermittelt werden soll. * @return der konkrete Typ der Klasse oder NULL, wenn sie nicht typisiert ist. */ public static Class getType(Class c) { if (c == null) { Logger.warn("no (typed) class given"); return null; } // Gefunden in http://www.nautsch.net/2008/10/29/class-von-type-parameter-java-generics-gepimpt/ // Generics-Voodoo ;) // 1. check super class Class ct = getActualType(c.getGenericSuperclass()); if (ct != null) return ct; // 2. check interfaces Type[] interfaces = c.getGenericInterfaces(); if (interfaces == null || interfaces.length == 0) return null; // keine Interfaces for (Type t:interfaces) { ct = getActualType(t); if (ct != null) return ct; } return null; // kein Typ gefunden } /** * Liefert die konkrete Typisierung des Typs. * @param type der zu pruefende Typ. * @return der konkrete Typ oder NULL. */ private static Class getActualType(Type type) { if (!(type instanceof ParameterizedType)) return null; ParameterizedType pType = (ParameterizedType) type; Type[] types = pType.getActualTypeArguments(); if (types == null || types.length == 0) return null; if (!(types[0] instanceof Class)) return null; return (Class) types[0]; } } jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/GenericIterator.java000077500000000000000000000033621327610051000271100ustar00rootroot00000000000000/********************************************************************** * * Copyright (c) by Olaf Willuhn * All rights reserved * **********************************************************************/ package de.willuhn.datasource; import java.rmi.Remote; import java.rmi.RemoteException; /** * generischer RMI-tauglicher Iterator. * @param der konkrete Objekt-Typ. */ public interface GenericIterator extends Remote { /** * Liefert true, wenn weitere Elemente in diesem Iterator existieren. * @return true, wenn weitere Elemente vorhanden sind. * @throws RemoteException */ public boolean hasNext() throws RemoteException; /** * Liefert das aktuelle Element der Iteration und blaettert um ein Element weiter. * @return aktuelles Element. * @throws RemoteException */ public T next() throws RemoteException; /** * Liefert das aktuelle Element der Iteration und blaetter um ein Element zurueck. * @return aktuelles Element. * @throws RemoteException */ public T previous() throws RemoteException; /** * Blaettert den Iterator wieder an den Anfang zurueck. Somit kann er erneut * durchlaufen werden. * @throws RemoteException */ public void begin() throws RemoteException; /** * Liefert die Anzahl der Elemente dieses Iterators. * @return Anzahl der Elemente in dem Iterator. * @throws RemoteException */ public int size() throws RemoteException; /** * Prueft, ob das uebergebene Objekt in der aktuellen Liste vorhanden ist. * @param o das zu pruefende Objekt. * @return null wenn kein Objekt uebereinstimmt, andernfalls das ueberinstimmende Objekt aus dieser Liste. * @throws RemoteException */ public T contains(T o) throws RemoteException; } jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/GenericObject.java000077500000000000000000000055731327610051000265330ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/GenericObject.java,v $ * $Revision: 1.2 $ * $Date: 2004/12/09 23:22:25 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource; import java.rmi.Remote; import java.rmi.RemoteException; /** * Generisches RMI-faehiges Objekt, welches Attribute besitzt. * Das kann also so ziemlich alles sein, vom Kalendereintrag bis * zum Datensatz in einer Datenbank. Entscheidendes Merkmal ist, * dass es eine Funktion getAttribute(AliasName) besitzt, * mit der die Werte der Attribute ueber Aliasnamen abgefragt * werden koennen. */ public interface GenericObject extends Remote { /** * Liefert den Wert des angegebenen Attributes. * @param name Name des Attributes. * @return Wert des Attributes. * @throws RemoteException im Fehlerfall. */ public Object getAttribute(String name) throws RemoteException; /** * Liefert ein String-Array mit allen verfuegbaren Attribut-Namen. * @return Liste aller Attribut-Namen. * @throws RemoteException */ public String[] getAttributeNames() throws RemoteException; /** * Liefert einen Identifier fuer dieses Objekt. * Dieser muss innerhalb des gesamten Systems/Services fuer diese Objektart eindeutig sein. * @return der Identifier des Objektes. * @throws RemoteException */ public String getID() throws RemoteException; /** * Liefert den Namen des Primaer-Attributes dieses Objektes. * Hintergrund: Wenn man z.Bsp. in einer Select-Box nur einen Wert * anzeigen kann, dann wird dieser genommen. * Achtung: Die Funktion liefert nicht den Wert des Attributes sondern nur dessen Namen. * @return Name des Primaer-Attributes. * @throws RemoteException im Fehlerfall. */ public String getPrimaryAttribute() throws RemoteException; /** * Vergleicht dieses Objekt mit dem uebergebenen. * Achtung: Wir ueberschreiben hier nicht die equals-Funktion von Object * da das via RMI nicht geht. * @param other das zu vergleichende Objekt. * @return true, die Objekte gleiche Eigenschaften besitzen. * @throws RemoteException */ public boolean equals(GenericObject other) throws RemoteException; } /********************************************************************** * $Log: GenericObject.java,v $ * Revision 1.2 2004/12/09 23:22:25 willuhn * @N getAttributeNames nun Bestandteil der API * * Revision 1.1 2004/07/21 23:53:56 willuhn * @C massive Refactoring ;) * * Revision 1.2 2004/06/17 00:28:01 willuhn * *** empty log message *** * * Revision 1.1 2004/06/17 00:05:50 willuhn * @N GenericObject, GenericIterator * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/GenericObjectNode.java000077500000000000000000000065021327610051000273320ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/GenericObjectNode.java,v $ * $Revision: 1.3 $ * $Date: 2006/04/20 08:34:13 $ * $Author: web0 $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource; import java.rmi.RemoteException; /** * Generisches RMI-faehiges Objekt, welches von genericObject * abgeleitet ist, jedoch noch Funktionen zur Abbildung einer Baumstruktur mitbringt. */ public interface GenericObjectNode extends GenericObject { /** * Liefert einen Iterator mit allen direkten Kind-Objekten * des aktuellen Objektes. Jedoch keine Kindes-Kinder. * @return Iterator mit den direkten Kind-Objekten. * @throws RemoteException */ public GenericIterator getChildren() throws RemoteException; /** * Prueft, ob das uebergeben Node-Objekt ein Kind des aktuellen * ist. Dabei wird der gesamte Baum ab hier rekursiv durchsucht. * @param object das zu testende Objekt. * @return true wenn es ein Kind ist, sonst false. * @throws RemoteException */ public boolean hasChild(GenericObjectNode object) throws RemoteException; /** * Liefert das Eltern-Element des aktuellen oder null, wenn es sich * bereits auf oberster Ebene befindet. * @return das Eltern-Objekt oder null. * @throws RemoteException */ public GenericObjectNode getParent() throws RemoteException; /** * Liefert alle moeglichen Eltern-Objekte dieses Objektes. * Das sind nicht die tatsaechlichen Eltern (denn jedes Objekt * kann ja nur ein Eltern-Objekt haben) sondern eine Liste * der Objekte, an die es als Kind gehangen werden werden. * Das ist z.Bsp. sinnvoll, wenn man ein Kind-Element im Baum * woanders hinhaengenn will. Da das Objekt jedoch nicht an * eines seiner eigenen Kinder und auch nicht an sich selbst * gehangen werden kann (Rekursion) liefert diese Funktion nur * die moeglichen Eltern-Objekte. * @return Liste der moeglichen Eltern-Objekte. * @throws RemoteException */ public GenericIterator getPossibleParents() throws RemoteException; /** * Liefert eine Liste mit allen Eltern-Objekten bis hoch zum * Root-Objekt. Also sowas wie ein voller Verzeichnisname, jedoch * andersrum. Das oberste Element steht am Ende der Liste. * @return Liste aller Elternobjekte bis zum Root-Objekt. * @throws RemoteException */ public GenericIterator getPath() throws RemoteException; } /********************************************************************* * $Log: GenericObjectNode.java,v $ * Revision 1.3 2006/04/20 08:34:13 web0 * @C s/Childs/Children/ * * Revision 1.2 2004/08/11 23:36:34 willuhn * @N Node Objekte in GenericObjectNode und DBObjectNode aufgeteilt * * Revision 1.1 2004/07/21 23:53:56 willuhn * @C massive Refactoring ;) * * Revision 1.1 2004/06/17 00:05:50 willuhn * @N GenericObject, GenericIterator * * Revision 1.1 2004/01/10 14:52:19 willuhn * @C package removings * * Revision 1.1 2004/01/08 20:46:44 willuhn * @N database stuff separated from jameica * * Revision 1.1 2003/12/19 01:43:27 willuhn * @N added Tree * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/Service.java000077500000000000000000000052501327610051000254200ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/Service.java,v $ * $Revision: 1.4 $ * $Date: 2004/09/15 22:31:20 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource; import java.rmi.Remote; import java.rmi.RemoteException; /** * Basis-Interface aller Services, die via RMI genutzt werden koennen. * @author willuhn */ public interface Service extends Remote { /** * Startet den Service. * @throws RemoteException */ public void start() throws RemoteException; /** * Prueft, ob dieser Service gestartet ist. * @throws RemoteException * @return true wenn er gestartet ist, sonst false. */ public boolean isStarted() throws RemoteException; /** * Prueft, ob der Service gestartet werden darf. * @return true, wenn er gestartet werden darf, sonst false. * @throws RemoteException */ public boolean isStartable() throws RemoteException; /** * Stoppt den Service. * @param restartAllowed legt fest, ob der Service im laufenden Betrieb neu gestartet werden kann. * @throws RemoteException */ public void stop(boolean restartAllowed) throws RemoteException; /** * Liefert den sprechenden Namen des Services. * @return Name des Services. * @throws RemoteException */ public String getName() throws RemoteException; } /********************************************************************* * $Log: Service.java,v $ * Revision 1.4 2004/09/15 22:31:20 willuhn * *** empty log message *** * * Revision 1.3 2004/09/14 23:27:32 willuhn * @C redesign of service handling * * Revision 1.2 2004/08/31 17:33:11 willuhn * *** empty log message *** * * Revision 1.1 2004/07/21 23:53:56 willuhn * @C massive Refactoring ;) * * Revision 1.5 2004/06/30 20:58:07 willuhn * @C some refactoring * * Revision 1.4 2004/06/17 00:05:50 willuhn * @N GenericObject, GenericIterator * * Revision 1.3 2004/03/18 01:24:17 willuhn * @C refactoring * * Revision 1.2 2004/03/06 18:24:34 willuhn * @D javadoc * * Revision 1.1 2004/01/10 14:52:19 willuhn * @C package removings * * Revision 1.2 2004/01/08 21:38:47 willuhn * *** empty log message *** * * Revision 1.1 2004/01/08 20:46:44 willuhn * @N database stuff separated from jameica * * Revision 1.3 2003/12/12 21:11:29 willuhn * @N ObjectMetaCache * * Revision 1.2 2003/10/29 00:41:27 willuhn * *** empty log message *** * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/000077500000000000000000000000001327610051000235355ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/AbstractDBObject.java000077500000000000000000001256111327610051000275110ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/AbstractDBObject.java,v $ * $Revision: 1.73 $ * $Date: 2011/07/19 13:08:30 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import de.willuhn.datasource.GenericObject; import de.willuhn.datasource.db.types.Type; import de.willuhn.datasource.db.types.TypeRegistry; import de.willuhn.datasource.rmi.DBIterator; import de.willuhn.datasource.rmi.DBObject; import de.willuhn.datasource.rmi.Event; import de.willuhn.datasource.rmi.Listener; import de.willuhn.datasource.rmi.ObjectNotFoundException; import de.willuhn.logging.Logger; import de.willuhn.util.ApplicationException; import de.willuhn.util.Session; /** * Basisklasse fuer alle Business-Objekte * @author willuhn */ public abstract class AbstractDBObject extends UnicastRemoteObject implements DBObject { // Der Primary-Key des Objektes private String id; // Haelt die Eigenschaften des Objektes. private HashMap properties = new HashMap(); // Backup der Eigenschaften des Objektes, um Aenderungen zu ueberwachen private HashMap origProperties = new HashMap(); // Haelt die Datentypen der Properties. private HashMap types = new HashMap(); // definiert, ob das Objekt gerade in einer manuellen Transaktion ist private transient static Session transactions = new Session(5 * 60 * 1000l); // 5 Minuten // ein Cache fuer ForeignObjects private HashMap foreignObjectCache = new HashMap(); private transient DBServiceImpl service = null; private transient Connection conn = null; private transient ArrayList deleteListeners = null; private transient ArrayList storeListeners = null; private boolean upper = false; /** * ct * @throws RemoteException */ public AbstractDBObject() throws RemoteException { super(); // Konstruktor von UnicastRemoteObject } /** * Speichert den Service-Provider. * @param service * @throws Exception */ protected void setService(DBServiceImpl service) throws Exception { this.service = service; conn = service.getConnection(); if (conn == null) throw new SQLException("connection is null"); } /** * Liefert die Exception, die dieses Objekt gerade benutzt. * @return die Connection dieses Objektes. */ private Connection getConnection() { return conn; } /** * Liefert den Service-Provider. * @return Service. */ protected DBServiceImpl getService() { return service; } /** * Prueft, ob die Datenbankverbindung existiert und funktioniert. * @throws RemoteException wird geworfen, wenn die Connection kaputt ist. */ private void checkConnection() throws RemoteException { if (getConnection() == null) throw new RemoteException("database connection not set."); } /** * Holt sich die Meta-Daten der Tabelle und erzeugt die Properties. * @throws SQLException Wenn beim Laden der Meta-Daten ein Datenbank-Fehler auftrat. */ protected void init() throws SQLException { try { checkConnection(); } catch (RemoteException e) { throw new SQLException(e.getMessage()); } if (isInitialized()) return; // allready initialized // Checken, ob die Datenbank Uppercase ist this.upper = Boolean.getBoolean(getService().getClass().getName() + ".uppercase"); HashMap cachedMeta = ObjectMetaCache.getMetaData(getService().getClass(),this.getClass()); if (cachedMeta != null) { // Treffer. Die Daten nehmen wir. this.types = cachedMeta; Iterator i = cachedMeta.keySet().iterator(); while (i.hasNext()) { String s = (String) i.next(); if (s == null) continue; this.properties.put(s,null); } return; } String tableName = getTableName(); if (this.upper) tableName = tableName.toUpperCase(); ResultSet meta = null; try { String schema = System.getProperty(getService().getClass().getName() + ".schema",null); // BUGZILLA 960 try { meta = getConnection().getMetaData().getColumns(null,schema,tableName,null); } catch (Exception e) { Logger.trace("unable to fetch table meta-data using NULL column name pattern, trying '%', see https://bugs.mysql.com/bug.php?id=81105"); meta = getConnection().getMetaData().getColumns(null,schema,tableName,"%"); } String field; if (!meta.next()) throw new SQLException("database table not found: " + tableName); do { field = meta.getString("COLUMN_NAME"); if (field == null || field.equalsIgnoreCase(this.getIDField())) // skip empty fields and primary key continue; properties.put(this.upper ? field.toLowerCase() : field,null); types.put(this.upper ? field.toLowerCase() : field,meta.getString("TYPE_NAME")); } while (meta.next()); ObjectMetaCache.setMetaData(getService().getClass(),this.getClass(),types); } catch (SQLException e) { throw e; } finally { try { if (meta != null) meta.close(); } catch (Exception e) {/*useless*/} } } /** * Prueft, ob das Objekt initialisiert ist. * @return true, wenn es initialisiert ist. */ private boolean isInitialized() { return ( this.properties != null && this.properties.size() > 0 && this.types != null && this.types.size() > 0 ); } /** * Prueft, ob wir gerade in einer Transaktion sind. * @return true, wenn wir in einer Transaktion sind. */ private boolean inTransaction() { synchronized(transactions) { Transaction t = getTransaction(); return (t != null && t.count > 0); } } /** * Liefert die aktuelle Transaktion oder null. * @return Transaktion oder null. */ private Transaction getTransaction() { synchronized(transactions) { return (Transaction) transactions.get(getConnection()); } } /** * @see de.willuhn.datasource.rmi.DBObject#load(java.lang.String) */ public final void load(String id) throws RemoteException { checkConnection(); this.id = ((id == null || id.equals("")) ? null : id); if (this.id == null) return; // nothing to load if (!isInitialized()) throw new RemoteException("object not initialized."); String tableName = getTableName(); if (this.upper) tableName = tableName.toUpperCase(); Statement stmt = null; ResultSet data = null; try { stmt = getConnection().createStatement(); String load = getLoadQuery(); Logger.debug("executing query: " + load); data = stmt.executeQuery(load); if (!data.next()) { throw new ObjectNotFoundException("object [id: " + id + ", type: " + this.getClass().getName() + "] not found"); } fill(data); } catch (SQLException e) { throw new RemoteException("unable to load data from table " + tableName,e); } finally { try { if (data != null) data.close(); } catch (Throwable t) {/*useless*/} try { if (stmt != null) stmt.close(); } catch (Throwable t) {/*useless*/} } } /** * Fuellt das Objekt mit den Daten aus dem Resultset. * @param rs * @throws SQLException * @throws RemoteException */ void fill(ResultSet rs) throws SQLException, RemoteException { String[] attributes = getAttributeNames(); for (int i=0;i * Ist der Parameter vom Typ dbObject nimmt die Funktion an, dass * es sich um einen Fremdschluessel handelt und speichert automatisch statt * des Objektes selbst nur dessen ID mittels new Integer(((DBObject)value).getID()). * @return vorheriger Wert des Feldes. * @throws RemoteException */ public Object setAttribute(String fieldName, Object value) throws RemoteException { if (fieldName == null) return null; return properties.put(fieldName, value); } /** * @see de.willuhn.datasource.GenericObject#getAttributeNames() */ public final String[] getAttributeNames() throws RemoteException { Set s = properties.keySet(); return (String[]) s.toArray(new String[s.size()]); } /** * Wird bei einem Insert aufgerufen, ermittelt die ID des erzeugten Datensatzes und speichert sie in diesem Objekt. * @return die letzte ID. * @throws SQLException * @throws RemoteException */ private String getLastId() throws SQLException, RemoteException { checkConnection(); Statement stmt = null; ResultSet rs = null; try { String tableName = getTableName(); String idField = getIDField(); if (this.upper) { tableName = tableName.toUpperCase(); idField = idField.toUpperCase(); } stmt = getConnection().createStatement(); rs = stmt.executeQuery("select max(" + idField + ") from " + tableName); if (!rs.next()) throw new SQLException("select max(id) returned empty resultset"); return rs.getString(1); } finally { if (rs != null) { try { rs.close(); } catch (SQLException se) {/*useless*/} } if (stmt != null) { try { stmt.close(); } catch (SQLException se) {/*useless*/} } } } /** * Speichert das Objekt explizit als neuen Datensatz in der Datenbank. * Die Funktion wird auch dann ein Insert versuchen, wenn das Objekt * bereits eine ID besitzt. Das ist z.Bsp. sinnvoll, wenn das Objekt * von einer Datenbank auf eine andere kopiert werden soll. Es kann jedoch * durchaus fehlschlagen, wenn ein Objekt mit dieser ID bereits in * der Datenbank existiert. * @throws RemoteException Wenn beim Speichern Fehler aufgetreten sind. * @throws ApplicationException Durch insertCheck() erzeugte Benutzerfehler. */ public void insert() throws RemoteException, ApplicationException { checkConnection(); if (!isInitialized()) throw new RemoteException("object not initialized."); insertCheck(); PreparedStatement stmt = null; ResultSet rs = null; try { stmt = getInsertSQL(); stmt.executeUpdate(); // Wenn wir noch keine ID haben (das ist immer dann der Fall, wenn // wir sie nicht explizit vor dem Insert angegeben haben - also der // Normalfall), dann holen wir sie uns if (this.id == null) { try { rs = stmt.getGeneratedKeys(); if (rs.next()) this.id = rs.getString(1); } catch (SQLException e) { // Das darf passieren, wenn die Datenbank das nicht unterstuetzt // In dem Fall greifen dann die folgenden Zeilen mit getLastId() } } // Es kann sein, dass der Treiber "Statement.RETURN_GENERATED_KEYS" // nicht unterstuetzt. In dem Fall muessen wir uns die ID selbst // holen. if (this.id == null) this.id = getLastId(); boolean tx = this.inTransaction(); this.created = tx; // Rollback-Markierung nur setzen, wenn wir in einer Transaktion sind // Sonst auto-commit if (!tx) { getConnection().commit(); } notify(storeListeners); } catch (SQLException e) { this.id = null; // Der Datensatz gilt als nicht gespeichert if (!this.inTransaction()) { try { getConnection().rollback(); throw new RemoteException("insert failed, rollback successful",e); } catch (SQLException e2) { throw new RemoteException("insert failed, rollback failed",e2); } } throw new RemoteException("insert failed",e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException se) {/*useless*/} } if (stmt != null) { try { stmt.close(); } catch (SQLException se) {/*useless*/} } } } /** * Aktualisiert das Objekt explizit in der Datenbank. * Wenn es sich um ein neues Objekt handelt, wird das Update fehlschlagen. * @throws RemoteException Wenn beim Update Fehler aufgetreten sind. * @throws ApplicationException durch updateCheck() erzeugte Benutzer-Fehler. */ private void update() throws RemoteException, ApplicationException { checkConnection(); if (!isInitialized()) throw new RemoteException("object not initialized."); if (isNewObject()) { // Objekt hat keine ID. Von daher kann's auch nicht upgedated werden throw new RemoteException("object is new - cannot update"); } updateCheck(); PreparedStatement stmt = null; int affected = 0; try { stmt = getUpdateSQL(); if (stmt == null) return; affected = stmt.executeUpdate(); if (affected != 1) { // Wenn nicht genau ein Datensatz geaendert wurde, ist was faul. throw new SQLException("update ambiguous"); } if (!this.inTransaction()) getConnection().commit(); notify(storeListeners); this.origProperties.putAll(this.properties); } catch (SQLException e) { if (!this.inTransaction()) { try { getConnection().rollback(); throw new RemoteException("update failed, rollback successful",e); } catch (SQLException e2) { throw new RemoteException("update failed, rollback failed",e2); } } throw new RemoteException("update failed",e); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se) {/*useless*/} } } /** * Liefert das automatisch erzeugte SQL-Statement fuer ein Update. * Kann bei Bedarf ueberschrieben um ein vom dynamisch erzeugten * abweichendes Statement f�r die Speicherung zu verwenden. * Die Funktion darf zurueckliefern, wenn nichts zu aendern ist. * @return das erzeugte SQL-Statement. * @throws RemoteException wenn beim Erzugen des Statements ein Fehler auftrat. */ protected PreparedStatement getUpdateSQL() throws RemoteException { checkConnection(); String tableName = getTableName(); String idField = getIDField(); if (this.upper) { tableName = tableName.toUpperCase(); idField = idField.toUpperCase(); } String sql = "update " + tableName + " set "; String[] attributes = getAttributeNames(); int count = 0; for (int i=0;igetIDField auch liefert, da das von DBIteratorImpl gelesen wird. * Also z.Bsp. "select " + getIDField() + " from " + getTableName(). * Kann bei Bedarf �berschrieben um ein abweichendes Statement zu verwenden. * Die Funktion muss das Statement nur dewegen als String zurueckliefern, * weil es typischerweise von DBIterator weiterverwendet wird und dort eventuell * noch weitere Filterkriterien hinzugefuegt werden koennen muessen. * @return das erzeugte SQL-Statement. */ protected String getListQuery() { // return "select " + getIDField() + " from " + getTableName(); String tableName = getTableName(); if (this.upper) tableName = tableName.toUpperCase(); return "select " + tableName + ".* from " + tableName; } /** * Liefert das automatisch erzeugte SQL-Statement zum Laden des Objektes. * Hierbei werden die Eigenschaften des Objektes geladen, dessen ID aktuell * von getID() geliefert wird. * ACHTUNG: Das Statement muss alle Felder selecten (*). * Also z.Bsp. "select * from " + getTableName() + " where " + getIDField() + " = " + getID(); * Kann bei Bedarf �berschrieben um ein abweichendes Statement zu verwenden. * @return das erzeugte SQL-Statement. * @throws RemoteException Wenn beim Erzeugen des Statements ein Fehler auftrat. */ protected String getLoadQuery() throws RemoteException { String tableName = getTableName(); String idField = getIDField(); if (this.upper) { tableName = tableName.toUpperCase(); idField = idField.toUpperCase(); } try { return "select * from " + tableName + " where " + idField + " = "+Integer.parseInt(this.getID()); } catch (NumberFormatException e) { return "select * from " + tableName + " where " + idField + " = '"+this.getID()+"'"; } } /** * Macht sozusagen das Typ-Mapping bei Insert und Update. * Hintergrund: Die Funktionen getInsertSQL() und * getUpdateSQL() erzeugen ja die Statements fuer * Insert und Update. Da ein PreparedStatement ja typsichere * Werte haben muss, rufen beide Funktion diese hier auf, um * hier die Werte korrekt setzen zu lassen. * @param stmt das PreparedStatement. * @param index der Index im Statement. * @param type Bezeichnung des Feld-Typs entspechend der types-Mappingtabelle. * @param value der Wert. * @throws SQLException */ private void setStmtValue(PreparedStatement stmt, int index, String type, Object value) throws SQLException { index++; // Wer zur Hoelle hat sich ausgedacht, dass Arrays bei Index 0, PreparedStatements aber bei 1 anfangen?? Grr Type t = TypeRegistry.getType(type); t.set(stmt,index,value); } /** * @see de.willuhn.datasource.rmi.DBObject#isNewObject() */ public final boolean isNewObject() throws RemoteException { return getID() == null; } /** * Liefert den Namen der Spalte, in der sich der Primary-Key befindet. * Default: "id". * @return Name der Spalte mit dem Primary-Key. */ protected String getIDField() { return upper ? "ID" : "id"; } /** * Liefert den Namen der repraesentierenden SQL-Tabelle. * Muss von allen abgeleiteten Klassen implementiert werden. * @return Name der repraesentierenden SQL-Tabelle. */ protected abstract String getTableName(); /** * @see de.willuhn.datasource.GenericObject#getPrimaryAttribute() */ public abstract String getPrimaryAttribute() throws RemoteException; /** * Diese Methode wird intern vor der Ausfuehrung von delete() * aufgerufen. Sie muss �berschrieben werden, damit das Fachobjekt * vor dem Durchf�hren der L�schaktion Pr�fungen vornehmen kann. * Z.Bsp. ob eventuell noch Abhaengigkeiten existieren und * das Objekt daher nicht gel�scht werden kann. * @throws ApplicationException wenn das Objekt nicht gel�scht werden darf. */ protected void deleteCheck() throws ApplicationException { } /** * Diese Methode wird intern vor der Ausfuehrung von insert() * aufgerufen. Sie muss �berschrieben werden, damit das Fachobjekt * vor dem Durchf�hren der Speicherung Pr�fungen vornehmen kann. * Z.Bsp. ob alle Pflichtfelder ausgef�llt sind und korrekte Werte enthalten. * @throws ApplicationException wenn das Objekt nicht gespeichert werden darf. */ protected void insertCheck() throws ApplicationException { } /** * Diese Methode wird intern vor der Ausfuehrung von update() * aufgerufen. Sie muss �berschrieben werden, damit das Fachobjekt * vor dem Durchf�hren der Speicherung Pr�fungen vornehmen kann. * Z.Bsp. ob alle Pflichtfelder ausgef�llt sind und korrekte Werte enthalten. * @throws ApplicationException wenn das Objekt nicht gespeichert werden darf. */ protected void updateCheck() throws ApplicationException { } /** * Prueft, ob das angegebene Feld ein Fremschluessel zu einer * anderen Tabelle ist. Wenn das der Fall ist, liefert es die * Klasse, die die Fremd-Tabelle abbildet. Andernfalls null. * @param field das zu pruefende Feld. * @return Klasse (abgeleitet von DBObject) welche den Fremdschluessel abbildet oder null. * @throws RemoteException im Fehlerfall. */ protected Class getForeignObject(String field) throws RemoteException { return null; } /** * @see de.willuhn.datasource.rmi.DBObject#transactionBegin() */ public final void transactionBegin() throws RemoteException { synchronized(transactions) { checkConnection(); Transaction tr = getTransaction(); if (tr == null) tr = new Transaction(); tr.count++; if (tr.count > 5) Logger.warn("[begin] transaction count: " + tr.count + " - forgotten to rollback/commit?"); Logger.debug("[begin] transaction count: " + tr.count); } } private boolean created = false; /** * @see de.willuhn.datasource.rmi.DBObject#transactionRollback() */ public final void transactionRollback() throws RemoteException { synchronized(transactions) { // Erkennt, ob das rollback nach einem Insert ausgefuehrt wurde. // Ist das der Fall, muss das Member mit der ID geloescht werden, // denn es existiert ja nicht in der DB. if (created) { this.id = null; this.created = false; } if (!this.inTransaction()) { Logger.debug("[rollback] rollback without begin or transaction allready rolled back"); return; } checkConnection(); Transaction tr = getTransaction(); if (tr == null) { Logger.debug("[rollback] rollback called, but no transaction found"); return; } tr.count--; Logger.debug("[rollback] transaction count: " + tr.count); if (tr.count > 0) return; try { Logger.debug("[rollback] transaction rollback"); getConnection().rollback(); } catch (SQLException e) { throw new RemoteException("rollback failed",e); } } } /** * @see de.willuhn.datasource.rmi.DBObject#transactionCommit() */ public final void transactionCommit() throws RemoteException { synchronized(transactions) { if (!this.inTransaction()) { Logger.debug("[commit] transaction commit without begin or transaction allready commited, skipping"); return; } checkConnection(); Transaction tr = getTransaction(); if (tr == null) { Logger.debug("[commit] commit called, but no transaction found"); return; } tr.count--; Logger.debug("[commit] transaction count: " + tr.count); if (tr.count > 0) return; try { Logger.debug("[commit] transaction commit"); getConnection().commit(); // Transaktion ist durch. Egal, ob das Ojekt gerade erstellt wurde oder // schon existierte. Jetzt ist es auf jeden Fall nicht mehr frisch. this.created = false; } catch (SQLException se) { try { getConnection().rollback(); throw new RemoteException("commit failed, rollback successful",se); } catch (SQLException se2) { throw new RemoteException("commit failed, rollback failed",se2); } } } } /** * @see de.willuhn.datasource.rmi.DBObject#getList() */ public DBIterator getList() throws RemoteException { return new DBIteratorImpl(this,service); } /** * @see de.willuhn.datasource.rmi.DBObject#overwrite(de.willuhn.datasource.rmi.DBObject) */ public void overwrite(DBObject object) throws RemoteException { if (object == null) return; if (!object.getClass().equals(this.getClass())) return; String[] attributes = getAttributeNames(); for (int i=0;i 10000) { Logger.error("max recursion limit reached for [" + this.getTableName() + ":" + this.getID() + "]"); return false; // limit recursion } child = (GenericObjectNode) childs.next(); // Direktes Kind? if (child.equals(object)) return true; // Kindes-Kinder checken if (child.hasChild(object)) return true; } return false; } /** * @see de.willuhn.datasource.GenericObjectNode#getParent() */ public GenericObjectNode getParent() throws RemoteException { DBIterator list = getList(); Object parent = this.getAttribute(this.getNodeField()); if (parent == null) return null; if (parent instanceof DBObject) parent = ((DBObject) parent).getID(); list.addFilter(getIDField() + "=" + parent); if (!list.hasNext()) return null; return (GenericObjectNode) list.next(); } /** * @see de.willuhn.datasource.GenericObjectNode#getPossibleParents() */ public GenericIterator getPossibleParents() throws RemoteException { DBIterator list = this.getList(); if (!this.isNewObject()) list.addFilter(getIDField() + " != "+this.getID()); // Objekt darf nicht sich selbst als Eltern-Objekt haben ArrayList array = new ArrayList(); GenericObjectNode element = null; while (list.hasNext()) { element = (GenericObjectNode) list.next(); if (!this.hasChild(element)) { // Kinder duerfen keine Eltern sein array.add(element.getID()); } } return new DBIteratorImpl(this,array,getService()); } /** * @see de.willuhn.datasource.GenericObjectNode#getPath() */ public GenericIterator getPath() throws RemoteException { ArrayList objectArray = new ArrayList(); boolean reached = false; GenericObjectNode currentObject = this.getParent(); if (currentObject == null) { // keine Eltern-Objekte. Also liefern wir eine leere Liste. return new DBIteratorImpl(this,objectArray,getService()); } objectArray.add(currentObject.getID()); GenericObjectNode object = null; while (!reached) { object = currentObject.getParent(); if (object != null) { objectArray.add(object.getID()); currentObject = object; } else { reached = true; } } return new DBIteratorImpl(this,objectArray,getService()); } /** * Da Objekte in einem Baum Abhaengigkeiten untereinander haben, * muessen diese vorm Loeschen geprueft werden. Grundsaetzliche * Checks koennen wir bereits hier durchfuehren. Zum Beispiel * ist es nicht moeglich, ein Objekt zu loeschen, wenn es * Kind-Objekte hat. * @see de.willuhn.datasource.db.AbstractDBObject#deleteCheck() */ protected void deleteCheck() throws ApplicationException { try { GenericIterator list = getChildren(); if (list.hasNext()) throw new ApplicationException("Objekt kann nicht gelöscht werden da Abhängigkeiten existieren."); } catch (RemoteException e) { Logger.error("error while checking children",e); throw new ApplicationException("Fehler beim Prüfen der Abhängigkeiten."); } } /** * Prueft, ob das angegebene Eltern-Objekt (insofern vorhanden) erlaubt ist. * Sprich: Es wird geprueft, ob es nicht auf sich selbst zurueckzeigt * und ob das Eltern-Element nicht gleichzeitig ein Kind-Element ist. * @see de.willuhn.datasource.db.AbstractDBObject#insertCheck() */ protected void insertCheck() throws ApplicationException { // Wir pruefen, ob das Objekt an gueltiger Stelle eingehaengt wurde. try { GenericObjectNode parent = getParent(); if (parent == null) return; GenericIterator parents = getPossibleParents(); while (parents.hasNext()) { GenericObjectNode node = (GenericObjectNode) parents.next(); if (node.equals(parent)) return; // Angegebenes Eltern-Objekt ist eines der erlaubten Eltern } throw new ApplicationException("Angegebenes Eltern-Objekt nicht erlaubt"); } catch (RemoteException e) { Logger.error("error while checking children",e); throw new ApplicationException("Fehler beim Prüfen der Abhängigkeiten."); } } /** * @see de.willuhn.datasource.db.AbstractDBObject#updateCheck() */ protected void updateCheck() throws ApplicationException { insertCheck(); } /** * @see de.willuhn.datasource.rmi.DBObjectNode#setParent(de.willuhn.datasource.rmi.DBObjectNode) */ public void setParent(DBObjectNode parent) throws RemoteException { setAttribute(getNodeField(),parent); } } /********************************************************************* * $Log: AbstractDBObjectNode.java,v $ * Revision 1.18 2011/07/29 08:55:12 willuhn * @B Das SQL-Statement fuer getParent() in AbstractDBObjectNode war ungueltig * * Revision 1.17 2011-07-29 08:46:00 willuhn * @B falsches Encoding * @B fehlendes Log * * Revision 1.16 2010-08-29 22:10:17 willuhn * *** empty log message *** * * Revision 1.15 2009/11/09 10:34:18 willuhn * *** empty log message *** * * Revision 1.14 2009/02/23 22:42:05 willuhn * @B Falscher Check in hasChild * * Revision 1.13 2009/02/23 22:31:08 willuhn * *** empty log message *** * * Revision 1.12 2009/02/23 22:25:06 willuhn * *** empty log message *** * * Revision 1.11 2009/02/23 22:13:49 willuhn * @N setParent(DBObjectNode) in DBObjectNode * * Revision 1.10 2006/04/20 08:34:12 web0 * @C s/Childs/Children/ * * Revision 1.9 2004/08/11 23:36:34 willuhn * @N Node Objekte in GenericObjectNode und DBObjectNode aufgeteilt * * Revision 1.8 2004/08/02 11:53:59 willuhn * *** empty log message *** * * Revision 1.7 2004/08/02 10:31:41 willuhn * *** empty log message *** * * Revision 1.6 2004/07/21 23:53:56 willuhn * @C massive Refactoring ;) * * Revision 1.5 2004/06/17 00:05:50 willuhn * @N GenericObject, GenericIterator * * Revision 1.4 2004/03/29 20:36:23 willuhn * *** empty log message *** * * Revision 1.3 2004/03/18 01:24:16 willuhn * @C refactoring * * Revision 1.2 2004/03/06 18:24:34 willuhn * @D javadoc * * Revision 1.1 2004/01/10 14:52:19 willuhn * @C package removings * * Revision 1.1 2004/01/08 20:46:43 willuhn * @N database stuff separated from jameica * * Revision 1.2 2003/12/19 01:43:26 willuhn * @N added Tree * * Revision 1.1 2003/12/18 21:47:12 willuhn * @N AbstractDBObjectNode * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/DBIteratorImpl.java000077500000000000000000000170231327610051000272270ustar00rootroot00000000000000/********************************************************************** * * Copyright (c) by Olaf Willuhn * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Types; import java.util.ArrayList; import java.util.List; import de.willuhn.datasource.rmi.DBIterator; import de.willuhn.datasource.rmi.DBService; import de.willuhn.logging.Logger; /** * Kleiner Hilfsiterator zum Holen von Listen von Objekten aus der Datenbank. * @param der konkrete Typ. */ public class DBIteratorImpl extends UnicastRemoteObject implements DBIterator { private DBService service = null; private Connection conn = null; private T object = null; private String filter = ""; private String order = ""; private int limit = -1; private ArrayList params = new ArrayList(); private String joins = ""; private List list = new ArrayList(); private int index = 0; private boolean initialized = false; /** * Erzeugt einen neuen Iterator. * @param object Objekt, fuer welches die Liste erzeugt werden soll. * @param service der Datenbankservice. * @throws RemoteException */ DBIteratorImpl(T object, DBServiceImpl service) throws RemoteException { if (object == null) throw new RemoteException("given object type is null"); this.object = object; this.service = service; this.conn = service.getConnection(); if (conn == null) throw new RemoteException("given connection is null"); } /** * Erzeugt einen neuen Iterator mit der uebergebenen Liste von IDs. * @param object Objekt, fuer welches die Liste erzeugt werden soll. * @param list eine vorgefertigte Liste. * @param service der Datenbank-Service. * @throws RemoteException */ DBIteratorImpl(T object, ArrayList list, DBServiceImpl service) throws RemoteException { this(object,service); if (list == null) throw new RemoteException("given list is null"); try { for (int i=0;i 0) sql += " limit " + Integer.toString(this.limit); return sql; } /** * Initialisiert den Iterator. * @throws RemoteException */ private void init() throws RemoteException { if (this.initialized) return; // allready initialzed PreparedStatement stmt = null; String sql = null; ResultSet rs = null; try { sql = prepareSQL(); stmt = conn.prepareStatement(sql); for (int i=0;i 0); } /** * @see de.willuhn.datasource.GenericIterator#next() */ public T next() throws RemoteException { init(); try { return list.get(index++); } catch (Exception e) { throw new RemoteException(e.getMessage()); } } /** * @see de.willuhn.datasource.GenericIterator#previous() */ public T previous() throws RemoteException { init(); try { return list.get(index--); } catch (Exception e) { throw new RemoteException(e.getMessage()); } } /** * @see de.willuhn.datasource.GenericIterator#size() */ public int size() throws RemoteException { init(); return list.size(); } /** * @see de.willuhn.datasource.GenericIterator#begin() */ public void begin() throws RemoteException { this.index = 0; } /** * @see de.willuhn.datasource.GenericIterator#contains(de.willuhn.datasource.GenericObject) */ public T contains(T other) throws RemoteException { init(); if (other == null) return null; if (!other.getClass().equals(object.getClass())) return null; // wir koennen uns die Iteration sparen. T object = null; for (int i=0;i 0) { Logger.info("transaction isolation level: " + trLevel); conn.setTransactionIsolation(trLevel); } } catch (SQLException e) { throw new RemoteException("autocommit=false failed or transaction isolation level not supported",e); } Logger.info("created new connection for " + (key == null ? "" : key)); this.connections.put(key,conn); } return conn; } /** * Liefert den Client-Host oder null. * @return ein Client-Identifier. */ private String getClientIdentifier() { try { return UnicastRemoteObject.getClientHost(); } catch (Throwable t) { // ignore } return null; } /** * Erstellt eine neue Connection. * @return die neu erstellte Connection. * @throws RemoteException */ private Connection createConnection() throws RemoteException { Logger.info("creating new connection"); String url = getJdbcUrl(); try { String username = getJdbcUsername(); String password = getJdbcPassword(); if (username != null && username.length() > 0 && password != null) return DriverManager.getConnection(url,username,password); return DriverManager.getConnection(url); } catch (SQLException e2) { throw new RemoteException("connection to database." + url + " failed",e2); } } /** * Schliesst die uebergebene Connection. * @param conn */ private void closeConnection(Connection conn) { if (conn == null) return; try { Logger.info("commit connection"); try { conn.commit(); } catch (Exception e) { Logger.warn("commit failed"); } Logger.info("closing connection"); conn.close(); Logger.info("connection closed"); } catch (Throwable t) { Logger.error("error while closing connection. message: " + t.getMessage()); } } /** * Kann von abgeleiteten Klassen ueberschrieben werden, um die Connection * zu testen. * @param conn die zu testende Connection. Ist nie null. * @throws SQLException */ protected void checkConnection(Connection conn) throws SQLException { } /** * Definiert einen optionalen Classfinder, der von dem Service * zum Laden von Objekten genommen werden soll. * Konkret wird er in creatObject und createList * verwendet, um zum uebergebenen Interface eine passende Implementierung * zu finden. Dabei wird die Funktion findImplementor() im * ClassFinder befragt.
* Wurde kein ClassFinder angegeben, versucht der Service direkt die * uebergebene Klasse zu instanziieren. Ist dies der Fall, koennen den * beiden create-Methoden natuerliche keine Interfaces-Klassen uebergeben werden. * @param finder zu verwendender ClassFinder. */ protected void setClassFinder(ClassFinder finder) { this.finder = finder; } /** * Definiert einen optionalen benutzerdefinierten Classloader. * Wird er nicht gesetzt, wird Class.forName() benutzt. * @param loader Benutzerdefinierter Classloader. */ protected void setClassloader(ClassLoader loader) { this.loader = loader; } /** * @see de.willuhn.datasource.Service#isStartable() */ public synchronized boolean isStartable() throws RemoteException { return startable; } /** * @see de.willuhn.datasource.Service#start() */ public synchronized void start() throws RemoteException { if (isStarted()) return; if (!isStartable()) throw new RemoteException("service restart not allowed"); Logger.info("starting db service"); try { Logger.info("request from host: " + UnicastRemoteObject.getClientHost()); } catch (ServerNotActiveException soe) {} String driver = getJdbcDriver(); try { if (loader != null) { try { DriverManager.registerDriver(new MyDriver(driver,loader)); } catch (Throwable t) { throw new RemoteException("unable to load jdbc driver",t); } } else { Class.forName(driver); } } catch (ClassNotFoundException e2) { Logger.error("unable to load jdbc driver " + driver,e2); throw new RemoteException("unable to load jdbc driver " + driver,e2); } started = true; } /** * @see de.willuhn.datasource.Service#stop(boolean) */ public synchronized void stop(boolean restartAllowed) throws RemoteException { if (!started) { Logger.info("service allready stopped"); return; } String key = getClientIdentifier(); if (key != null) { // Das ist eine Remote-Client, der sich disconnected. // Wir stoppen nicht den Service sondern melden nur // den Client ab Logger.info("disconnect client " + key); closeConnection((Connection) this.connections.remove(key)); return; } try { startable = restartAllowed; Logger.info("stopping db service"); try { Logger.info("stop request from host: " + getClientHost()); } catch (ServerNotActiveException soe) {} Logger.debug("db service: object cache matches: " + ObjectMetaCache.getStats() + " %"); int count = 0; synchronized(this.connections) { Iterator i = this.connections.keySet().iterator(); while (i.hasNext()) { key = (String) i.next(); closeConnection((Connection) this.connections.remove(key)); count++; } } Logger.info("db service stopped [" + count + " connection(s) closed]"); } finally { started = false; } } /** * Erzeugt ein neues Objekt aus der angegeben Klasse. * @param c Klasse des zu erstellenden Objekts. * @return das erzeugte Objekt. * @throws Exception wenn beim Erzeugen des Objektes ein Fehler auftrat. */ private T create(Class c) throws Exception { Class clazz = c; if (this.finder != null) { Class[] found = finder.findImplementors(c); clazz = found[found.length-1]; // wir nehmen das letzte Element. Das ist am naehesten dran. } if (clazz.isInterface()) throw new Exception("no classfinder defined: unable to find implementor for interface " + c.getName()); Constructor ct = clazz.getConstructor(new Class[]{}); ct.setAccessible(true); AbstractDBObject o = (AbstractDBObject) ct.newInstance(new Object[] {}); o.setService(this); o.init(); return (T)o; } /** * @see de.willuhn.datasource.rmi.DBService#createObject(java.lang.Class, java.lang.String) */ public T createObject(Class c, String identifier) throws RemoteException { checkStarted(); try { Logger.debug("try to create new DBObject. request from host: " + getClientHost()); } catch (ServerNotActiveException soe) {} try { T o = create(c); o.load(identifier); return o; } catch (RemoteException re) { throw re; } catch (Exception e) { Logger.error("unable to create object " + (c == null ? "unknown" : c.getName()),e); throw new RemoteException("unable to create object " + (c == null ? "unknown" : c.getName()),e); } } /** * @see de.willuhn.datasource.rmi.DBService#createList(java.lang.Class) */ public DBIterator createList(Class c) throws RemoteException { checkStarted(); try { Logger.debug("try to create new DBIterator. request from host: " + getClientHost()); } catch (ServerNotActiveException soe) {} try { T o = create(c); return new DBIteratorImpl((AbstractDBObject)o,this); } catch (RemoteException re) { throw re; } catch (Exception e) { Logger.error("unable to create list for object " + c.getName(),e); throw new RemoteException("unable to create list for object " + c.getName(),e); } } /** * @see de.willuhn.datasource.rmi.DBService#execute(java.lang.String, java.lang.Object[], de.willuhn.datasource.rmi.ResultSetExtractor) */ public Object execute(String sql, Object[] params, ResultSetExtractor extractor) throws RemoteException { checkStarted(); PreparedStatement ps = null; ResultSet rs = null; try { ps = getConnection().prepareStatement(sql); if (params != null) { for (int i=0;ivorher die zu verwendende ID ermitteln soll. * MySQL zum besitzt eine auto_increment-Funktion, mit der es nicht notwendig ist, die ID beim * Insert mit anzugeben. Falls die Datenbank das jedoch nicht korrekt kann (z.Bsp. McKoi), dann * kann die Funktion true liefern. In dem Fall wird vor dem Insert ein "select max(id)+1 from table" * ausgefuehrt und diese ID fuer das Insert verwendet. * Standard-Wert: TRUE * @return true, wenn bei Inserts vorher die ID ermittelt werden soll. * @throws RemoteException */ protected boolean getInsertWithID() throws RemoteException { return true; } } jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/EmbeddedDBServiceImpl.java000077500000000000000000000023411327610051000304450ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/EmbeddedDBServiceImpl.java,v $ * $Revision: 1.1 $ * $Date: 2004/11/03 18:42:42 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db; import java.rmi.RemoteException; /** * DB-Service, der gezielt auf die Embedded-DB vorbereitet ist. */ public class EmbeddedDBServiceImpl extends DBServiceImpl { /** * ct. * @param pathToDbConf Path to db.conf. * @param username username. * @param password password. * @throws RemoteException */ public EmbeddedDBServiceImpl(String pathToDbConf, String username, String password) throws RemoteException { super("com.mckoi.JDBCDriver",":jdbc:mckoi:local://" + pathToDbConf,username,password); } } /********************************************************************** * $Log: EmbeddedDBServiceImpl.java,v $ * Revision 1.1 2004/11/03 18:42:42 willuhn * *** empty log message *** * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/EmbeddedDatabase.java000077500000000000000000000310461327610051000275250ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/EmbeddedDatabase.java,v $ * $Revision: 1.27 $ * $Date: 2006/11/20 22:57:35 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.StringWriter; import java.rmi.RemoteException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.mckoi.database.TableDataConglomerate; import com.mckoi.database.TransactionSystem; import com.mckoi.database.control.DBController; import com.mckoi.database.control.DBSystem; import com.mckoi.database.control.DefaultDBConfig; import com.mckoi.util.UserTerminal; import de.willuhn.datasource.rmi.DBService; import de.willuhn.logging.Logger; import de.willuhn.sql.CheckSum; import de.willuhn.sql.ScriptExecutor; /** * Embedded Datenbank die man jederzeit gut gebrauchen kann. * Einfach eine Instanz mit User, Passwort und Pfad im Konstruktor * erzeugen, die Datenbank wird geladen oder (wenn sie noch nicht existiert) * automatisch im genannten Verzeichnis angelegt. */ public class EmbeddedDatabase { private File path = null; private DefaultDBConfig config = null; private DBController control = null; private DBService db = null; private String username = null; private String password = null; private static String defaultConfig = "database_path=.\n" + "log_path=./log\n" + "root_path=configuration\n" + "jdbc_server_port=9157\n" + "ignore_case_for_identifiers=disabled\n" + "data_cache_size=4194304\n" + "max_cache_entry_size=8192\n" + "maximum_worker_threads=4\n" + "debug_log_file=debug.log\n" + "transaction_error_on_dirty_select=disabled\n" + "debug_level=30\n"; /** * Erzeugt eine neue Instanz der Datenbank. * Existiert sie noch nicht, wird sie automatisch angelegt. * @param path Verzeichnis, in dem sich die Datenbank befindet bzw angelegt werden soll. * @param username Username. * @param password Passwort. * @throws Exception */ public EmbeddedDatabase(String path, String username, String password) throws Exception { if (username == null || username.length() == 0) { throw new Exception("please enter a username"); } if (password == null || password.length() == 0) { throw new Exception("please enter a password"); } if (path == null || path.length() == 0) { throw new IOException("please enter a path"); } this.path = new File(path); this.username = username; this.password = password; if (!this.path.exists()) { Logger.info("creating directory " + this.path.getAbsolutePath()); this.path.mkdir(); } if (!this.path.canWrite()) throw new IOException("write permission failed in " + this.path.getAbsolutePath()); config = new DefaultDBConfig(this.path); config.setDatabasePath(this.path.getAbsolutePath()); config.setLogPath(this.path.getAbsolutePath() + "/log"); control = DBController.getDefault(); if (!exists()) create(); } /** * Prueft, ob die Datenbank existiert. * @return true, wenn sie existiert. */ public synchronized boolean exists() { return control.databaseExists(config); } /** * Erstellt eine neue Datenbank, falls sie noch nicht existiert. * @throws IOException Wenn ein Fehler bei der Erstellung auftrat. */ public synchronized void create() throws IOException { if (exists()) return; // Config-Datei kopieren Logger.info("creating database config file"); try { FileOutputStream fos = new FileOutputStream(this.path.getAbsolutePath() + "/db.conf"); fos.write(defaultConfig.getBytes()); fos.close(); } catch (IOException e) { Logger.error("failed",e); throw new IOException(e.getMessage()); } try { DBSystem session = null; Logger.info("creating database"); session = control.createDatabase(config,username,password); session.close(); } catch (Error error) { Logger.error("error while creating database",error); throw new IOException(error.getMessage()); } catch (Exception e) { Logger.error("error while creating database",e); throw new IOException(e.getMessage()); } } /** * Loescht die Datenbank gnadenlos. * Diese Funktion bitte MIT BEDACHT verwenden!. */ public synchronized void delete() { Logger.warn("deleting database in " + path.getAbsolutePath()); if (!exists()) { Logger.warn("database does not exist, skipping"); return; } DBSystem system = control.startDatabase(config); system.setDeleteOnClose(true); system.close(); Logger.warn("database deleted"); } /** * Fuehrt das uebergebene File mit SQL-Kommandos auf der Datenbank aus. * Die Funktion liefert kein DBIteratorImpl zurueck, weil sie typischerweise * fuer die Erstellung der Tabellen verwendet werden sollte. Wenn das * Plugin also bei der Installation seine SQL-Tabellen erstellen will, * kann es das am besten hier machen. * @param file das auszufuehrende SQL-Script. * @throws IOException Wenn beim Lesen des SQL-Scripts Fehler auftraten. * @throws SQLException Wenn beim Ausfuehren Fehler auftraten. */ public void executeSQLScript(File file) throws IOException, SQLException { if (file == null) throw new NullPointerException("sql file not given"); Logger.debug("executing " + file.getAbsolutePath()); if (!file.canRead() || !file.exists()) throw new IOException("SQL file does not exist or is not readable"); Connection conn = null; DBSystem session = null; FileReader reader = null; try { session = control.startDatabase(config); conn = session.getConnection(username,password); reader = new FileReader(file); Logger.info("executing sql commands from " + file.getAbsolutePath()); ScriptExecutor.execute(reader,conn); } finally { try { if (reader != null) reader.close(); } catch (Exception e3) { Logger.error("error while closing file " + file.getAbsolutePath(),e3); } try { if (conn != null) conn.close(); } catch (Exception e3) { Logger.error("error while closing connection",e3); } try { if (session != null) session.close(); } catch (Exception e4) { Logger.error("error while closing session",e4); } } } /** * Liefert den Verzeichnis-Pfad, in dem sich die Datenbank befindet. * @return Pfad zur Datenbank. */ public File getPath() { return this.path; } /** * Liefert einen DBService zu dieser Datenbank. * @return DBService. * @throws RemoteException */ public DBService getDBService() throws RemoteException { if (db != null) return db; db = new DBServiceImpl("com.mckoi.JDBCDriver",":jdbc:mckoi:local://" + path.getAbsolutePath() + "/db.conf?user=" + username + "&password=" + password); return db; } /** * Liefert eine MD5-Checksumme (BASE64-encoded) der Datenbank-Eigenschaften. * Diese kann gegen eine gespeicherte Version verglichen werden, um zu pruefen, * ob die Datenbank den erwarteten Eigenschaften entspricht. Das ist z.Bsp. * sinnvoll, wenn man pruefen will, ob das Datenbank-Modell zur Software-Version * passt.
* Szenario: Eine Anwendung moechte seine embedded Datenbank auf den aktuellen * Stand bringen, weiss jedoch nicht, welche SQL-Statements hierfuer noetig sind, * da das momentane Datenbank-Layout nicht bekannt ist.
* Loesung: Die Anwendung haelt fuer alle moeglichen Versionsstaende der Datenbank * je eine MD5-Summe bereit und vergleicht diese mit der aktuellen. Somit kann * sie herausfinden, welche SQL-Befehle noch noetig sind, um die Anwendung * auf den aktuellen Stand zu bringen.
* Eine weitere Einsatzmoeglichkeit ist das Detektieren von Datenbank-Manipulationen. * Sprich: Wurde die Datenbank von einem Dritten geaendert, laesst sich dies durch * Pruefen der Checksumme herausfinden. * @return MD5-Checksumme. * @throws Exception */ public String getMD5Sum() throws Exception { Connection conn = null; try { conn = getConnection(); return CheckSum.md5(conn,null,"APP"); } finally { try { if (conn != null) conn.close(); } catch (Exception e2) { Logger.error("error while closing connection",e2); } } } /** * Repariert die Datenbank. * @param terminal Terminal, welches zur Ausgabe und Interaktion verwendet werden soll. * UserTerminal ist ein Interface und muss vom Benutzer implementiert werden. */ public void repair(UserTerminal terminal) { TransactionSystem system = new TransactionSystem(); DefaultDBConfig config = new DefaultDBConfig(); config.setDatabasePath(path.getAbsolutePath()); config.setLogPath(""); config.setMinimumDebugLevel(50000); // We do not use the NIO API for repairs for safety. config.setValue("do_not_use_nio_api", "enabled"); system.setDebugOutput(new StringWriter()); system.init(config); final TableDataConglomerate conglomerate = new TableDataConglomerate(system, system.storeSystem()); // Check it. conglomerate.fix("DefaultDatabase", terminal); // Dispose the transaction system system.dispose(); } /** * Liefert eine Connection zu dieser Datenbank. * @return Connection. * @throws Exception */ public Connection getConnection() throws Exception { Class.forName("com.mckoi.JDBCDriver"); return DriverManager.getConnection(":jdbc:mckoi:local://" + path.getAbsolutePath() + "/db.conf?user=" + username + "&password=" + password); } } /********************************************************************** * $Log: EmbeddedDatabase.java,v $ * Revision 1.27 2006/11/20 22:57:35 willuhn * @N new parameter in default config: transaction_error_on_dirty_select=disabled * * Revision 1.26 2006/01/30 14:55:33 web0 * @N de.willuhn.sql * * Revision 1.25 2005/12/12 18:50:34 web0 * @B try/catch Handling * * Revision 1.24 2005/11/18 11:56:45 web0 * *** empty log message *** * * Revision 1.23 2005/08/25 22:37:29 web0 * *** empty log message *** * * Revision 1.22 2005/03/09 01:07:51 web0 * @D javadoc fixes * * Revision 1.21 2005/02/01 17:14:58 willuhn * *** empty log message *** * * Revision 1.20 2004/11/12 18:21:56 willuhn * *** empty log message *** * * Revision 1.19 2004/08/18 23:14:00 willuhn * @D Javadoc * * Revision 1.18 2004/07/23 15:51:07 willuhn * @C Rest des Refactorings * * Revision 1.17 2004/07/21 23:53:56 willuhn * @C massive Refactoring ;) * * Revision 1.16 2004/07/09 00:04:19 willuhn * @C Redesign * * Revision 1.15 2004/07/04 17:08:09 willuhn * *** empty log message *** * * Revision 1.14 2004/06/30 21:58:12 willuhn * @N md5 check for database * * Revision 1.13 2004/06/30 20:58:07 willuhn * @C some refactoring * * Revision 1.12 2004/04/22 23:48:04 willuhn * *** empty log message *** * * Revision 1.11 2004/04/13 23:13:09 willuhn * *** empty log message *** * * Revision 1.10 2004/03/18 01:24:17 willuhn * @C refactoring * * Revision 1.9 2004/03/06 18:24:34 willuhn * @D javadoc * * Revision 1.8 2004/02/09 13:04:34 willuhn * @C misc * * Revision 1.7 2004/01/29 00:46:01 willuhn * *** empty log message *** * * Revision 1.6 2004/01/29 00:13:11 willuhn * *** empty log message *** * * Revision 1.5 2004/01/27 23:54:32 willuhn * *** empty log message *** * * Revision 1.4 2004/01/25 18:39:49 willuhn * *** empty log message *** * * Revision 1.3 2004/01/23 00:25:52 willuhn * *** empty log message *** * * Revision 1.2 2004/01/10 14:52:19 willuhn * @C package removings * * Revision 1.1 2004/01/08 20:46:44 willuhn * @N database stuff separated from jameica * * Revision 1.5 2004/01/06 20:32:59 willuhn * *** empty log message *** * * Revision 1.4 2004/01/05 19:14:45 willuhn * *** empty log message *** * * Revision 1.3 2004/01/05 18:27:13 willuhn * *** empty log message *** * * Revision 1.2 2004/01/04 18:48:36 willuhn * @N config store support * * Revision 1.1 2004/01/03 18:08:05 willuhn * @N Exception logging * @C replaced bb.util xml parser with nanoxml * * Revision 1.2 2003/12/30 19:11:29 willuhn * @N new splashscreen * * Revision 1.1 2003/12/30 17:44:41 willuhn * @N automatic database create * **********************************************************************/ jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/MyDriver.java000077500000000000000000000062321327610051000261470ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/MyDriver.java,v $ * $Revision: 1.2 $ * $Date: 2005/03/09 01:07:51 $ * $Author: web0 $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Properties; import java.util.logging.Logger; /** * Hilfsklasse da java.sql.DriverManager nur Driver akzeptiert, * die vom Systemclassloader geladen worden. * Siehe: http://www.kfu.com/~nsayer/Java/dyn-jdbc.html * Sprich: Bringt zum Beispiel ein Jameica-Plugin eigene JDBC-Treiber * mit, wuerde java.sql.DriverManager die nicht haben wollen, weil * sie nicht vom System-Classloader kommen. Daher zimmern wir * uns einen Wrapper um den eigentlichen Driver. Hauptsache MyDriver * ist vom SystemClassloader geladen. Wo der tatsaechliche Treiber * herkommt, interessiert den DriverManager nicht ;). */ public class MyDriver implements Driver { private Driver driver = null; /** * ct. * @param driverClass * @param loader * @throws Exception */ public MyDriver(String driverClass, ClassLoader loader) throws Exception { driver = (Driver) loader.loadClass(driverClass).newInstance(); } /** * @see java.sql.Driver#getMajorVersion() */ public int getMajorVersion() { return driver.getMajorVersion(); } /** * @see java.sql.Driver#getMinorVersion() */ public int getMinorVersion() { return driver.getMinorVersion(); } /** * @see java.sql.Driver#jdbcCompliant() */ public boolean jdbcCompliant() { return driver.jdbcCompliant(); } /** * @see java.sql.Driver#acceptsURL(java.lang.String) */ public boolean acceptsURL(String url) throws SQLException { return driver.acceptsURL(url); } /** * @see java.sql.Driver#connect(java.lang.String, java.util.Properties) */ public Connection connect(String url, Properties info) throws SQLException { return driver.connect(url,info); } /** * @see java.sql.Driver#getPropertyInfo(java.lang.String, java.util.Properties) */ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return driver.getPropertyInfo(url,info); } /** * @since Java 7 * @see java.sql.Driver#getParentLogger() */ @SuppressWarnings("javadoc") public Logger getParentLogger() throws SQLFeatureNotSupportedException { // FeatureNotSupportedException werfen, damits auch in Java 6 noch compiliert. throw new SQLFeatureNotSupportedException("getParentLogger not supported"); } } /********************************************************************** * $Log: MyDriver.java,v $ * Revision 1.2 2005/03/09 01:07:51 web0 * @D javadoc fixes * * Revision 1.1 2004/12/07 01:27:58 willuhn * @N Dummy Driver * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/ObjectMetaCache.java000077500000000000000000000076461327610051000273610ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/ObjectMetaCache.java,v $ * $Revision: 1.6 $ * $Date: 2007/10/05 15:16:27 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db; import java.util.HashMap; import de.willuhn.logging.Logger; import de.willuhn.util.Session; /** * Diese Klasse ist (wie der Name schon sagt ;) ein Cache. * Und zwar fuer die Meta-Daten der Business-Objekte. Und zwar: * AbstractDBObject ist ja die Basisklasse aller Business-Objekte. * Und diese ermittelt die Eigenschaften der Objekte "on the fly" * aus den Meta-Daten der SQL-Tabelle. Dies ist ein zeitraubender * Prozess, der nicht fuer jede Instanziierung eines Objektes neu * gemacht werden sollte. Schliesslich kennen wir den Aufbau der * SQL-Tabelle ja schon, wenn wir ein Objekt dieses Typs bereits * geladen haben. Nunja, dieser Cache macht nichts anderes, als * in einer Liste die Metadaten der verwendeten Objekte zu sammeln, * damit sie bei der naechsten Erzeugung eines Objektes "recycled" * werden koennen. * @author willuhn */ public class ObjectMetaCache { private static Session metaCache = new Session(1000l * 60 * 60 * 2); // 2 Stunden Timeout private static long found = 0; private static long all = 0; /** * Liefert die Meta-Daten einer Klasse oder null. * @param service Klasse des Service. * @param objectType Klasse des Objekt-Typs. * @return Die Metadaten. */ public static HashMap getMetaData(Class service, Class objectType) { if (all == 10000l) { // Nach 100.000 Aufrufen geben wir die Stats aus. Logger.info("[object meta cache stats] requests: " + all + ", matches: " + found + " [" + getStats() + "%]"); found = 0; all = 0; } ++all; HashMap m = (HashMap) metaCache.get(service.getName() + "." + objectType.getName()); if (m != null) ++found; return m; } /** * Fuegt dem Cache die Meta-Daten einer DBObject-Klasse hinzu. * @param service Klasse des Service. * @param objectType Klasse des Objekt-Typs. * @param fields Hashmap mit den Metadaten (key=Feldnamen,value=Datentyp). */ public static void setMetaData(Class service, Class objectType, HashMap fields) { metaCache.put(service.getName() + "." + objectType.getName(),fields); } /** * Liefert den prozentualen Anteil zwischen Cache-Abfragen insgesamt und erfolgreich * beantworteten Abfragen. * @return Anteil der erfolgreich beantworteten Anfragen in Prozent. */ public static int getStats() { if (found == 0 || all == 0) return 0; int stats = (int) ((100 * found) / all); return stats; } } /********************************************************************* * $Log: ObjectMetaCache.java,v $ * Revision 1.6 2007/10/05 15:16:27 willuhn * @N Objekt-Metadaten pro Service speichern * * Revision 1.5 2007/01/12 14:31:39 willuhn * @N made metadata methods public * * Revision 1.4 2005/04/28 21:28:48 web0 * *** empty log message *** * * Revision 1.3 2005/04/28 15:44:09 web0 * *** empty log message *** * * Revision 1.2 2005/03/09 01:07:51 web0 * @D javadoc fixes * * Revision 1.1 2004/01/10 14:52:19 willuhn * @C package removings * * Revision 1.1 2004/01/08 20:46:43 willuhn * @N database stuff separated from jameica * * Revision 1.5 2003/12/18 21:47:12 willuhn * @N AbstractDBObjectNode * * Revision 1.4 2003/12/15 19:08:01 willuhn * *** empty log message *** * * Revision 1.3 2003/12/13 20:05:21 willuhn * *** empty log message *** * * Revision 1.2 2003/12/12 21:11:28 willuhn * @N ObjectMetaCache * * Revision 1.1 2003/12/12 01:28:05 willuhn * *** empty log message *** * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/000077500000000000000000000000001327610051000247015ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/Type.java000066400000000000000000000026241327610051000264710ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/Type.java,v $ * $Revision: 1.1 $ * $Date: 2008/07/11 09:30:17 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * Basis-Interface fuer alle Typen. */ public interface Type { /** * Liest den Wert zum angegebenen Feld aus dem Resultset. * @param rs Resultset * @param name Name des Feldes. * @return gelesener Wert. * @throws SQLException */ public Object get(ResultSet rs, String name) throws SQLException; /** * Speichert den uebergebenen Wert im Statement. * @param stmt das Statement. * @param index Index. * @param value der Wert. * @throws SQLException */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException; } /********************************************************************* * $Log: Type.java,v $ * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeByteArray.java000066400000000000000000000060301327610051000303070ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeByteArray.java,v $ * $Revision: 1.4 $ * $Date: 2009/07/14 12:00:47 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import de.willuhn.logging.Logger; /** * Typ Byte-Array. */ public class TypeByteArray extends TypeGeneric { /** * @see de.willuhn.datasource.db.types.TypeGeneric#get(java.sql.ResultSet, java.lang.String) */ public Object get(ResultSet rs, String name) throws SQLException { Object value = super.get(rs, name); if (value == null) return null; InputStream is = null; if (value instanceof InputStream) { is = (InputStream) value; } else if (value instanceof Blob) { Blob b = (Blob) value; is = b.getBinaryStream(); } else if (value instanceof byte[]) return value; if (is == null) { Logger.warn("don't know how to handle type " + value.getClass().getName() + " - returning unchanged"); return value; } // Daten aus dem InputStream kopieren try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = is.read(buf)) != -1) bos.write(buf,0,len); return bos.toByteArray(); } catch (IOException ioe) { throw new SQLException("unable to read blob: " + ioe.getMessage()); } finally { try { is.close(); } catch (IOException e) { throw new SQLException("unable to close inputstream: " + e.getMessage()); } } } /** * @see de.willuhn.datasource.db.types.TypeGeneric#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else stmt.setBytes(index,(byte[])value); } } /********************************************************************* * $Log: TypeByteArray.java,v $ * Revision 1.4 2009/07/14 12:00:47 willuhn * @C byte[] unveraendert zurueckliefern * * Revision 1.3 2009/06/28 22:04:09 willuhn * @C java.sql.Blob in Byte-Array kopieren (Heiners Patch) * * Revision 1.2 2008/07/11 16:15:54 willuhn * @B rs.getObject() liefert ggf. (abhaengig von der Datenbank) einen InputStream statt byte[] * * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeDate.java000066400000000000000000000023751327610051000272720ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeDate.java,v $ * $Revision: 1.1 $ * $Date: 2008/07/11 09:30:16 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * Typ Date */ public class TypeDate extends TypeGeneric { /** * @see de.willuhn.datasource.db.types.TypeGeneric#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else stmt.setDate(index,new java.sql.Date(((java.util.Date) value).getTime())); } } /********************************************************************* * $Log: TypeDate.java,v $ * Revision 1.1 2008/07/11 09:30:16 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeDouble.java000066400000000000000000000030351327610051000276210ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeDouble.java,v $ * $Revision: 1.3 $ * $Date: 2008/09/02 18:00:12 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * Typ Double. */ public class TypeDouble extends TypeGeneric { /** * @see de.willuhn.datasource.db.types.TypeGeneric#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else { if (value instanceof Double) stmt.setDouble(index,((Number) value).doubleValue()); else if (value instanceof BigDecimal) stmt.setBigDecimal(index,(BigDecimal) value); else stmt.setObject(index,value); } } } /********************************************************************* * $Log: TypeDouble.java,v $ * Revision 1.3 2008/09/02 18:00:12 willuhn * @N BigDecimal akzeptieren * * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeGeneric.java000066400000000000000000000026671327610051000277750ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeGeneric.java,v $ * $Revision: 1.1 $ * $Date: 2008/07/11 09:30:17 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; /** * Generisch. */ public class TypeGeneric implements Type { /** * @see de.willuhn.datasource.db.types.Type#get(java.sql.ResultSet, java.lang.String) */ public Object get(ResultSet rs, String name) throws SQLException { return rs.getObject(name); } /** * @see de.willuhn.datasource.db.types.Type#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else stmt.setObject(index,value); } } /********************************************************************* * $Log: TypeGeneric.java,v $ * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeInteger.java000066400000000000000000000030531327610051000300040ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeInteger.java,v $ * $Revision: 1.2 $ * $Date: 2009/01/29 22:31:29 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * Typ Integer. */ public class TypeInteger extends TypeGeneric { /** * @see de.willuhn.datasource.db.types.TypeGeneric#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else { if (value instanceof Integer) stmt.setInt(index,((Integer) value).intValue()); else if (value instanceof Long) stmt.setLong(index,((Long) value).longValue()); else stmt.setObject(index,value); } } } /********************************************************************* * $Log: TypeInteger.java,v $ * Revision 1.2 2009/01/29 22:31:29 willuhn * @B http://www.onlinebanking-forum.de/phpBB2/viewtopic.php?p=54958#54958 * * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeLongString.java000066400000000000000000000051501327610051000304750ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeLongString.java,v $ * $Revision: 1.1 $ * $Date: 2008/07/15 11:02:31 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.io.IOException; import java.io.Reader; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; /** * Typ fuer "TEXT" und "LONGVARCHAR". */ public class TypeLongString extends TypeGeneric { /** * @see de.willuhn.datasource.db.types.TypeGeneric#get(java.sql.ResultSet, java.lang.String) */ public Object get(ResultSet rs, String name) throws SQLException { Object value = rs.getObject(name); if (value != null && (value instanceof Reader)) { // Wenn es ein Stream ist, kopieren wir die Daten in ein // Byte-Array Reader r = (Reader) value; try { StringBuffer sb = new StringBuffer(); char[] buf = new char[1024]; int len = 0; while ((len = r.read(buf)) != -1) sb.append(buf,0,len); return sb.toString(); } catch (IOException ioe) { throw new SQLException("unable to read text/longvarchar: " + ioe.getMessage()); } finally { try { r.close(); } catch (IOException e) { throw new SQLException("unable to close inputstream: " + e.getMessage()); } } } return value; } /** * @see de.willuhn.datasource.db.types.TypeGeneric#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else stmt.setString(index,value.toString()); } } /********************************************************************* * $Log: TypeLongString.java,v $ * Revision 1.1 2008/07/15 11:02:31 willuhn * @N Neuer Typ "TypeLongString", der aus den Feldern "TEXT", "LONGTEXT" und "LONGVARCHAR" bei Bedarf aus einem Reader liest (ist abhaengig vom JDBC-Treiber) * * Revision 1.2 2008/07/14 12:11:53 willuhn * *** empty log message *** * * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeRegistry.java000066400000000000000000000062171327610051000302240ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeRegistry.java,v $ * $Revision: 1.4 $ * $Date: 2011/08/04 08:35:51 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.util.HashMap; import java.util.Map; import de.willuhn.logging.Logger; /** * Registry, in der die unterstuetzten Feld-Typen gehalten werden. */ public class TypeRegistry { private static Map types = new HashMap(); /** * Generischer Typ, der Verwendung findet, wenn kein passender Typ gefunden wurde. */ public final static Type TYPE_DEFAULT = new TypeGeneric(); static { types.put(null, TYPE_DEFAULT); types.put("varchar", new TypeString()); types.put("longvarchar", new TypeLongString()); types.put("text", new TypeLongString()); types.put("longtext", new TypeLongString()); types.put("date", new TypeDate()); types.put("datetime", new TypeTimestamp()); types.put("timestamp", new TypeTimestamp()); types.put("int", new TypeInteger()); types.put("double", new TypeDouble()); types.put("decimal", new TypeDouble()); types.put("blob", new TypeByteArray()); types.put("longblob", new TypeByteArray()); // Daemliches PostgreSQL - muessen die denn ALLES anders machen? :( types.put("bytea", new TypeByteArray()); types.put("timestamptz", new TypeTimestamp()); } /** * Liefert die Typ-Implementierung fuer den angegebenen Typ. * Die Funktion beruecksichtigt KEINE Gross-Kleinschreibung. * @param name Name des Feld-Typs. * @return Implementierung des Typs. Die Funktion liefert nie * null sondern hoechstens TYPE_DEFAULT. */ public static Type getType(String name) { if (name == null) return TYPE_DEFAULT; Type t = (Type) types.get(name.toLowerCase()); return t == null ? TYPE_DEFAULT : t; } /** * Registriert einen benutzerdefinierten SQL-Typ. * @param name Name des Feld-Typs. * @param type Implementierung. */ public static void register(String name,Type type) { if (name == null || type == null) { Logger.error("name or type cannot be null"); return; } types.put(name.toLowerCase(),type); } } /********************************************************************* * $Log: TypeRegistry.java,v $ * Revision 1.4 2011/08/04 08:35:51 willuhn * @B daemliches PostgreSQL * * Revision 1.3 2008/07/15 11:02:31 willuhn * @N Neuer Typ "TypeLongString", der aus den Feldern "TEXT", "LONGTEXT" und "LONGVARCHAR" bei Bedarf aus einem Reader liest (ist abhaengig vom JDBC-Treiber) * * Revision 1.2 2008/07/14 08:55:28 willuhn * @N "longvarchar" added * * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeString.java000066400000000000000000000030431327610051000276540ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeString.java,v $ * $Revision: 1.2 $ * $Date: 2008/07/14 12:11:53 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; /** * Typ String. */ public class TypeString extends TypeGeneric { /** * @see de.willuhn.datasource.db.types.TypeGeneric#get(java.sql.ResultSet, java.lang.String) */ public Object get(ResultSet rs, String name) throws SQLException { return rs.getString(name); } /** * @see de.willuhn.datasource.db.types.TypeGeneric#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else stmt.setString(index,value.toString()); } } /********************************************************************* * $Log: TypeString.java,v $ * Revision 1.2 2008/07/14 12:11:53 willuhn * *** empty log message *** * * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/db/types/TypeTimestamp.java000066400000000000000000000024511327610051000303530ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/db/types/TypeTimestamp.java,v $ * $Revision: 1.1 $ * $Date: 2008/07/11 09:30:17 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.db.types; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import java.util.Date; /** * Typ Timestamp. */ public class TypeTimestamp extends TypeGeneric { /** * @see de.willuhn.datasource.db.types.TypeGeneric#set(java.sql.PreparedStatement, int, java.lang.Object) */ public void set(PreparedStatement stmt, int index, Object value) throws SQLException { if (value == null) stmt.setNull(index,Types.NULL); else stmt.setTimestamp(index,new java.sql.Timestamp(((Date) value).getTime())); } } /********************************************************************* * $Log: TypeTimestamp.java,v $ * Revision 1.1 2008/07/11 09:30:17 willuhn * @N Support fuer Byte-Arrays * @N SQL-Typen sind jetzt erweiterbar * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/pseudo/000077500000000000000000000000001327610051000244475ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/pseudo/PseudoIterator.java000077500000000000000000000100051327610051000302620ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/pseudo/PseudoIterator.java,v $ * $Revision: 1.8 $ * $Date: 2007/04/25 13:30:05 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.pseudo; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.willuhn.datasource.GenericIterator; import de.willuhn.datasource.GenericObject; /** * Ein Pseudo-Iterator, der zwar das GenericIterator-Interface * implementiert, jedoch kein Datenbank-Backend benutzt sondern * Listen/Maps aus java.util. */ public class PseudoIterator extends UnicastRemoteObject implements GenericIterator { private static final long serialVersionUID = 1L; private List list = null; private int index = 0; /** * Der Konstruktor ist private, damit Instanzen nur * ueber die statischen Methoden fromFoo erzeugt werden. * @throws RemoteException */ private PseudoIterator() throws RemoteException { } /** * Erzeugt einen GenericIterator aus einem Array von GenericObjects. * @param objects das Array, aus dem der Iterator aufgebaut werden soll. * @return der generierte Iterator. * @throws RemoteException */ public static GenericIterator fromArray(GenericObject[] objects) throws RemoteException { PseudoIterator i = new PseudoIterator(); i.list = Arrays.asList(objects); return i; } /** * Erzeugt eine Liste aus einem GenericIterator. * @param iterator zu konvertierender Iterator. * @return Liste. * @throws RemoteException */ public static List asList(GenericIterator iterator) throws RemoteException { ArrayList list = new ArrayList(); while (iterator.hasNext()) list.add(iterator.next()); iterator.begin(); return list; } /** * @see de.willuhn.datasource.GenericIterator#hasNext() */ public boolean hasNext() throws RemoteException { return (list.size() > index && list.size() > 0); } /** * @see de.willuhn.datasource.GenericIterator#next() */ public GenericObject next() throws RemoteException { return (GenericObject) list.get(index++); } /** * @see de.willuhn.datasource.GenericIterator#previous() */ public GenericObject previous() throws RemoteException { return (GenericObject) list.get(index--); } /** * @see de.willuhn.datasource.GenericIterator#begin() */ public void begin() throws RemoteException { index = 0; } /** * @see de.willuhn.datasource.GenericIterator#size() */ public int size() throws RemoteException { return list.size(); } /** * @see de.willuhn.datasource.GenericIterator#contains(de.willuhn.datasource.GenericObject) */ public GenericObject contains(GenericObject o) throws RemoteException { if (o == null) return null; GenericObject object = null; for (int i=0;istore() aufgerufen werden. * @param object das Objekt, welches als Quelle verwendet werden soll. * @throws RemoteException im Fehlerfall. */ public void overwrite(DBObject object) throws RemoteException; } /********************************************************************* * $Log: Changeable.java,v $ * Revision 1.3 2004/10/25 17:58:37 willuhn * @N Delete/Store-Listeners * * Revision 1.2 2004/08/31 18:13:59 willuhn * *** empty log message *** * * Revision 1.1 2004/08/18 23:14:00 willuhn * @D Javadoc * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/DBIterator.java000077500000000000000000000041331327610051000266050ustar00rootroot00000000000000/********************************************************************** * * Copyright (c) by Olaf Willuhn * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.RemoteException; import de.willuhn.datasource.GenericIterator; /** * Iterator fuer Datenbanktabellen auf Objekt-Ebene. * @param der konkrete Typ. */ public interface DBIterator extends GenericIterator { /** * Fuegt dem Iterator einen zusaetzlichen Filter hinzu, der * sich auf die Anzahl der Treffer auswirkt. Bsp: * addFilter("kontonummer='2020'"); * Bewirkt, dass eine zusaetzliche Where-Klausel "where kontonummer='2020'" * hinzugefuegt wird. * @param filter ein zusaetzlicher SQL-Filter. * Z.Bsp.: "konto_id = 20". * @throws RemoteException */ public void addFilter(String filter) throws RemoteException; /** * Wie {@link DBIterator#addFilter(String)} - allerdings mit dem * Unterschied, dass ueber das Objekt-Array zusaetzliche Parameter * angegeben werden koennen, mit denen dann ein PreparedStatement * gefuellt wird. * Mann kann also entweder schreiben: * addFilter("kontonummer='200'"); * oder * addFilter("kontonummer=?","200"); * Die Verwendung des PreparedStatements schuetzt vor SQL-Injections. * @see DBIterator#addFilter(String) * @param filter ein zusaetzlicher Filter. * @param params * @throws RemoteException */ public void addFilter(String filter, Object... params) throws RemoteException; /** * Fuegt eine Tabelle via Join hinzu. * @param table zu joinende Tabelle. * @throws RemoteException */ public void join(String table) throws RemoteException; /** * Fuegt dem Iterator eine Sortierung hinzu. * @param order * @throws RemoteException */ public void setOrder(String order) throws RemoteException; /** * Fuegt ein "limit {i}" dem Statement hinzu. * @param i Hoehe des Limit. * @throws RemoteException */ public void setLimit(int i) throws RemoteException; } jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/DBObject.java000077500000000000000000000146611327610051000262310ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/rmi/DBObject.java,v $ * $Revision: 1.12 $ * $Date: 2006/10/18 17:07:20 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.RemoteException; import de.willuhn.datasource.GenericObject; /** * Erweiterung des GenericObjects um Datenbank-Funktionalitaet. */ public interface DBObject extends GenericObject, Transactionable, Changeable { /** * Laedt die Eigenschaften des Datensatzes mit der angegebenen * ID aus der Datenbank. * @param id ID des zu ladenden Objektes. * @throws RemoteException im Fehlerfall. */ public void load(String id) throws RemoteException; /** * Liefert den Wert des angegebenen Attributes. * Aber die Funktion ist richtig schlau ;) * Sie checkt naemlich den Typ des Feldes in der Datenbank und * liefert nicht nur einen String sondern den korrespondierenden * Java-Typ. Insofern die Businessklasse die Funktion * getForeignObject(String field) sinnvoll uberschrieben hat, liefert * die Funktion bei Fremdschluesseln sogar gleich das entsprechende * Objekt aus der Verknuepfungstabelle. * @param name Name des Feldes. * @return Wert des Feldes. * @throws RemoteException im Fehlerfall. * @see de.willuhn.datasource.GenericObject#getAttribute(java.lang.String) */ public Object getAttribute(String name) throws RemoteException; /** * Liefert den Attributtyp des uebergebenen Feldes. * Siehe DBObject.ATTRIBUTETYPE_*. * @param attributeName Name des Attributes. * @return Konstante fuer den Attributtyp. Siehe DBObject.ATTRIBUTETYPE_*. * @throws RemoteException im Fehlerfall. */ public String getAttributeType(String attributeName) throws RemoteException; /** * @see de.willuhn.datasource.GenericObject#getPrimaryAttribute() */ public String getPrimaryAttribute() throws RemoteException; /** * Liefert eine Liste aller Objekte des aktuellen Types. * @return Liste mit allen Objekten dieser Tabelle. * @throws RemoteException */ public DBIterator getList() throws RemoteException; /** * Vergleicht dieses Objekt mit dem uebergebenen. * Hinweis: Es wird nicht der Inhalt verglichen sondern nur die ID und der Typ. * @param other das zu vergleichende Objekt. * @return true, wenn sie vom gleichen Typ sind und die selbe ID haben. * @throws RemoteException * @see de.willuhn.datasource.GenericObject#equals(de.willuhn.datasource.GenericObject) */ public boolean equals(GenericObject other) throws RemoteException; /** * Fuegt dem Objekt einen Listener hinzu, der ausgeloest wird, wenn * das Objekt gerade geloescht wurde. * Hinweis: Das Event wird unmittelbar nach dem Loeschen * ausgeloest, jedoch noch bevor die ID auf null gesetzt wurde. * @param l der Listener. * @throws RemoteException */ public void addDeleteListener(Listener l) throws RemoteException; /** * Fuegt dem Objekt einen Listener hinzu, der ausgeloest wird, wenn * das Objekt gespeichert wurde. * Hinweis: Das Event wird nach dem Speichern ausgeloest. * @param l der Listener. * @throws RemoteException */ public void addStoreListener(Listener l) throws RemoteException; /** * Entfernt den Listener wieder. * @param l der Listener. * @throws RemoteException */ public void removeDeleteListener(Listener l) throws RemoteException; /** * Entfernt den Listener wieder. * @param l der Listener. * @throws RemoteException */ public void removeStoreListener(Listener l) throws RemoteException; } /********************************************************************* * $Log: DBObject.java,v $ * Revision 1.12 2006/10/18 17:07:20 willuhn * @N DBIterator registriert einen DeleteListener, um sich selbst zu bereinigen, wenn Objekte aus ihr geloescht werden * @N deleteListener in AbstractDBObject * * Revision 1.11 2006/01/04 17:04:56 web0 * @C DeleteListener wird nun unmittelbar nach dem Loeschen jedoch vor this.id=null aufgerufen * * Revision 1.10 2004/10/25 17:58:37 willuhn * @N Delete/Store-Listeners * * Revision 1.9 2004/08/31 18:13:59 willuhn * *** empty log message *** * * Revision 1.8 2004/08/18 23:21:38 willuhn * *** empty log message *** * * Revision 1.7 2004/08/18 23:14:00 willuhn * @D Javadoc * * Revision 1.6 2004/07/21 23:53:56 willuhn * @C massive Refactoring ;) * * Revision 1.5 2004/07/13 22:19:30 willuhn * @C paar Funktionsnamen umbenannt * * Revision 1.4 2004/06/17 00:05:50 willuhn * @N GenericObject, GenericIterator * * Revision 1.3 2004/04/05 23:28:30 willuhn * *** empty log message *** * * Revision 1.2 2004/03/06 18:24:34 willuhn * @D javadoc * * Revision 1.1 2004/01/10 14:52:19 willuhn * @C package removings * * Revision 1.1 2004/01/08 20:46:44 willuhn * @N database stuff separated from jameica * * Revision 1.15 2003/12/29 22:07:40 willuhn * *** empty log message *** * * Revision 1.14 2003/12/29 16:29:47 willuhn * @N javadoc * * Revision 1.13 2003/12/28 22:58:27 willuhn * @N synchronize mode * * Revision 1.12 2003/12/27 21:23:33 willuhn * @N object serialization * * Revision 1.11 2003/12/26 21:43:30 willuhn * @N customers changable * * Revision 1.10 2003/12/19 01:43:27 willuhn * @N added Tree * * Revision 1.9 2003/12/15 19:08:01 willuhn * *** empty log message *** * * Revision 1.8 2003/11/27 00:22:18 willuhn * @B paar Bugfixes aus Kombination RMI + Reflection * @N insertCheck(), deleteCheck(), updateCheck() * @R AbstractDBObject#toString() da in RemoteObject ueberschrieben (RMI-Konflikt) * * Revision 1.7 2003/11/24 23:01:58 willuhn * @N added settings * * Revision 1.6 2003/11/24 16:25:53 willuhn * @N AbstractDBObject is now able to resolve foreign keys * * Revision 1.5 2003/11/24 14:21:53 willuhn * *** empty log message *** * * Revision 1.4 2003/11/22 20:43:05 willuhn * *** empty log message *** * * Revision 1.3 2003/11/21 02:10:21 willuhn * @N prepared Statements in AbstractDBObject * @N a lot of new SWT parts * * Revision 1.2 2003/11/20 03:48:42 willuhn * @N first dialogues * * Revision 1.1 2003/11/05 22:46:19 willuhn * *** empty log message *** **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/DBObjectNode.java000077500000000000000000000040471327610051000270340ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/rmi/DBObjectNode.java,v $ * $Revision: 1.4 $ * $Date: 2009/02/23 22:13:49 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.RemoteException; import de.willuhn.datasource.GenericIterator; import de.willuhn.datasource.GenericObjectNode; /** * Diese Klasse ist die ideale Basis-Klasse, wenn es gilt, Baum-Strukturen abzubilden. * In einer Datenbank wuerde das wie folgt gehen: Man nehme eine SQL-Tabelle und erweitere * sie um eine Spalte fuer das Eltern-Objekt. Diese heisst z.Bsp. "parent_id". * Dieser Fremd-Schluessel zeigt auf die selbe Tabelle und dort auf das * uebergeordnete Objekt. Ein solches Objekt laesst sich dann prima mit * der GUI-Komponente "Tree" darstellen. * Hinweis: Objekte, die sich bereits auf der obersten Ebene des Baumes * befinden, muessen den Wert "0" im Feld fuer das Eltern-Objekt besitzen. * @author willuhn */ public interface DBObjectNode extends DBObject, GenericObjectNode { /** * Liefert einen Iterator mit allen Root-Objekten. * Das sind all die, welche sich auf oberster Ebene befinden. * @return Iterator mit den Root-Objekten. * @throws RemoteException */ public GenericIterator getTopLevelList() throws RemoteException; /** * Speichert das Eltern-Element. * @param parent Eltern-Element. * @throws RemoteException */ public void setParent(DBObjectNode parent) throws RemoteException; } /********************************************************************* * $Log: DBObjectNode.java,v $ * Revision 1.4 2009/02/23 22:13:49 willuhn * @N setParent(DBObjectNode) in DBObjectNode * * Revision 1.3 2004/08/11 23:36:34 willuhn * @N Node Objekte in GenericObjectNode und DBObjectNode aufgeteilt * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/DBService.java000077500000000000000000000032471327610051000264210ustar00rootroot00000000000000/********************************************************************** * * Copyright (c) by Olaf Willuhn * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.RemoteException; import de.willuhn.datasource.Service; /** * Basisklasse fuer alle DBServices. */ public interface DBService extends Service { /** * Liefert eine Liste aller in der Datenbank vorhandenen Objekte des angegebenen Typs, * @param clazz Name der Klasse von der eine Liste geholt werden soll. * @return Eine Liste mit den gefundenen Objekten. * @throws RemoteException */ public DBIterator createList(Class clazz) throws RemoteException; /** * Erzeugt ein neues Objekt des angegebenen Typs. * @param clazz Name der Klasse des zu erzeugenden Objektes. * @param identifier der eindeutige Identifier des Objektes. * Kann null sein, wenn ein neues Objekt erzeugt werden soll. * Andernfalls wird das mit dem genannten Identifier geladen. * @return Das erzeugte Objekt * @throws RemoteException */ public T createObject(Class clazz, String identifier) throws RemoteException; /** * Fuehrt ein SQL-Statement aus und uebergibt das Resultset an den Extractor. * @param sql das Statement. * @param params die Parameter zur Erzeugung des PreparedStatements. * @param extractor der Extractor. * @return die vom ResultSetExtractor zurueckgelieferten Daten. * @throws RemoteException */ public Object execute(String sql, Object[] params, ResultSetExtractor extractor) throws RemoteException; } jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/Event.java000077500000000000000000000020201327610051000256600ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/rmi/Event.java,v $ * $Revision: 1.1 $ * $Date: 2004/10/25 17:58:37 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.Remote; import java.rmi.RemoteException; /** * Ein Event, dass bei verschiedenen Aktionen ausgeloest werden kann. */ public interface Event extends Remote { /** * Das Objekt, fuer das dieses Event ausgeloest wurde. * @return das Objekt. * @throws RemoteException */ public DBObject getObject() throws RemoteException; } /********************************************************************** * $Log: Event.java,v $ * Revision 1.1 2004/10/25 17:58:37 willuhn * @N Delete/Store-Listeners * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/Listener.java000077500000000000000000000020501327610051000263670ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/rmi/Listener.java,v $ * $Revision: 1.1 $ * $Date: 2004/10/25 17:58:37 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.Remote; import java.rmi.RemoteException; /** * Ein Listener, der ueber Aenderungen an DBObjects benachrichtigt wird. */ public interface Listener extends Remote { /** * Wird bei Aenderungen des DBObjects aufgerufen. * @param e das ausgeloeste Event. * @throws RemoteException */ public void handleEvent(Event e) throws RemoteException; } /********************************************************************** * $Log: Listener.java,v $ * Revision 1.1 2004/10/25 17:58:37 willuhn * @N Delete/Store-Listeners * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/ObjectNotFoundException.java000077500000000000000000000026311327610051000313510ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/rmi/ObjectNotFoundException.java,v $ * $Revision: 1.2 $ * $Date: 2007/04/02 23:00:42 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.RemoteException; /** * Exception, die geworfen wird, wenn ein Objekt nicht in der Datenbank gefunden wurde. */ public class ObjectNotFoundException extends RemoteException { private static final long serialVersionUID = 1L; /** * ct. */ public ObjectNotFoundException() { super(); } /** * ct. * @param s message. */ public ObjectNotFoundException(String s) { super(s); } /** * ct. * @param s message * @param ex cause. */ public ObjectNotFoundException(String s, Throwable ex) { super(s, ex); } } /********************************************************************** * $Log: ObjectNotFoundException.java,v $ * Revision 1.2 2007/04/02 23:00:42 willuhn * @B falscher Parameter in BeanUtil#get * @N PseudoIterator#asList * * Revision 1.1 2004/08/26 23:19:33 willuhn * @N added ObjectNotFoundException * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/ResultSetExtractor.java000066400000000000000000000025261327610051000304350ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/rmi/ResultSetExtractor.java,v $ * $Revision: 1.1 $ * $Date: 2006/09/05 20:52:24 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.Remote; import java.rmi.RemoteException; import java.sql.ResultSet; import java.sql.SQLException; /** * Ein Interface, ueber das man sich die Daten aus einem Resultset holen kann. */ public interface ResultSetExtractor extends Remote { /** * Wird vom DBService aufgerufen. * @param rs das erzeugte Resultset. * @return das extrahierte Objekt. * @throws RemoteException * @throws SQLException */ public Object extract(ResultSet rs) throws RemoteException, SQLException; } /********************************************************************* * $Log: ResultSetExtractor.java,v $ * Revision 1.1 2006/09/05 20:52:24 willuhn * @N Added ResultsetExtractor (portiert aus Syntax) * * Revision 1.1 2006/05/30 23:22:55 willuhn * @C Redsign beim Laden der Buchungen. Jahresabschluss nun korrekt * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/rmi/Transactionable.java000077500000000000000000000035351327610051000277240ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/rmi/Transactionable.java,v $ * $Revision: 1.2 $ * $Date: 2004/08/31 18:13:59 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.datasource.rmi; import java.rmi.RemoteException; /** * Bildet Funktionen zur Unterstuetzung von Transaktionen ab. */ public interface Transactionable { /** * Damit kann man manuell eine Transaktion starten. * Normalerweise wir bei store() oder delete() sofort * bei Erfolg ein commit gemacht. Wenn man aber von * aussen das Transaktionsverhalten beeinflussen will, * kann man diese Methode aufrufen. Hat man dies * getan, werden store() und delete() erst dann in * der Datenbank ausgefuehrt, wenn man anschliessend * transactionCommit() aufruft. * @throws RemoteException im Fehlerfall. */ public void transactionBegin() throws RemoteException; /** * Beendet eine manuell gestartete Transaktion. * Wenn vorher kein transactionBegin() aufgerufen wurde, * wird dieser Aufruf ignoriert. * @throws RemoteException im Fehlerfall. */ public void transactionCommit() throws RemoteException; /** * Rollt die angefangene Transaktion manuell zurueck. * @throws RemoteException im Fehlerfall. */ public void transactionRollback() throws RemoteException; } /********************************************************************* * $Log: Transactionable.java,v $ * Revision 1.2 2004/08/31 18:13:59 willuhn * *** empty log message *** * * Revision 1.1 2004/08/18 23:14:00 willuhn * @D Javadoc * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/serialize/000077500000000000000000000000001327610051000251375ustar00rootroot00000000000000jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/serialize/AbstractXmlIO.java000066400000000000000000000176311327610051000304660ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/serialize/AbstractXmlIO.java,v $ * $Revision: 1.5 $ * $Date: 2011/06/29 19:56:45 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.serialize; import java.io.IOException; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import de.willuhn.logging.Logger; import de.willuhn.util.Base64; /** * Abstrakte Basis-Implementierung des XML-Formats. */ public abstract class AbstractXmlIO implements IO { protected final static String ENCODING = "UTF-8"; protected final static Map valueMap = new HashMap(); static { valueMap.put(null, new StringValue()); valueMap.put("java.lang.Double", new DoubleValue()); valueMap.put("java.math.BigDecimal", new BigDecimalValue()); valueMap.put("java.lang.Integer", new IntegerValue()); valueMap.put("java.lang.Long", new LongValue()); valueMap.put("java.lang.Boolean", new BooleanValue()); valueMap.put("java.util.Date", new DateValue()); valueMap.put("java.sql.Date", new SqlDateValue()); valueMap.put("java.sql.Timestamp", new TimestampValue()); valueMap.put("[B", new ByteArrayValue()); } protected static interface Value { /** * Erzeugt eine String-Repraesentation des Objektes. * @param o Objekt. * @return String-Repraesentation. * @throws IOException */ public String serialize(Object o) throws IOException; /** * Erzeugt ein Object aus dem String. * @param s der String. * @return das Objekt. * @throws IOException */ public Object unserialize(String s) throws IOException; } protected static abstract class AbstractValue implements Value { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#serialize(java.lang.Object) */ public String serialize(Object o) throws IOException { return o == null ? "" : o.toString(); } } /** * Implementierung fuer Strings. */ protected static class StringValue extends AbstractValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { return s == null ? "" : s; } } /** * Implementierung fuer Double. */ protected static class DoubleValue extends AbstractValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { return (s == null || s.length() == 0) ? null : new Double(s); } } /** * Implementierung fuer BigDecimal. */ protected static class BigDecimalValue extends AbstractValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { return (s == null || s.length() == 0) ? null : new BigDecimal(s); } } /** * Implementierung fuer Integer. */ protected static class IntegerValue extends AbstractValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { return (s == null || s.length() == 0) ? null : new Integer(s); } } /** * Implementierung fuer Long. */ protected static class LongValue extends AbstractValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { return (s == null || s.length() == 0) ? null : new Long(s); } } /** * Implementierung fuer Boolean. */ protected static class BooleanValue extends AbstractValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { return s != null && (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("1")); } } /** * Implementierung fuer java.util.Date. */ protected static class DateValue implements Value { private final static DateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { if (s == null || s.length() == 0) return null; try { return format.parse(s); } catch (ParseException e) { Logger.error("unable to parse date " + s); throw new IOException(e.getMessage()); } } /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#serialize(java.lang.Object) */ public String serialize(Object o) throws IOException { return o == null ? "" : format.format((Date)o); } } /** * Implementierung fuer java.sql.Date. */ protected static class SqlDateValue extends DateValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { Date date = (Date) super.unserialize(s); return date == null ? null : new java.sql.Date(date.getTime()); } } /** * Implementierung fuer java.sql.Timestamp. */ protected static class TimestampValue extends DateValue { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { Date date = (Date) super.unserialize(s); return date == null ? null : new java.sql.Timestamp(date.getTime()); } } /** * Implementierung fuer Byte-Arrays. */ protected static class ByteArrayValue implements Value { /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#serialize(java.lang.Object) */ public String serialize(Object o) throws IOException { if (o == null) return ""; if (!(o instanceof byte[])) throw new IOException("unable to serialize " + o); return Base64.encode((byte[])o); } /** * @see de.willuhn.datasource.serialize.AbstractXmlIO.Value#unserialize(java.lang.String) */ public Object unserialize(String s) throws IOException { if (s == null || s.length() == 0) return null; return Base64.decode(s); } } } /********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/serialize/AbstractXmlIO.java,v $ * $Revision: 1.5 $ * $Date: 2011/06/29 19:56:45 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ /********************************************************************* * $Log: AbstractXmlIO.java,v $ * Revision 1.5 2011/06/29 19:56:45 willuhn * @N Support fuer Boolean in XMLReader/XMLWriter * * Revision 1.4 2008/09/29 14:18:00 willuhn * @N Support for NULL-values * * Revision 1.3 2008/09/28 23:26:53 willuhn * @N Support fuer bytearray * * Revision 1.2 2008/09/02 17:59:10 willuhn * @N Support fuer BigDecimal im XML-Export * * Revision 1.1 2008/01/22 12:03:09 willuhn * @N Objekt-Serializer/-Deserializer fuer XML-Format * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/serialize/IO.java000066400000000000000000000016571327610051000263220ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/serialize/IO.java,v $ * $Revision: 1.1 $ * $Date: 2008/01/22 12:03:09 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.serialize; import java.io.IOException; /** * Basis-Interface aller Reader und Writer. */ public interface IO { /** * Schliesst den Serializer. * @throws IOException */ public void close() throws IOException; } /********************************************************************* * $Log: IO.java,v $ * Revision 1.1 2008/01/22 12:03:09 willuhn * @N Objekt-Serializer/-Deserializer fuer XML-Format * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/serialize/ObjectFactory.java000066400000000000000000000023541327610051000305440ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/serialize/ObjectFactory.java,v $ * $Revision: 1.1 $ * $Date: 2008/01/22 12:03:09 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.serialize; import java.util.Map; import de.willuhn.datasource.GenericObject; /** * Factory, welche die Objekt-Instanzen erzeugt. */ public interface ObjectFactory { /** * Erzeugt ein neues Objekt des angegebenen Typs. * @param type Typ (Klassen-Name). * @param identifier ID. * @param attributes Map mit den Objekt-Attributen. * @return die Instanz des erzeugten Objektes. * @throws Exception */ public GenericObject create(String type, String identifier, Map attributes) throws Exception; } /********************************************************************* * $Log: ObjectFactory.java,v $ * Revision 1.1 2008/01/22 12:03:09 willuhn * @N Objekt-Serializer/-Deserializer fuer XML-Format * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/serialize/Reader.java000066400000000000000000000022451327610051000272070ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/serialize/Reader.java,v $ * $Revision: 1.1 $ * $Date: 2008/01/22 12:03:09 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.serialize; import java.io.IOException; import de.willuhn.datasource.GenericObject; /** * Interface zum Lesen von Objekten des Typs GenericObject. */ public interface Reader extends IO { /** * Liest das naechste Objekt aus dem Reader. * @return das naechste verfuegbare Objekt. * Wenn die Funktion null liefert, * ist der Reader "am Ende angekommen". * @throws IOException */ public GenericObject read() throws IOException; } /********************************************************************* * $Log: Reader.java,v $ * Revision 1.1 2008/01/22 12:03:09 willuhn * @N Objekt-Serializer/-Deserializer fuer XML-Format * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/serialize/Writer.java000066400000000000000000000021141327610051000272540ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/serialize/Writer.java,v $ * $Revision: 1.1 $ * $Date: 2008/01/22 12:03:09 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.serialize; import java.io.IOException; import de.willuhn.datasource.GenericObject; /** * Interface zum Schreiben von Objekten des Typs GenericObject. */ public interface Writer extends IO { /** * Serialisiert das Objekt. * @param object das zu serialisierende Objekt. * @throws IOException */ public void write(GenericObject object) throws IOException; } /********************************************************************* * $Log: Writer.java,v $ * Revision 1.1 2008/01/22 12:03:09 willuhn * @N Objekt-Serializer/-Deserializer fuer XML-Format * **********************************************************************/jameica-datasource-2.8.1+dfsg/src/de/willuhn/datasource/serialize/XmlReader.java000066400000000000000000000070461327610051000276740ustar00rootroot00000000000000/********************************************************************** * $Source: /cvsroot/jameica/datasource/src/de/willuhn/datasource/serialize/XmlReader.java,v $ * $Revision: 1.2 $ * $Date: 2008/09/29 14:18:00 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn software & services * All rights reserved * **********************************************************************/ package de.willuhn.datasource.serialize; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import de.willuhn.datasource.GenericObject; import de.willuhn.logging.Logger; /** * Implementierung des Readers im XML-Format. */ public class XmlReader extends AbstractXmlIO implements Reader { private InputStream is = null; private ObjectFactory factory = null; private Document doc = null; private int pos = 0; /** * ct * @param is InputStream, von dem gelesen werden soll. * @param factory ueber das die Objekt-Instanzen erzeugt werden sollen. * @throws Exception */ public XmlReader(InputStream is, ObjectFactory factory) throws Exception { this.is = is; this.factory = factory; this.doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); } /** * @see de.willuhn.datasource.serialize.Reader#read() */ public GenericObject read() throws IOException { NodeList objects = this.doc.getElementsByTagName("object"); if (objects == null || objects.getLength() == 0) return null; // Keine Objekte in der Datei Node current = objects.item(pos++); if (current == null) return null; // Am Ende angekommen NamedNodeMap attributes = current.getAttributes(); String type = attributes.getNamedItem("type").getNodeValue(); Node nid = attributes.getNamedItem("id"); String id = nid != null ? nid.getNodeValue() : null; HashMap values = new HashMap(); NodeList list = current.getChildNodes(); for (int i=0;i".getBytes(ENCODING)); } finally { super.close(); } } }; } /** * @see de.willuhn.datasource.serialize.IO#close() */ public void close() throws IOException { this.os.close(); } /** * Liefert die Namen der zu serialisierenden Attributes des Objektes. * Kann bei Bedarf ueberschrieben werden. * Die Default-Implementierung ruft die Methode "getAttributeNames()" * von GenericObject auf. * @param object das zu serialisierende Objekt. * @return die zu serialisierenden Attributes. * @throws RemoteException */ public String[] getAttributeNames(GenericObject object) throws RemoteException { return object.getAttributeNames(); } /** * @see de.willuhn.datasource.serialize.Writer#write(de.willuhn.datasource.GenericObject) */ public synchronized void write(GenericObject object) throws IOException { if (!headerWritten) { Logger.debug("writing xml header"); os.write(("\n\n").getBytes(ENCODING)); headerWritten = true; } Logger.debug("serializing object: " + object.getClass().getName() + ":" + object.getID()); StringBuffer sb = new StringBuffer(); sb.append(" \n"); String[] names = getAttributeNames(object); for (int i=0;i"); Value v = (Value) valueMap.get(type); if (v == null) v = (Value) valueMap.get(null); sb.append(encode(v.serialize(o))); sb.append("\n"); } sb.append(" \n"); os.write(sb.toString().getBytes(ENCODING)); } /** * Fuehrt XML-Escapings durch. * @param s zu escapender String. * @return der escapte String. */ private String encode(String s) { char[] chars = s.toCharArray(); StringBuffer sb = new StringBuffer(); for (int i=0;i