Project Report: fawkez

Packagesummary org.jcoderz.testdata

org.jcoderz.testdata.Importer

LineHitsNoteSource
1 (1)package org.jcoderz.testdata;
2  
3  import java.io.File;
4  import java.io.IOException;
5  import java.io.InputStream;
6  import java.sql.Connection;
7  import java.sql.DriverManager;
8  import java.sql.ResultSet;
9  import java.sql.SQLException;
10  import java.sql.SQLWarning;
11  import java.sql.Statement;
12  import java.util.ArrayList;
13  import java.util.Collection;
14  import java.util.HashMap;
15  import java.util.HashSet;
16  import java.util.Iterator;
17  import java.util.List;
18  import java.util.Locale;
19  import java.util.Map;
20  import java.util.Properties;
21  import java.util.Set;
22  import java.util.logging.Level;
23  import java.util.logging.Logger;
24  
25  import nu.xom.Builder;
26  import nu.xom.Document;
27  import nu.xom.Element;
28  import nu.xom.Node;
29  import nu.xom.Nodes;
30  import nu.xom.XPathContext;
31  import nu.xom.xinclude.XIncluder;
32  
33  import org.hibernate.SessionFactory;
34  import org.hibernate.cfg.Configuration;
35  import org.hibernate.mapping.Table;
36  
37  /**
38 (2) * Generic Test data importer. Recursively scans a directory for test data items and
39 (3) * submits them via JDBC to a predefined database. The tables and attribute names are
40 (4) * mapped straightforward to the hibernate configuration expected on the classpath. This
41   * implementation relies on auto index of all tables.
42   *
43   * @author Torsten Stolpmann
44   */
45 (5)public class Importer {
46  
47      private static final int ERROR_EXIT_CODE = 20;
48  
49      private static final String DEFAULT_TABLE_PREFIX = "S0IR_";
50  
51      private static final long DEFAULT_SEQUENCE_BASE = 100000L;
52  
53      private static final String SUFFIX_XML = ".xml";
54  
55      private static final String FILE_SEPARATOR = "/";
56  
570     private static final XPathContext TD_CONTEXT = new XPathContext("td",
58              "http://jcoderz.org/test-data");
59  
600(6)    static final Logger logger = Logger.getLogger(Importer.class.getName());
61  
62 (7)    private String tablePrefix;
63 (8)    private long sequenceBase;
64  
65 (9)    private Connection connection;
66  
67      /**
68       * The main method.
69       *
70       * @param args Command line arguments.
71       */
72 (10)(11)(12)(13)    public static void main(String[] args) {
73  
740(14)        if (args.length < 1) {
750             System.out.println("Usage: " + Importer.class.getName()
76                      + " <sourceDirectory>");
77          }
78  
790(15)        String sourceDirectory = args[0];
80  
810         Properties properties = new Properties();
820(16)        List<String> tableNames = new ArrayList<String>();
83  
840         logger.info("Starting import ...");
85  
860         Locale.setDefault(Locale.GERMANY);
87  
88 (17)        try {
890(18)            String defaultPropertiesName = "/testdata.properties";
90  
910(19)            InputStream defaultInput = Importer.class
92                      .getResourceAsStream(defaultPropertiesName);
930(20)            if (defaultInput != null) {
940(21)                logger.fine("Loading default properties (" + defaultPropertiesName + ")");
950                 properties.load(defaultInput); //$NON-NLS-1$
96 (22)(23)            } else {
970                 logger.fine("Default properties not found");
98              }
990(24)(25)            String userPropertiesName = FILE_SEPARATOR + System.getProperty("user.name")
100                      + ".properties";
1010(26)            InputStream userInput = Importer.class
102                      .getResourceAsStream(userPropertiesName);
1030(27)            if (userInput != null) {
1040                 logger.fine("Loading user properties");
1050                 properties.load(userInput); //$NON-NLS-1$
106 (28)(29)            } else {
1070(30)                logger.fine("User properties (" + userPropertiesName + ") not found");
108              }
1090             System.getProperties().putAll(properties);
1100             logger.warning(System.getProperties().toString());
1110             properties = System.getProperties();
112  
1130(31)            Configuration hibernateConfig = new Configuration();
1140             hibernateConfig.addProperties(properties);
1150             hibernateConfig.configure();
1160(32)            hibernateConfig.getProperties().remove("hibernate.connection.datasource");
1170             hibernateConfig.getProperties().remove(
118                      "hibernate.transaction.manager_lookup_class");
1190(33)            hibernateConfig.getProperties().remove("hibernate.transaction.factory_class");
120  
1210(34)            Iterator<?> iter = hibernateConfig.getTableMappings();
1220(35)            while (iter.hasNext()) {
1230(36)                Table table = (Table) iter.next();
1240(37)                tableNames.add(table.getName().toUpperCase());
1250             }
1260(38)            SessionFactory factory = hibernateConfig.buildSessionFactory();
1270(39)(40)        } catch (IOException e) {
1280             logger.log(Level.SEVERE, "Exception: ", e);
1290             System.exit(ERROR_EXIT_CODE);
1300         }
131  
1320(41)(42)        Importer importer = new Importer(DEFAULT_TABLE_PREFIX, DEFAULT_SEQUENCE_BASE);
133  
1340(43)        Map<String, Document> items = new HashMap<String, Document>();
135  
1360(44)        if (!importer.loadItems(sourceDirectory, items)) {
1370(45)            logger.log(Level.SEVERE, "Invalid test data set detected - aborting.");
1380             System.exit(ERROR_EXIT_CODE);
139          }
140  
1410(46)(47)        Map<String, Set<String>> dependencyMap = importer.buildDependencyMap(items);
142  
1430(48)        if (importer.validateDependencies(items, dependencyMap)) {
1440(49)            List<String> result = new ArrayList<String>();
1450(50)            List<String> leftover = new ArrayList<String>();
146  
1470             importer.reOrderItems(items, dependencyMap, result, leftover);
148  
1490(51)            List<String> queries = new ArrayList<String>();
1500(52)            if (importer.generateQueries(result, items, queries, null, tableNames, properties,
151 (53)                    false)) {
1520                 logger.info("Execution plan for constrained inserts:");
1530                 logger.info("---------------------------------------");
1540(54)                for (String query : queries) {
1550                     logger.info(query);
156                  }
1570                 logger.info("---------------------------------------");
158  
159 (55)(56)            } else {
1600                 logger
161 (57)                        .severe("No insert statements have been executed since errors have been detected.");
1620                 System.exit(ERROR_EXIT_CODE);
163              }
164  
1650(58)            List<String> leftOverQueries = new ArrayList<String>();
1660(59)            Set<String> postQueries = new HashSet<String>();
167  
1680(60)            if (importer.generateQueries(leftover, items, leftOverQueries, postQueries, tableNames,
169 (61)                    properties, true)) {
1700                 logger.info("Execution plan for unconstrained inserts:");
1710                 logger.info("-----------------------------------------");
1720(62)                for (String query : leftOverQueries) {
1730                     logger.info(query);
174                  }
175  
1760(63)                for (String query : postQueries) {
1770                     logger.info(query);
178                  }
1790                 logger.info("---------------------------------------");
180  
181 (64)(65)            } else {
1820                 logger
183 (66)                        .severe("No insert statements have been executed since errors have been detected.");
1840                 System.exit(ERROR_EXIT_CODE);
185              }
186  
1870             importer.executeQueries(properties, queries, false);
1880             importer.executeQueries(properties, leftOverQueries, false);
1890             importer.executeQueries(properties, postQueries, true);
190  
191 (67)            try {
1920(68)                Connection conn = importer.getConnection(properties);
1930                 conn.close();
1940(69)(70)            } catch (ClassNotFoundException e) {
1950                 logger.log(Level.SEVERE, "Exception: ", e);
1960(71)(72)            } catch (SQLException e) {
1970                 logger.log(Level.SEVERE, "Exception: ", e);
1980             }
1990(73)(74)        } else {
2000             logger
201 (75)                    .severe("No insert statements have been executed since errors have been detected.");
2020             System.exit(ERROR_EXIT_CODE);
203          }
2040     }
205  
2060(76)(77)(78)(79)    public Importer(final String prefix, final long base) {
207  
2080         tablePrefix = prefix;
2090         sequenceBase = base;
210  
2110     }
212  
213      /**
214       * Execute the supplied SQL queries.
215       *
216       * @param hibernateProperties the hibernate properties.
217       * @param queries the queries
218       */
219 (80)    private void executeQueries(final Properties hibernateProperties,
220 (81)            final Collection<String> queries, boolean delayErrors) {
221  
2220         boolean success = true;
223 (82)        try {
2240(83)            Connection conn = getConnection(hibernateProperties);
225  
2260             for (SQLWarning warn = conn.getWarnings(); warn != null; warn = warn
227 (84)                    .getNextWarning()) {
2280                 logger.warning("SQL Warning:");
2290                 logger.warning("State : " + warn.getSQLState());
2300                 logger.warning("Message: " + warn.getMessage());
2310                 logger.warning("Error : " + warn.getErrorCode());
232              }
233  
2340(85)(86)            Statement langStmt = conn.createStatement();
2350(87)            String alterStatement = "ALTER SESSION SET NLS_TERRITORY='AMERICA'";
2360             langStmt.execute(alterStatement);
2370             langStmt.close();
238  
2390(88)            for (String query : queries) {
240  
241 (89)                try {
2420                     logger.info(query);
2430(90)                    Statement stmt = conn.createStatement();
2440(91)(92)(93)                    ResultSet rs = stmt.executeQuery(query);
245  
2460                     rs.close();
2470                     stmt.close();
2480                     conn.commit();
2490(94)(95)                } catch (SQLException e) {
250  
2510                     logger.severe("SQL Exception:");
252  
2530(96)                    while (e != null) {
2540                         logger.severe("State : " + e.getSQLState());
2550                         logger.severe("Message: " + e.getMessage());
2560                         logger.severe("Error : " + e.getErrorCode());
257  
2580                         e = e.getNextException();
259                      }
2600(97)                    if (!delayErrors) {
2610(98)                        System.exit(ERROR_EXIT_CODE);
262                      }
2630                     success = false;
2640                 }
265              }
2660(99)(100)        } catch (SQLException e) {
267  
2680             logger.severe("SQL Exception:");
269  
2700(101)            while (e != null) {
2710                 logger.severe("State : " + e.getSQLState());
2720                 logger.severe("Message: " + e.getMessage());
2730                 logger.severe("Error : " + e.getErrorCode());
274  
2750                 e = e.getNextException();
276              }
2770(102)            if (!delayErrors) {
2780                 System.exit(ERROR_EXIT_CODE);
279              }
2800             success = false;
281  
2820(103)(104)        } catch (Exception e) {
2830             logger.log(Level.SEVERE, "Exception: ", e);
2840             System.exit(ERROR_EXIT_CODE);
2850         }
2860(105)        if (delayErrors && !success) {
2870             System.exit(ERROR_EXIT_CODE);
288          }
2890     }
290  
291      /**
292       * Write the map of documents.
293       *
294       * @param items the map of items
295       * @param queries the resulting queries
296       * @param postQueries the post insert queries
297       * @param idList the ordered list of item names
298       * @param tableNames the table names
299       * @param hibernateProperties the hibernate properties.
300       * @param disableConstraints true if constraints should be disabled here.
301       * @return true, if write
302       */
303 (106)(107)    private boolean generateQueries(final List<String> idList,
304              final Map<String, Document> items, final List<String> queries,
305              final Set<String> postQueries,
306              final List<String> tableNames, final Properties hibernateProperties,
307 (108)            final boolean disableConstraints) {
308  
3090         boolean valid = true;
310  
3110         final Set<String> preQueries = new HashSet<String>();
3120         final List<String> insertQueries = new ArrayList<String>();
313  
3140(109)        for (String id : idList) {
315  
3160(110)            StringBuffer query = new StringBuffer();
3170(111)            StringBuffer names = new StringBuffer("(");
3180(112)            StringBuffer values = new StringBuffer("(");
319  
3200(113)            Document item = items.get(id);
3210(114)            String tableName = getTableName(item);
322  
3230(115)            if (!tableNames.contains(tableName)) {
3240                 logger.severe("The type " + getItemType(item) + " of item "
325                          + getItemId(item)
326 (116)                        + " has no matching table in the current configuration ("
327                          + tableName + ")");
3280                 valid = false;
329              }
3300(117)            Map<String, Node> attributes = getAttributes(item);
331  
3320             int position = 0;
3330(118)            int end = attributes.entrySet().size();
334  
3350(119)            for (Map.Entry<String, Node> attribute : attributes.entrySet()) {
336  
3370                 position++;
338  
3390(120)(121)                String name = attribute.getKey().toUpperCase();
3400(122)                Node node = attribute.getValue();
341  
3420(123)                if (node instanceof Element) {
3430(124)                    Element element = (Element) node;
3440(125)(126)                    if (element.getLocalName().equals("value")) {
3450                         names.append(name);
3460(127)                        values.append("'");
3470                         values.append(element.getValue());
3480(128)                        values.append("'");
3490(129)(130)(131)                    } else if (element.getLocalName().equals("autovalue")) {
3500                         names.append(name);
3510                         values.append(getAsPrimaryKey(id));
3520(132)(133)(134)                    } else if (element.getLocalName().equals("ref")) {
3530(135)                        String reference = element.getValue();
3540(136)                        if (reference.length() > 0) {
3550(137)(138)                            if (items.containsKey(reference)) {
3560                                 names.append(name);
3570(139)                                values.append(getAsPrimaryKey(element.getValue()));
358 (140)(141)                            } else {
3590(142)                                logger.severe("ERROR! the reference " + reference
360                                          + " could not be resolved.");
3610                                 valid = false;
362                              }
363                          }
364                      }
365                  }
3660(143)                if (position == end) {
3670                     names.append(") ");
3680                     values.append(") ");
369 (144)(145)                } else {
3700                     names.append(", ");
3710                     values.append(", ");
372                  }
3730             }
3740(146)            if (attributes.size() > 0) {
3750(147)                query.append("INSERT INTO " + tableName);
3760(148)                query.append(" ");
3770                 query.append(names);
3780                 query.append(" VALUES ");
3790                 query.append(values);
380              }
3810             logger.fine(query.toString());
3820(149)            if (disableConstraints) {
3830                 preQueries.addAll(buildEnableConstraints(false, tableName,
384                          hibernateProperties));
3850                 insertQueries.add(query.toString());
3860                 postQueries.addAll(buildEnableConstraints(true, tableName,
387                          hibernateProperties));
388 (150)(151)            } else {
3890                 insertQueries.add(query.toString());
390              }
3910         }
3920         queries.addAll(preQueries);
3930         queries.addAll(insertQueries);
3940         return valid;
395      }
396  
397      /**
398       * Reorder the items.
399       *
400       * @param items the document items.
401       * @param dependencyMap the dependency map
402       * @param result the resulting list of id's
403       * @param leftover the leftover items if any.
404       */
405 (152)    private void reOrderItems(final Map<String, Document> items,
406 (153)            final Map<String, Set<String>> dependencyMap, final List<String> result,
407 (154)            final List<String> leftover) {
408  
409          boolean changed;
4100         logger.fine("Reordering " + items.size() + " items ...");
4110(155)        final Map<String, Document> itemPool = new HashMap<String, Document>(items);
412 (156)        do {
4130             changed = false;
414  
4150(157)            Iterator<Map.Entry<String, Document>> entries = itemPool.entrySet()
416                      .iterator();
4170(158)            while (entries.hasNext()) {
4180(159)                Map.Entry<String, Document> item = entries.next();
4190(160)                String id = item.getKey();
4200                 boolean accepted = true;
421  
4220(161)                Set<String> dependencies = dependencyMap.get(id);
4230(162)                for (String dependency : dependencies) {
4240(163)                    if (!result.contains(dependency)) {
4250                         accepted = false;
4260                         break;
427                      }
428                  }
4290(164)                if (accepted) {
4300(165)(166)                    List<String> declaredDependencies = getDeclaredDependencies(item
431                              .getValue());
4320(167)                    for (String declaredDependency : declaredDependencies) {
4330(168)                        if (!result.contains(declaredDependency)) {
4340                             accepted = false;
4350                             break;
436                          }
437                      }
438                  }
439  
4400(169)                if (accepted) {
4410                     logger.fine("Accepting item: " + id);
4420                     entries.remove();
4430                     result.add(id);
4440                     changed = true;
445                  }
4460             }
4470         } while (changed);
4480         logger.fine("Accepted " + result.size() + " items ...");
449  
4500(170)        if (!itemPool.isEmpty()) {
4510             logger
452 (171)                    .warning("Reference loop(s) detected! The following items will be added ignoring db-constraints:");
4530(172)            for (String id : itemPool.keySet()) {
4540                 leftover.add(id);
4550(173)                StringBuffer dependencyList = new StringBuffer();
4560(174)                Set<String> dependencies = dependencyMap.get(id);
4570(175)                for (String dependency : dependencies) {
4580                     dependencyList.append(dependency);
4590(176)                    dependencyList.append(" ");
460                  }
461  
4620                 logger.warning(id + ": [" + dependencyList.toString() + "]");
4630             }
464          }
4650     }
466  
467      /**
468       * Validate dependencies.
469       *
470       * @param items the items
471       * @param dependencyMap the dependency map
472       * @return true, if successful
473       */
474 (177)    private boolean validateDependencies(Map<String, Document> items,
475 (178)            Map<String, Set<String>> dependencyMap) {
476  
4770         boolean valid = true;
478  
4790(179)(180)        for (Map.Entry<String, Set<String>> dependenciesEntry : dependencyMap.entrySet()) {
480  
4810(181)            String id = dependenciesEntry.getKey();
4820(182)            Set<String> dependencies = dependenciesEntry.getValue();
4830(183)            for (String dependency : dependencies) {
4840(184)                if (!items.containsKey(dependency)) {
4850                     logger.severe("Item " + id + " contains invalid reference: "
486 (185)                            + dependency + " (Note: Self references are not allowed!)");
4870                     valid = false;
488                  }
489              }
4900         }
4910         return valid;
492      }
493  
494      /**
495       * Builds the dependency map.
496       *
497       * @param items the items to build from.
498       * @return the Map of dependencies.
499       */
500 (186)(187)(188)    private Map<String, Set<String>> buildDependencyMap(final Map<String, Document> items) {
501  
5020(189)(190)        Map<String, Set<String>> dependencyMap = new HashMap<String, Set<String>>();
503  
5040(191)        for (Map.Entry<String, Document> item : items.entrySet()) {
505  
5060(192)            String id = item.getKey();
5070(193)            Document document = item.getValue();
508  
5090(194)            Set<String> dependencies = new HashSet<String>();
510  
5110(195)(196)            Nodes references = document.query("/td:item/td:attribute/td:ref", TD_CONTEXT);
512  
5130(197)            for (int j = 0; j < references.size(); j++) {
5140(198)                Node node = references.get(j);
5150(199)                String refId = node.getValue();
5160(200)                if (refId.length() > 0) {
5170                     dependencies.add(refId);
518 (201)(202)                } else {
519                      // Drop empty references.
5200                     node.getParent().detach();
521                  }
522              }
523  
5240             dependencyMap.put(id, dependencies);
5250         }
5260         return dependencyMap;
527      }
528  
529      /**
530       * Recursively scan the directory and add found items to the map.
531       *
532       * @param dirName the directory name
533       * @param itemMap the item map
534       */
535 (203)(204)(205)    private boolean loadItems(String dirName, Map<String, Document> itemMap) {
536  
5370(206)        File rootDir = new File(dirName);
5380(207)        if (!rootDir.exists()) {
5390             logger.severe("Root directory '" + dirName + "' not found.");
5400             return false;
541          }
5420(208)        String[] entries = rootDir.list();
5430         boolean success = true;
544  
5450(209)        for (int i = 0; i < entries.length; i++) {
5460(210)            String entry = dirName + FILE_SEPARATOR + entries[i];
5470(211)            File subFile = new File(entry);
5480(212)            if (subFile.isDirectory()) {
5490                 success &= loadItems(entry, itemMap);
550 (213)(214)            } else {
5510(215)                if (subFile.getName().endsWith(SUFFIX_XML)) {
5520(216)                    Builder parser = new Builder(false);
553 (217)                    try {
5540(218)                        Document raw = parser.build(entry);
5550(219)                        Document document = XIncluder.resolve(raw);
5560(220)                        String id = getItemId(document);
557  
5580(221)                        if (itemMap.containsKey(id)) {
5590                             logger.severe("Duplicate id detected: " + id
560                                      + " - item will be skipped");
5610                             success = false;
562 (222)(223)                        } else {
5630                             itemMap.put(id, document);
5640                             logger.fine("Adding item: " + id);
565                          }
5660(224)(225)                    } catch (Exception e) {
5670(226)                        logger.log(Level.SEVERE, "Error parsing file " + entry + ": ", e);
5680                     }
569                  }
570              }
571          }
5720         return success;
573      }
574  
575      /**
576       * Gets the supplied id as a primary key representation.
577       *
578       * @param id the id
579       * @return the primary key
580       */
581 (227)(228)    protected String getAsPrimaryKey(final String id) {
582  
5830(229)(230)        return "" + (sequenceBase + Long.parseLong(id.substring(3)));
584      }
585  
586      /**
587       * Returns the table name for the given item.
588       *
589       * @param item the item
590       * @return the table name
591       */
592 (231)(232)    protected String getTableName(final Document item) {
593  
5940(233)        Node type = item.query("//td:item/td:type", TD_CONTEXT).get(0);
5950(234)        return tablePrefix + type.getValue().toUpperCase();
596      }
597  
598      /**
599       * Gets the item id.
600       *
601       * @param document the document containing the item.
602       * @return the item id if any, null else.
603       */
604 (235)(236)    private String getItemType(final Document document) {
605  
6060         String type = null;
607  
6080(237)        Nodes nodes = document.query("//td:item/td:type", TD_CONTEXT);
6090(238)        for (int j = 0; j < nodes.size(); j++) {
6100(239)            Node node = nodes.get(j);
6110             type = node.getValue();
6120             break;
613          }
6140(240)        if (type == null) {
6150             logger.severe(getItemId(document) + " contains no type element!");
616          }
6170         return type;
618      }
619  
620      /**
621       * Gets the item id.
622       *
623       * @param document the document containing the item.
624       * @return the item id if any, null else.
625       */
626 (241)(242)    private String getItemId(final Document document) {
627  
6280         String id = null;
629  
6300(243)        Nodes nodes = document.query("//td:item/td:id", TD_CONTEXT);
6310(244)        for (int j = 0; j < nodes.size(); j++) {
6320(245)            Node node = nodes.get(j);
6330             id = node.getValue();
6340             break;
635          }
6360         return id;
637      }
638  
639      /**
640       * Return the item attributes.
641       *
642       * @param document the document containing the item.
643       * @return the attributes of this item.
644       */
645 (246)(247)    private Map<String, Node> getAttributes(final Document document) {
646  
6470(248)        Map<String, Node> attributeMap = new HashMap<String, Node>();
648  
6490(249)        Nodes attributes = document.query("//td:item/td:attribute", TD_CONTEXT);
6500(250)        for (int j = 0; j < attributes.size(); j++) {
6510(251)            Node attribute = attributes.get(j);
6520(252)(253)            String name = attribute.query("td:name", TD_CONTEXT).get(0).getValue();
6530(254)(255)            Nodes values = attribute.query("td:value|td:autovalue|td:ref", TD_CONTEXT);
6540(256)            if (values.size() > 0) {
6550                 attributeMap.put(name, values.get(0));
656              }
657          }
6580         return attributeMap;
659      }
660  
661      /**
662       * Return the explicit item dependencies.
663       *
664       * @param document the document containing the item.
665       * @return the explicit dependencies of this item.
666       */
667 (257)(258)    private List<String> getDeclaredDependencies(final Document document) {
668  
6690(259)        List<String> result = new ArrayList<String>();
670  
6710(260)(261)        Nodes dependencies = document.query("//td:item/td:dependency", TD_CONTEXT);
6720(262)        for (int j = 0; j < dependencies.size(); j++) {
6730(263)            Node dependency = dependencies.get(j);
6740             result.add(dependency.getValue());
675          }
6760         return result;
677      }
678  
679      /**
680       * Enable database constraints.
681       *
682       * @param enabled the enabled flag
683       * @param tableName the table name
684       * @param hibernateProperties the hibernate properties
685       * @return the list of queries
686       */
687 (264)    private List<String> buildEnableConstraints(final boolean enabled,
688 (265)            final String tableName, final Properties hibernateProperties) {
689  
6900         final List<String> queries = new ArrayList<String>();
6910(266)(267)        List<String> constraints = getConstraints(tableName, hibernateProperties);
6920(268)        for (String constraint : constraints) {
693  
694              final String query;
6950(269)            if (enabled) {
6960(270)                query = "ALTER TABLE " + tableName + " ENABLE CONSTRAINT " + constraint;
697 (271)(272)            } else {
6980(273)                query = "ALTER TABLE " + tableName + " DISABLE CONSTRAINT " + constraint;
699              }
7000             queries.add(query);
7010         }
7020         return queries;
703      }
704  
705 (274)(275)(276)    private List<String> getConstraints(String tableName, Properties hibernateProperties) {
706  
7070         final List<String> constraints = new ArrayList<String>();
708 (277)        try {
7090(278)            Connection conn = getConnection(hibernateProperties);
710  
7110             for (SQLWarning warn = conn.getWarnings(); warn != null; warn = warn
712 (279)                    .getNextWarning()) {
7130                 logger.warning("SQL Warning:");
7140                 logger.warning("State : " + warn.getSQLState());
7150                 logger.warning("Message: " + warn.getMessage());
7160                 logger.warning("Error : " + warn.getErrorCode());
717              }
718  
7190(280)(281)            String query = "select constraint_name from user_constraints where table_name ='"
720                      + tableName + "' and constraint_type='R'";
721  
7220             logger.info(query);
7230(282)(283)(284)            Statement stmt = conn.createStatement();
7240(285)(286)(287)            ResultSet rs = stmt.executeQuery(query);
7250(288)            while (rs.next()) {
7260(289)                String constraint = rs.getString(1);
7270                 constraints.add(constraint);
7280             }
7290             rs.close();
7300             stmt.close();
7310(290)(291)        } catch (SQLException e) {
732  
7330             logger.severe("SQL Exception:");
734  
7350(292)            while (e != null) {
7360                 logger.severe("State : " + e.getSQLState());
7370                 logger.severe("Message: " + e.getMessage());
7380                 logger.severe("Error : " + e.getErrorCode());
739  
7400                 e = e.getNextException();
741              }
7420(293)(294)        } catch (Exception e) {
7430             logger.log(Level.SEVERE, "Exception: ", e);
7440         }
7450         return constraints;
746      }
747  
748      /**
749       * Gets the database connection for the given properties.
750       *
751       * @param hibernateProperties the hibernate properties
752       * @return the connection
753       * @throws ClassNotFoundException the class not found exception
754       * @throws SQLException the SQL exception
755       */
756 (295)    private Connection getConnection(final Properties hibernateProperties)
757 (296)            throws ClassNotFoundException, SQLException {
758  
7590(297)        if (connection == null) {
7600             Class.forName(hibernateProperties
761                      .getProperty("hibernate.connection.driver_class"));
762  
7630(298)            Properties info = new Properties();
7640             info.setProperty("user", hibernateProperties
765                      .getProperty("hibernate.connection.username"));
7660             info.setProperty("password", hibernateProperties
767                      .getProperty("hibernate.connection.password"));
7680             info.setProperty("useUnicode", "true");
7690             info.setProperty("characterEncoding", "UTF-8");
770  
7710             connection = DriverManager.getConnection(hibernateProperties
772                      .getProperty("hibernate.connection.url"), info);
773          }
7740         return connection;
775      }
776  }

Findings in this File

f (299) method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) creates local variable-based synchronized collection We are still on Java 1.4 here.
f (300) method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) creates local variable-based synchronized collection We are still on Java 1.4 here.
f (301) method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) creates local variable-based synchronized collection We are still on Java 1.4 here.
f (302) method org.jcoderz.testdata.Importer.reOrderItems(Map, Map, List, List) creates local variable-based synchronized collection We are still on Java 1.4 here.
c (1) 1 : 0 Line does not match expected header line of '^/\*$'.
c (2) 38 : 0 Line is longer than 80 characters.
c (3) 39 : 0 Line is longer than 80 characters.
c (4) 40 : 0 Line is longer than 80 characters.
c (5) 45 : 23 '{' should be on a new line.
c (6) 60 : 5 Variable access definition in wrong order.
c (7) 62 : 20 Name 'tablePrefix' must match pattern '^m[A-Z][a-zA-Z0-9]*$'.
c (8) 63 : 18 Name 'sequenceBase' must match pattern '^m[A-Z][a-zA-Z0-9]*$'.
c (9) 65 : 24 Name 'connection' must match pattern '^m[A-Z][a-zA-Z0-9]*$'.
c (10) 72 : 5 Cyclomatic Complexity is 15 (max allowed is 12).
d (11) 72 : 5 Method length is 133 lines (max allowed is 100).
c (12) 72 : 28 '(' is not preceded with whitespace.
c (13) 72 : 44 '{' should be on a new line.
c (14) 74 : 30 '{' should be on a new line.
c (15) 79 : 16 Variable 'sourceDirectory' should be declared final.
c (16) 82 : 22 Variable 'tableNames' should be declared final.
c (17) 88 : 13 '{' should be on a new line.
c (18) 89 : 20 Variable 'defaultPropertiesName' should be declared final.
c (19) 91 : 25 Variable 'defaultInput' should be declared final.
c (20) 93 : 39 '{' should be on a new line.
c (21) 94 : 0 Line is longer than 80 characters.
c (22) 96 : 13 '}' should be alone on a line.
c (23) 96 : 20 '{' should be on a new line.
c (24) 99 : 0 Line is longer than 80 characters.
c (25) 99 : 20 Variable 'userPropertiesName' should be declared final.
c (26) 101 : 25 Variable 'userInput' should be declared final.
c (27) 103 : 36 '{' should be on a new line.
c (28) 106 : 13 '}' should be alone on a line.
c (29) 106 : 20 '{' should be on a new line.
c (30) 107 : 0 Line is longer than 80 characters.
c (31) 113 : 27 Variable 'hibernateConfig' should be declared final.
c (32) 116 : 0 Line is longer than 80 characters.
c (33) 119 : 0 Line is longer than 80 characters.
c (34) 121 : 25 Variable 'iter' should be declared final.
c (35) 122 : 36 '{' should be on a new line.
c (36) 123 : 23 Variable 'table' should be declared final.
i (37) 124 : 0 Use of non-localized String.toUpperCase() or String.toLowerCase
c (38) 126 : 28 Variable 'factory' should be declared final.
c (39) 127 : 9 '}' should be alone on a line.
c (40) 127 : 33 '{' should be on a new line.
c (41) 132 : 0 Line is longer than 80 characters.
c (42) 132 : 18 Variable 'importer' should be declared final.
c (43) 134 : 31 Variable 'items' should be declared final.
c (44) 136 : 58 '{' should be on a new line.
c (45) 137 : 0 Line is longer than 80 characters.
c (46) 141 : 0 Line is longer than 80 characters.
c (47) 141 : 34 Variable 'dependencyMap' should be declared final.
c (48) 143 : 66 '{' should be on a new line.
c (49) 144 : 26 Variable 'result' should be declared final.
c (50) 145 : 26 Variable 'leftover' should be declared final.
c (51) 149 : 26 Variable 'queries' should be declared final.
c (52) 150 : 0 Line is longer than 80 characters.
c (53) 151 : 29 '{' should be on a new line.
c (54) 154 : 46 '{' should be on a new line.
c (55) 159 : 13 '}' should be alone on a line.
c (56) 159 : 20 '{' should be on a new line.
c (57) 161 : 0 Line is longer than 80 characters.
c (58) 165 : 26 Variable 'leftOverQueries' should be declared final.
c (59) 166 : 25 Variable 'postQueries' should be declared final.
c (60) 168 : 0 Line is longer than 80 characters.
c (61) 169 : 40 '{' should be on a new line.
c (62) 172 : 54 '{' should be on a new line.
c (63) 176 : 50 '{' should be on a new line.
c (64) 181 : 13 '}' should be alone on a line.
c (65) 181 : 20 '{' should be on a new line.
c (66) 183 : 0 Line is longer than 80 characters.
c (67) 191 : 17 '{' should be on a new line.
c (68) 192 : 28 Variable 'conn' should be declared final.
c (69) 194 : 13 '}' should be alone on a line.
c (70) 194 : 48 '{' should be on a new line.
c (71) 196 : 13 '}' should be alone on a line.
c (72) 196 : 38 '{' should be on a new line.
c (73) 199 : 9 '}' should be alone on a line.
c (74) 199 : 16 '{' should be on a new line.
c (75) 201 : 0 Line is longer than 80 characters.
c (76) 206 : 5 Constructor definition in wrong order.
c (77) 206 : 5 Missing a Javadoc comment.
c (78) 206 : 20 '(' is not preceded with whitespace.
c (79) 206 : 59 '{' should be on a new line.
c (80) 219 : 32 '(' is not preceded with whitespace.
c (81) 220 : 68 '{' should be on a new line.
c (82) 223 : 13 '{' should be on a new line.
c (83) 224 : 24 Variable 'conn' should be declared final.
c (84) 227 : 40 '{' should be on a new line.
c (85) 234 : 23 Variable 'langStmt' should be declared final.
i (86) 234 : 0 org.jcoderz.testdata.Importer.executeQueries(Properties, Collection, boolean) may fail to close database resource on exception
c (87) 235 : 20 Variable 'alterStatement' should be declared final.
c (88) 239 : 42 '{' should be on a new line.
c (89) 241 : 21 '{' should be on a new line.
c (90) 243 : 31 Variable 'stmt' should be declared final.
c (91) 244 : 31 Variable 'rs' should be declared final.
w (92) 244 : 0 Method org.jcoderz.testdata.Importer.executeQueries(Properties, Collection, boolean) executes sql queries inside of loops
i (93) 244 : 0 Method org.jcoderz.testdata.Importer.executeQueries(Properties, Collection, boolean) passes a nonconstant String to an execute method on an SQL statement
c (94) 249 : 17 '}' should be alone on a line.
c (95) 249 : 42 '{' should be on a new line.
c (96) 253 : 39 '{' should be on a new line.
c (97) 260 : 39 '{' should be on a new line.
w (98) 261 : 0 org.jcoderz.testdata.Importer.executeQueries(Properties, Collection, boolean) invokes System.exit(...), which shuts down the entire virtual machine
c (99) 266 : 9 '}' should be alone on a line.
c (100) 266 : 34 '{' should be on a new line.
c (101) 270 : 31 '{' should be on a new line.
c (102) 277 : 31 '{' should be on a new line.
c (103) 282 : 9 '}' should be alone on a line.
c (104) 282 : 31 '{' should be on a new line.
c (105) 286 : 38 '{' should be on a new line.
c (106) 303 : 5 Cyclomatic Complexity is 13 (max allowed is 12).
c (107) 303 : 36 '(' is not preceded with whitespace.
c (108) 307 : 47 '{' should be on a new line.
c (109) 314 : 34 '{' should be on a new line.
c (110) 316 : 26 Variable 'query' should be declared final.
c (111) 317 : 26 Variable 'names' should be declared final.
c (112) 318 : 26 Variable 'values' should be declared final.
c (113) 320 : 22 Variable 'item' should be declared final.
c (114) 321 : 20 Variable 'tableName' should be declared final.
c (115) 323 : 50 '{' should be on a new line.
c (116) 326 : 0 Line is longer than 80 characters.
c (117) 330 : 31 Variable 'attributes' should be declared final.
c (118) 333 : 17 Variable 'end' should be declared final.
c (119) 335 : 77 '{' should be on a new line.
c (120) 339 : 24 Variable 'name' should be declared final.
i (121) 339 : 0 Use of non-localized String.toUpperCase() or String.toLowerCase
c (122) 340 : 22 Variable 'node' should be declared final.
c (123) 342 : 46 '{' should be on a new line.
c (124) 343 : 29 Variable 'element' should be declared final.
c (125) 344 : 65 '{' should be on a new line.
i (126) 344 : 0 method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) makes literal string comparisons passing the literal as an argument
w (127) 346 : 0 Method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) passes constant String of length 1 to character overridden method
w (128) 348 : 0 Method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) passes constant String of length 1 to character overridden method
c (129) 349 : 21 '}' should be alone on a line.
c (130) 349 : 76 '{' should be on a new line.
i (131) 349 : 0 method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) makes literal string comparisons passing the literal as an argument
c (132) 352 : 21 '}' should be alone on a line.
c (133) 352 : 70 '{' should be on a new line.
i (134) 352 : 0 method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) makes literal string comparisons passing the literal as an argument
c (135) 353 : 32 Variable 'reference' should be declared final.
c (136) 354 : 53 '{' should be on a new line.
c (137) 355 : 29 Nested if-else depth is 3 (max allowed is 2).
c (138) 355 : 63 '{' should be on a new line.
c (139) 357 : 0 Line is longer than 80 characters.
c (140) 358 : 29 '}' should be alone on a line.
c (141) 358 : 36 '{' should be on a new line.
c (142) 359 : 0 Line is longer than 80 characters.
c (143) 366 : 38 '{' should be on a new line.
c (144) 369 : 17 '}' should be alone on a line.
c (145) 369 : 24 '{' should be on a new line.
c (146) 374 : 40 '{' should be on a new line.
w (147) 375 : 0 method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) passes simple concatenating string in StringBuffer or StringBuilder append
w (148) 376 : 0 Method org.jcoderz.testdata.Importer.generateQueries(List, Map, List, Set, List, Properties, boolean) passes constant String of length 1 to character overridden method
c (149) 382 : 37 '{' should be on a new line.
c (150) 388 : 13 '}' should be alone on a line.
c (151) 388 : 20 '{' should be on a new line.
c (152) 405 : 30 '(' is not preceded with whitespace.
c (153) 406 : 0 Line is longer than 80 characters.
c (154) 407 : 42 '{' should be on a new line.
c (155) 411 : 0 Line is longer than 80 characters.
c (156) 412 : 12 '{' should be on a new line.
c (157) 415 : 51 Variable 'entries' should be declared final.
c (158) 417 : 39 '{' should be on a new line.
c (159) 418 : 45 Variable 'item' should be declared final.
c (160) 419 : 24 Variable 'id' should be declared final.
c (161) 422 : 29 Variable 'dependencies' should be declared final.
c (162) 423 : 56 '{' should be on a new line.
c (163) 424 : 55 '{' should be on a new line.
c (164) 429 : 31 '{' should be on a new line.
c (165) 430 : 0 Line is longer than 80 characters.
c (166) 430 : 34 Variable 'declaredDependencies' should be declared final.
c (167) 432 : 76 '{' should be on a new line.
c (168) 433 : 67 '{' should be on a new line.
c (169) 440 : 31 '{' should be on a new line.
c (170) 450 : 34 '{' should be on a new line.
c (171) 452 : 0 Line is longer than 80 characters.
c (172) 453 : 49 '{' should be on a new line.
c (173) 455 : 30 Variable 'dependencyList' should be declared final.
c (174) 456 : 29 Variable 'dependencies' should be declared final.
c (175) 457 : 56 '{' should be on a new line.
w (176) 459 : 0 Method org.jcoderz.testdata.Importer.reOrderItems(Map, Map, List, List) passes constant String of length 1 to character overridden method
c (177) 474 : 41 '(' is not preceded with whitespace.
c (178) 475 : 53 '{' should be on a new line.
c (179) 479 : 0 Line is longer than 80 characters.
c (180) 479 : 91 '{' should be on a new line.
c (181) 481 : 20 Variable 'id' should be declared final.
c (182) 482 : 25 Variable 'dependencies' should be declared final.
c (183) 483 : 52 '{' should be on a new line.
c (184) 484 : 53 '{' should be on a new line.
c (185) 486 : 0 Line is longer than 80 characters.
c (186) 500 : 0 Line is longer than 80 characters.
c (187) 500 : 56 '(' is not preceded with whitespace.
c (188) 500 : 92 '{' should be on a new line.
c (189) 502 : 0 Line is longer than 80 characters.
c (190) 502 : 34 Variable 'dependencyMap' should be declared final.
c (191) 504 : 67 '{' should be on a new line.
c (192) 506 : 20 Variable 'id' should be declared final.
c (193) 507 : 22 Variable 'document' should be declared final.
c (194) 509 : 25 Variable 'dependencies' should be declared final.
c (195) 511 : 0 Line is longer than 80 characters.
c (196) 511 : 19 Variable 'references' should be declared final.
c (197) 513 : 57 '{' should be on a new line.
c (198) 514 : 22 Variable 'node' should be declared final.
c (199) 515 : 24 Variable 'refId' should be declared final.
c (200) 516 : 41 '{' should be on a new line.
c (201) 518 : 17 '}' should be alone on a line.
c (202) 518 : 24 '{' should be on a new line.
c (203) 535 : 5 Return count is 2 (max allowed is 1).
c (204) 535 : 30 '(' is not preceded with whitespace.
c (205) 535 : 78 '{' should be on a new line.
c (206) 537 : 14 Variable 'rootDir' should be declared final.
c (207) 538 : 32 '{' should be on a new line.
c (208) 542 : 18 Variable 'entries' should be declared final.
c (209) 545 : 50 '{' should be on a new line.
c (210) 546 : 20 Variable 'entry' should be declared final.
c (211) 547 : 18 Variable 'subFile' should be declared final.
c (212) 548 : 40 '{' should be on a new line.
c (213) 550 : 13 '}' should be alone on a line.
c (214) 550 : 20 '{' should be on a new line.
c (215) 551 : 61 '{' should be on a new line.
c (216) 552 : 29 Variable 'parser' should be declared final.
c (217) 553 : 25 '{' should be on a new line.
c (218) 554 : 34 Variable 'raw' should be declared final.
c (219) 555 : 34 Variable 'document' should be declared final.
c (220) 556 : 32 Variable 'id' should be declared final.
c (221) 558 : 54 '{' should be on a new line.
c (222) 562 : 25 '}' should be alone on a line.
c (223) 562 : 32 '{' should be on a new line.
c (224) 566 : 21 '}' should be alone on a line.
c (225) 566 : 43 '{' should be on a new line.
c (226) 567 : 0 Line is longer than 80 characters.
c (227) 581 : 37 '(' is not preceded with whitespace.
c (228) 581 : 55 '{' should be on a new line.
c (229) 583 : 65 '3' is a magic number.
w (230) 583 : 0 method org.jcoderz.testdata.Importer.getAsPrimaryKey(String) concatenates an empty string to effect type conversion
c (231) 592 : 34 '(' is not preceded with whitespace.
c (232) 592 : 56 '{' should be on a new line.
c (233) 594 : 14 Variable 'type' should be declared final.
i (234) 595 : 0 Use of non-localized String.toUpperCase() or String.toLowerCase
c (235) 604 : 31 '(' is not preceded with whitespace.
c (236) 604 : 57 '{' should be on a new line.
c (237) 608 : 15 Variable 'nodes' should be declared final.
c (238) 609 : 48 '{' should be on a new line.
c (239) 610 : 18 Variable 'node' should be declared final.
c (240) 614 : 27 '{' should be on a new line.
c (241) 626 : 29 '(' is not preceded with whitespace.
c (242) 626 : 55 '{' should be on a new line.
c (243) 630 : 15 Variable 'nodes' should be declared final.
c (244) 631 : 48 '{' should be on a new line.
c (245) 632 : 18 Variable 'node' should be declared final.
c (246) 645 : 44 '(' is not preceded with whitespace.
c (247) 645 : 70 '{' should be on a new line.
c (248) 647 : 27 Variable 'attributeMap' should be declared final.
c (249) 649 : 15 Variable 'attributes' should be declared final.
c (250) 650 : 53 '{' should be on a new line.
c (251) 651 : 18 Variable 'attribute' should be declared final.
c (252) 652 : 0 Line is longer than 80 characters.
c (253) 652 : 20 Variable 'name' should be declared final.
c (254) 653 : 0 Line is longer than 80 characters.
c (255) 653 : 19 Variable 'values' should be declared final.
c (256) 654 : 36 '{' should be on a new line.
c (257) 667 : 49 '(' is not preceded with whitespace.
c (258) 667 : 75 '{' should be on a new line.
c (259) 669 : 22 Variable 'result' should be declared final.
c (260) 671 : 0 Line is longer than 80 characters.
c (261) 671 : 15 Variable 'dependencies' should be declared final.
c (262) 672 : 55 '{' should be on a new line.
c (263) 673 : 18 Variable 'dependency' should be declared final.
c (264) 687 : 48 '(' is not preceded with whitespace.
c (265) 688 : 75 '{' should be on a new line.
c (266) 691 : 0 Line is longer than 80 characters.
c (267) 691 : 22 Variable 'constraints' should be declared final.
c (268) 692 : 47 '{' should be on a new line.
c (269) 695 : 26 '{' should be on a new line.
c (270) 696 : 0 Line is longer than 80 characters.
c (271) 697 : 13 '}' should be alone on a line.
c (272) 697 : 20 '{' should be on a new line.
c (273) 698 : 0 Line is longer than 80 characters.
c (274) 705 : 0 Line is longer than 80 characters.
c (275) 705 : 40 '(' is not preceded with whitespace.
c (276) 705 : 91 '{' should be on a new line.
c (277) 708 : 13 '{' should be on a new line.
c (278) 709 : 24 Variable 'conn' should be declared final.
c (279) 712 : 40 '{' should be on a new line.
c (280) 719 : 0 Line is longer than 80 characters.
c (281) 719 : 20 Variable 'query' should be declared final.
c (282) 723 : 23 Variable 'stmt' should be declared final.
w (283) 723 : 0 Method org.jcoderz.testdata.Importer.getConstraints(String, Properties) may fail to clean up stream or resource of type java.sql.Statement
i (284) 723 : 0 org.jcoderz.testdata.Importer.getConstraints(String, Properties) may fail to close database resource on exception
c (285) 724 : 23 Variable 'rs' should be declared final.
w (286) 724 : 0 Method org.jcoderz.testdata.Importer.getConstraints(String, Properties) may fail to clean up stream or resource of type java.sql.ResultSet
e (287) 724 : 0 Method org.jcoderz.testdata.Importer.getConstraints(String, Properties) passes a nonconstant String to an execute method on an SQL statement
c (288) 725 : 31 '{' should be on a new line.
c (289) 726 : 24 Variable 'constraint' should be declared final.
c (290) 731 : 9 '}' should be alone on a line.
c (291) 731 : 34 '{' should be on a new line.
c (292) 735 : 31 '{' should be on a new line.
c (293) 742 : 9 '}' should be alone on a line.
c (294) 742 : 31 '{' should be on a new line.
c (295) 756 : 37 '(' is not preceded with whitespace.
c (296) 757 : 57 '{' should be on a new line.
c (297) 759 : 33 '{' should be on a new line.
c (298) 763 : 24 Variable 'info' should be declared final.