http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/PojoGenerator.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/PojoGenerator.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/PojoGenerator.java deleted file mode 100644 index 500aa9a..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/PojoGenerator.java +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.generator; - -import org.apache.ignite.schema.model.*; -import org.apache.ignite.schema.ui.*; - -import java.io.*; -import java.text.*; -import java.util.*; - -import static org.apache.ignite.schema.ui.MessageBox.Result.*; - -/** - * POJO generator for key and value classes. - */ -public class PojoGenerator { - /** */ - private static final String TAB = " "; - /** */ - private static final String TAB2 = TAB + TAB; - /** */ - private static final String TAB3 = TAB + TAB + TAB; - - /** - * Add line to source code without indent. - * - * @param src Source code. - * @param line Code line. - */ - private static void add0(Collection<String> src, String line) { - src.add(line); - } - - /** - * Add line to source code with one indent. - * - * @param src Source code. - * @param line Code line. - */ - private static void add1(Collection<String> src, String line) { - src.add(TAB + line); - } - - /** - * Add line to source code with two indents. - * - * @param src Source code. - * @param line Code line. - */ - private static void add2(Collection<String> src, String line) { - src.add(TAB2 + line); - } - - /** - * Add line to source code with two indents. - * - * @param src Source code. - * @param fmt Code line with format placeholders. - * @param args Format arguments. - */ - private static void add2Fmt(Collection<String> src, String fmt, Object... args) { - add2(src, String.format(fmt, args)); - } - - /** - * Add line to source code with three indents. - * - * @param src Source code. - * @param line Code line. - */ - private static void add3(Collection<String> src, String line) { - src.add(TAB3 + line); - } - - /** - * @param str Source string. - * @return String with first letters in upper case. - */ - private static String capitalizeFirst(String str) { - return Character.toUpperCase(str.charAt(0)) + str.substring(1); - } - - /** - * @param field POJO field descriptor. - * @return Field java type name. - */ - private static String javaTypeName(PojoField field) { - String javaTypeName = field.javaTypeName(); - - return javaTypeName.startsWith("java.lang.") ? javaTypeName.substring(10) : javaTypeName; - } - - /** - * Generate java class code. - * - * @param pojo POJO descriptor. - * @param key {@code true} if key class should be generated. - * @param pkg Package name. - * @param pkgFolder Folder where to save generated class. - * @param constructor {@code true} if empty and full constructors should be generated. - * @param includeKeys {@code true} if key fields should be included into value class. - * @param askOverwrite Callback to ask user to confirm file overwrite. - * @throws IOException If failed to write generated code into file. - */ - private static void generateCode(PojoDescriptor pojo, boolean key, String pkg, File pkgFolder, - boolean constructor, boolean includeKeys, ConfirmCallable askOverwrite) throws IOException { - String type = key ? pojo.keyClassName() : pojo.valueClassName(); - - File out = new File(pkgFolder, type + ".java"); - - if (out.exists()) { - MessageBox.Result choice = askOverwrite.confirm(out.getName()); - - if (CANCEL == choice) - throw new IllegalStateException("POJO generation was canceled!"); - - if (NO == choice || NO_TO_ALL == choice) - return; - } - - Collection<String> src = new ArrayList<>(256); - - // License. - add0(src, "/*"); - add0(src, " * Licensed to the Apache Software Foundation (ASF) under one or more"); - add0(src, " * contributor license agreements. See the NOTICE file distributed with"); - add0(src, " * this work for additional information regarding copyright ownership."); - add0(src, " * The ASF licenses this file to You under the Apache License, Version 2.0"); - add0(src, " * (the \"License\"); you may not use this file except in compliance with"); - add0(src, " * the License. You may obtain a copy of the License at"); - add0(src, " *"); - add0(src, " * http://www.apache.org/licenses/LICENSE-2.0"); - add0(src, " *"); - add0(src, " * Unless required by applicable law or agreed to in writing, software"); - add0(src, " * distributed under the License is distributed on an \"AS IS\" BASIS,"); - add0(src, " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."); - add0(src, " * See the License for the specific language governing permissions and"); - add0(src, " * limitations under the License."); - add0(src, " */"); - add0(src, ""); - - // Package. - add0(src, "package " + pkg + ";"); - add0(src, ""); - - // Imports. - add0(src, "import java.io.*;"); - add0(src, ""); - - // Class. - add0(src, "/**"); - add0(src, " * " + type + " definition."); - add0(src, " *"); - add0(src, " * Code generated by Apache Ignite Schema Load utility: " + new SimpleDateFormat("MM/dd/yyyy").format(new Date()) + "."); - add0(src, " */"); - add0(src, "public class " + type + " implements Serializable {"); - - add1(src, "/** */"); - add1(src, "private static final long serialVersionUID = 0L;"); - add0(src, ""); - - Collection<PojoField> fields = key ? pojo.keyFields() : pojo.valueFields(includeKeys); - - // Generate fields declaration. - for (PojoField field : fields) { - String fldName = field.javaName(); - - add1(src, "/** Value for " + fldName + ". */"); - - if (key && field.affinityKey()) - add1(src, "@CacheAffinityKeyMapped"); - - add1(src, "private " + javaTypeName(field) + " " + fldName + ";"); - add0(src, ""); - } - - // Generate constructors. - if (constructor) { - add1(src, "/**"); - add1(src, " * Empty constructor."); - add1(src, " */"); - add1(src, "public " + type + "() {"); - add2(src, "// No-op."); - add1(src, "}"); - - add0(src, ""); - - add1(src, "/**"); - add1(src, " * Full constructor."); - add1(src, " */"); - add1(src, "public " + type + "("); - - Iterator<PojoField> it = fields.iterator(); - - while (it.hasNext()) { - PojoField field = it.next(); - - add2(src, javaTypeName(field) + " " + field.javaName() + (it.hasNext() ? "," : "")); - } - add1(src, ") {"); - - for (PojoField field : fields) - add2Fmt(src, "this.%1$s = %1$s;", field.javaName()); - - add1(src, "}"); - add0(src, ""); - } - - // Generate getters and setters methods. - for (PojoField field : fields) { - String fldName = field.javaName(); - - String fldType = javaTypeName(field); - - String mtdName = capitalizeFirst(fldName); - - add1(src, "/**"); - add1(src, " * Gets " + fldName + "."); - add1(src, " *"); - add1(src, " * @return Value for " + fldName + "."); - add1(src, " */"); - add1(src, "public " + fldType + " get" + mtdName + "() {"); - add2(src, "return " + fldName + ";"); - add1(src, "}"); - add0(src, ""); - - add1(src, "/**"); - add1(src, " * Sets " + fldName + "."); - add1(src, " *"); - add1(src, " * @param " + fldName + " New value for " + fldName + "."); - add1(src, " */"); - add1(src, "public void set" + mtdName + "(" + fldType + " " + fldName + ") {"); - add2(src, "this." + fldName + " = " + fldName + ";"); - add1(src, "}"); - add0(src, ""); - } - - // Generate equals() method. - add1(src, "/** {@inheritDoc} */"); - add1(src, "@Override public boolean equals(Object o) {"); - add2(src, "if (this == o)"); - add3(src, "return true;"); - add0(src, ""); - - add2(src, "if (!(o instanceof " + type + "))"); - add3(src, "return false;"); - add0(src, ""); - - add2Fmt(src, "%1$s that = (%1$s)o;", type); - - for (PojoField field : fields) { - add0(src, ""); - - String javaName = field.javaName(); - - if (field.primitive()) { - switch (field.javaTypeName()) { - case "float": - add2Fmt(src, "if (Float.compare(%1$s, that.%1$s) != 0)", javaName); - break; - - case "double": - add2Fmt(src, "if (Double.compare(%1$s, that.%1$s) != 0)", javaName); - break; - - default: - add2Fmt(src, "if (%1$s != that.%1$s)", javaName); - } - } - else - add2Fmt(src, "if (%1$s != null ? !%1$s.equals(that.%1$s) : that.%1$s != null)", javaName); - - add3(src, "return false;"); - } - - add0(src, ""); - add2(src, "return true;"); - add1(src, "}"); - add0(src, ""); - - // Generate hashCode() method. - add1(src, "/** {@inheritDoc} */"); - add1(src, "@Override public int hashCode() {"); - - List<String> hash = new ArrayList<>(fields.size() * 2); - - boolean first = true; - boolean tempVar = false; - - for (PojoField field : fields) { - String javaName = field.javaName(); - - if (!first) - add0(hash, ""); - - if (field.primitive()) { - switch (field.javaTypeName()) { - case "boolean": - add2Fmt(hash, first ? "int res = %s ? 1 : 0;" : "res = 31 * res + (%s ? 1 : 0);", javaName); - break; - - case "byte": - case "short": - add2Fmt(hash, first ? "int res = (int)%s;" : "res = 31 * res + (int)%s;", javaName); - break; - - case "int": - add2Fmt(hash, first ? "int res = %s;" : "res = 31 * res + %s;", javaName); - break; - - case "long": - add2Fmt(hash, first - ? "int res = (int)(%1$s ^ (%1$s >>> 32));" - : "res = 31 * res + (int)(%1$s ^ (%1$s >>> 32));", javaName); - break; - - case "float": - add2Fmt(hash, first - ? "int res = %1$s != +0.0f ? Float.floatToIntBits(%1$s) : 0;" - : "res = 31 * res + (%1$s != +0.0f ? Float.floatToIntBits(%1$s) : 0);", javaName); - break; - - case "double": - add2Fmt(hash, (tempVar ? "ig_hash_temp" : "long ig_hash_temp") + - " = Double.doubleToLongBits(%s);", javaName); - - add0(hash, ""); - - add2Fmt(hash, first - ? "int res = (int)(ig_hash_temp ^ (ig_hash_temp >>> 32));" - : "res = 31 * res + (int)(ig_hash_temp ^ (ig_hash_temp >>> 32));", javaName); - - tempVar = true; - break; - } - } - else - add2Fmt(hash, first ? "int res = %1$s != null ? %1$s.hashCode() : 0;" - : "res = 31 * res + (%1$s != null ? %1$s.hashCode() : 0);", javaName); - - first = false; - } - - for (String line : hash) - add0(src, line); - - add0(src, ""); - add2(src, "return res;"); - add1(src, "}"); - add0(src, ""); - - // Generate toString() method. - add1(src, "/** {@inheritDoc} */"); - add1(src, "@Override public String toString() {"); - - Iterator<PojoField> it = fields.iterator(); - - add2Fmt(src, "return \"%1$s [%2$s=\" + %2$s +", type, it.next().javaName()); - - while (it.hasNext()) - add3(src, String.format("\", %1$s=\" + %1$s +", it.next().javaName())); - - add3(src, "\"]\";"); - add1(src, "}"); - - add0(src, "}"); - add0(src, ""); - - // Write generated code to file. - try (Writer writer = new BufferedWriter(new FileWriter(out))) { - for (String line : src) - writer.write(line + '\n'); - } - } - - /** - * Generate source code for type by its metadata. - * - * @param pojo POJO descriptor. - * @param outFolder Output folder. - * @param pkg Types package. - * @param constructor {@code true} if empty and full constructors should be generated. - * @param includeKeys {@code true} if key fields should be included into value class. - * @param askOverwrite Callback to ask user to confirm file overwrite. - * @throws IOException If failed to write generated code into file. - */ - public static void generate(PojoDescriptor pojo, String outFolder, String pkg, boolean constructor, - boolean includeKeys, ConfirmCallable askOverwrite) throws IOException { - File pkgFolder = new File(outFolder, pkg.replace('.', File.separatorChar)); - - if (!pkgFolder.exists() && !pkgFolder.mkdirs()) - throw new IOException("Failed to create folders for package: " + pkg); - - generateCode(pojo, true, pkg, pkgFolder, constructor, false, askOverwrite); - - generateCode(pojo, false, pkg, pkgFolder, constructor, includeKeys, askOverwrite); - } -}
http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/SnippetGenerator.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/SnippetGenerator.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/SnippetGenerator.java deleted file mode 100644 index 4abd5a6..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/SnippetGenerator.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.generator; - -import org.apache.ignite.schema.model.*; -import org.apache.ignite.schema.ui.*; - -import java.io.*; -import java.util.*; - -import static org.apache.ignite.schema.ui.MessageBox.Result.*; - -/** - * Cache configuration snippet generator. - */ -public class SnippetGenerator { - /** - * Add type fields. - * - * @param src Source code lines. - * @param owner Fields owner collection. - * @param fields Fields metadata. - */ - private static void addFields(Collection<String> src, String owner, Collection<PojoField> fields) { - for (PojoField field : fields) { - String javaTypeName = field.javaTypeName(); - - if (javaTypeName.startsWith("java.lang.")) - javaTypeName = javaTypeName.substring(10); - - src.add(owner + ".add(new CacheTypeFieldMetadata(\"" + field.dbName() + "\", " + - "java.sql.Types." + field.dbTypeName() + ",\"" + - field.javaName() + "\", " + javaTypeName + ".class));"); - } - } - - /** - * Generate java snippet for cache configuration with JDBC store. - * - * @param pojos POJO descriptors. - * @param pkg Types package. - * @param includeKeys {@code true} if key fields should be included into value class. - * @param out File to output snippet. - * @param askOverwrite Callback to ask user to confirm file overwrite. - * @throws IOException If generation failed. - */ - public static void generate(Collection<PojoDescriptor> pojos, String pkg, boolean includeKeys, File out, - ConfirmCallable askOverwrite) throws IOException { - if (out.exists()) { - MessageBox.Result choice = askOverwrite.confirm(out.getName()); - - if (CANCEL == choice) - throw new IllegalStateException("Java configuration snippet generation was canceled!"); - - if (NO == choice || NO_TO_ALL == choice) - return; - } - - Collection<String> src = new ArrayList<>(256); - - src.add("// Code snippet for cache configuration."); - src.add(""); - src.add("IgniteConfiguration cfg = new IgniteConfiguration();"); - src.add(""); - src.add("CacheConfiguration ccfg = new CacheConfiguration<>();"); - src.add(""); - src.add("DataSource dataSource = null; // TODO: Create data source for your database."); - src.add(""); - src.add("// Create store. "); - src.add("CacheJdbcPojoStore store = new CacheJdbcPojoStore();"); - src.add("store.setDataSource(dataSource);"); - src.add(""); - src.add("// Create store factory. "); - src.add("ccfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory<>(store));"); - src.add(""); - src.add("// Configure cache to use store. "); - src.add("ccfg.setReadThrough(true);"); - src.add("ccfg.setWriteThrough(true);"); - src.add(""); - src.add("cfg.setCacheConfiguration(ccfg);"); - src.add(""); - src.add("// Configure cache types. "); - src.add("Collection<CacheTypeMetadata> meta = new ArrayList<>();"); - src.add(""); - - boolean first = true; - - for (PojoDescriptor pojo : pojos) { - String tbl = pojo.table(); - - src.add("// " + tbl + "."); - src.add((first ? "CacheTypeMetadata " : "") + "type = new CacheTypeMetadata();"); - src.add("type.setDatabaseSchema(\"" + pojo.schema() + "\");"); - src.add("type.setDatabaseTable(\"" + tbl + "\");"); - src.add("type.setKeyType(\"" + pkg + "." + pojo.keyClassName() + "\");"); - src.add("type.setValueType(\"" + pkg + "." + pojo.valueClassName() + "\");"); - src.add(""); - - src.add("// Key fields for " + tbl + "."); - src.add((first ? "Collection<CacheTypeFieldMetadata> " : "") + "keys = new ArrayList<>();"); - addFields(src, "keys", pojo.keyFields()); - src.add("type.setKeyFields(keys);"); - src.add(""); - - src.add("// Value fields for " + tbl + "."); - src.add((first ? "Collection<CacheTypeFieldMetadata> " : "") + "vals = new ArrayList<>();"); - addFields(src, "vals", pojo.valueFields(includeKeys)); - src.add("type.setValueFields(vals);"); - src.add(""); - - first = false; - } - - src.add("// Start Ignite node."); - src.add("Ignition.start(cfg);"); - - // Write generated code to file. - try (Writer writer = new BufferedWriter(new FileWriter(out))) { - for (String line : src) - writer.write(line + '\n'); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/XmlGenerator.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/XmlGenerator.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/XmlGenerator.java deleted file mode 100644 index c62a720..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/generator/XmlGenerator.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.generator; - -import org.apache.ignite.cache.*; -import org.apache.ignite.lang.*; -import org.apache.ignite.schema.model.*; -import org.apache.ignite.schema.ui.*; -import org.w3c.dom.*; - -import javax.xml.parsers.*; -import javax.xml.transform.*; -import javax.xml.transform.dom.*; -import javax.xml.transform.stream.*; -import java.io.*; -import java.nio.file.*; -import java.text.*; -import java.util.*; - -import static org.apache.ignite.schema.ui.MessageBox.Result.*; - -/** - * Generator of XML files for type metadata. - */ -public class XmlGenerator { - /** - * Add comment with license and generation date. - * - * @param doc XML document. - */ - private static void addComment(Document doc) { - doc.appendChild(doc.createComment("\n" + - " Licensed to the Apache Software Foundation (ASF) under one or more\n" + - " contributor license agreements. See the NOTICE file distributed with\n" + - " this work for additional information regarding copyright ownership.\n" + - " The ASF licenses this file to You under the Apache License, Version 2.0\n" + - " (the \"License\"); you may not use this file except in compliance with\n" + - " the License. You may obtain a copy of the License at\n\n" + - " http://www.apache.org/licenses/LICENSE-2.0\n\n" + - " Unless required by applicable law or agreed to in writing, software\n" + - " distributed under the License is distributed on an \"AS IS\" BASIS,\n" + - " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + - " See the License for the specific language governing permissions and\n" + - " limitations under the License.\n")); - - doc.appendChild(doc.createComment("\n XML generated by Apache Ignite Schema Load utility: " + - new SimpleDateFormat("MM/dd/yyyy").format(new Date()) + "\n")); - } - - /** - * Add bean to XML document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param clazz Bean class. - */ - private static Element addBean(Document doc, Node parent, Class<?> clazz) { - Element elem = doc.createElement("bean"); - - elem.setAttribute("class", clazz.getName()); - - parent.appendChild(elem); - - return elem; - } - - /** - * Add element to XML document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param tagName XML tag name. - * @param attr1 Name for first attr. - * @param val1 Value for first attribute. - * @param attr2 Name for second attr. - * @param val2 Value for second attribute. - */ - private static Element addElement(Document doc, Node parent, String tagName, - String attr1, String val1, String attr2, String val2) { - Element elem = doc.createElement(tagName); - - if (attr1 != null) - elem.setAttribute(attr1, val1); - - if (attr2 != null) - elem.setAttribute(attr2, val2); - - parent.appendChild(elem); - - return elem; - } - - /** - * Add element to XML document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param tagName XML tag name. - */ - private static Element addElement(Document doc, Node parent, String tagName) { - return addElement(doc, parent, tagName, null, null, null, null); - } - - /** - * Add element to XML document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param tagName XML tag name. - */ - private static Element addElement(Document doc, Node parent, String tagName, String attrName, String attrVal) { - return addElement(doc, parent, tagName, attrName, attrVal, null, null); - } - - /** - * Add "property" element to XML document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param name Value for "name" attribute - * @param val Value for "value" attribute - */ - private static Element addProperty(Document doc, Node parent, String name, String val) { - String valAttr = val != null ? "value" : null; - - return addElement(doc, parent, "property", "name", name, valAttr, val); - } - - /** - * Add type descriptors to XML document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param name Property name. - * @param fields Collection of POJO fields. - */ - private static void addFields(Document doc, Node parent, String name, Collection<PojoField> fields) { - if (!fields.isEmpty()) { - Element prop = addProperty(doc, parent, name, null); - - Element list = addElement(doc, prop, "list"); - - for (PojoField field : fields) { - Element item = addBean(doc, list, CacheTypeFieldMetadata.class); - - addProperty(doc, item, "databaseName", field.dbName()); - Element dbType = addProperty(doc, item, "databaseType", null); - addElement(doc, dbType, "util:constant", "static-field", "java.sql.Types." + field.dbTypeName()); - addProperty(doc, item, "javaName", field.javaName()); - addProperty(doc, item, "javaType", field.javaTypeName()); - } - } - } - - /** - * Add query fields to xml document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param name Property name. - * @param fields Map with fields. - */ - private static void addQueryFields(Document doc, Node parent, String name, Collection<PojoField> fields) { - if (!fields.isEmpty()) { - Element prop = addProperty(doc, parent, name, null); - - Element map = addElement(doc, prop, "map"); - - for (PojoField field : fields) - addElement(doc, map, "entry", "key", field.javaName(), "value", field.javaTypeName()); - } - } - - /** - * Add indexes to xml document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param groups Map with indexes. - */ - private static void addQueryGroups(Document doc, Node parent, - Map<String, Map<String, IgniteBiTuple<String, Boolean>>> groups) { - if (!groups.isEmpty()) { - Element prop = addProperty(doc, parent, "groups", null); - - Element map = addElement(doc, prop, "map"); - - for (Map.Entry<String, Map<String, IgniteBiTuple<String, Boolean>>> group : groups.entrySet()) { - Element entry1 = addElement(doc, map, "entry", "key", group.getKey()); - - Element val1 = addElement(doc, entry1, "map"); - - Map<String, IgniteBiTuple<String, Boolean>> fields = group.getValue(); - - for (Map.Entry<String, IgniteBiTuple<String, Boolean>> field : fields.entrySet()) { - Element entry2 = addElement(doc, val1, "entry", "key", field.getKey()); - - Element val2 = addBean(doc, entry2, IgniteBiTuple.class); - - IgniteBiTuple<String, Boolean> idx = field.getValue(); - - addElement(doc, val2, "constructor-arg", null, null, "value", idx.get1()); - addElement(doc, val2, "constructor-arg", null, null, "value", String.valueOf(idx.get2())); - } - } - } - } - - /** - * Add element with type metadata to XML document. - * - * @param doc XML document. - * @param parent Parent XML node. - * @param pkg Package fo types. - * @param pojo POJO descriptor. - */ - private static void addTypeMetadata(Document doc, Node parent, String pkg, PojoDescriptor pojo, - boolean includeKeys) { - Element bean = addBean(doc, parent, CacheTypeMetadata.class); - - addProperty(doc, bean, "databaseSchema", pojo.schema()); - - addProperty(doc, bean, "databaseTable", pojo.table()); - - addProperty(doc, bean, "keyType", pkg + "." + pojo.keyClassName()); - - addProperty(doc, bean, "valueType", pkg + "." + pojo.valueClassName()); - - addFields(doc, bean, "keyFields", pojo.keyFields()); - - addFields(doc, bean, "valueFields", pojo.valueFields(includeKeys)); - - addQueryFields(doc, bean, "queryFields", pojo.fields()); - - addQueryFields(doc, bean, "ascendingFields", pojo.ascendingFields()); - - addQueryFields(doc, bean, "descendingFields", pojo.descendingFields()); - - addQueryGroups(doc, bean, pojo.groups()); - } - - /** - * Transform metadata into xml. - * - * @param pkg Package fo types. - * @param pojo POJO descriptor. - * @param out File to output result. - * @param askOverwrite Callback to ask user to confirm file overwrite. - */ - public static void generate(String pkg, PojoDescriptor pojo, boolean includeKeys, File out, - ConfirmCallable askOverwrite) { - generate(pkg, Collections.singleton(pojo), includeKeys, out, askOverwrite); - } - - /** - * Transform metadata into xml. - * - * @param pkg Package fo types. - * @param pojos POJO descriptors. - * @param out File to output result. - * @param askOverwrite Callback to ask user to confirm file overwrite. - */ - public static void generate(String pkg, Collection<PojoDescriptor> pojos, boolean includeKeys, File out, - ConfirmCallable askOverwrite) { - - File outFolder = out.getParentFile(); - - if (outFolder == null) - throw new IllegalStateException("Invalid output file: " + out); - - if (!outFolder.exists() && !outFolder.mkdirs()) - throw new IllegalStateException("Failed to create output folder for XML file: " + outFolder); - - try { - if (out.exists()) { - MessageBox.Result choice = askOverwrite.confirm(out.getName()); - - if (CANCEL == choice) - throw new IllegalStateException("XML generation was canceled!"); - - if (NO == choice || NO_TO_ALL == choice) - return; - } - - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - - Document doc = docBuilder.newDocument(); - doc.setXmlStandalone(true); - - addComment(doc); - - Element beans = addElement(doc, doc, "beans"); - beans.setAttribute("xmlns", "http://www.springframework.org/schema/beans"); - beans.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); - beans.setAttribute("xmlns:util", "http://www.springframework.org/schema/util"); - beans.setAttribute("xsi:schemaLocation", - "http://www.springframework.org/schema/beans " + - "http://www.springframework.org/schema/beans/spring-beans.xsd " + - "http://www.springframework.org/schema/util " + - "http://www.springframework.org/schema/util/spring-util.xsd"); - - for (PojoDescriptor pojo : pojos) - addTypeMetadata(doc, beans, pkg, pojo, includeKeys); - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - - Transformer transformer = transformerFactory.newTransformer(); - - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(65536); - - transformer.transform(new DOMSource(doc), new StreamResult(baos)); - - // Custom pretty-print of generated XML. - Files.write(out.toPath(), baos.toString() - .replaceAll("><", ">\n<") - .replaceFirst("<!--", "\n<!--") - .replaceFirst("-->", "-->\n") - .replaceAll("\" xmlns", "\"\n xmlns") - .replaceAll("\" xsi", "\"\n xsi") - .replaceAll(" http://www.springframework", "\n http://www.springframework") - .getBytes()); - } - catch (ParserConfigurationException | TransformerException | IOException e) { - throw new IllegalStateException(e); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoDescriptor.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoDescriptor.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoDescriptor.java deleted file mode 100644 index 9f3322b..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoDescriptor.java +++ /dev/null @@ -1,510 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.model; - -import javafx.beans.property.*; -import javafx.beans.value.*; -import javafx.collections.*; -import org.apache.ignite.lang.*; -import org.apache.ignite.schema.parser.*; - -import java.math.*; -import java.util.*; - -import static java.sql.Types.*; - -/** - * Descriptor for java type. - */ -public class PojoDescriptor { - /** Database table. */ - private final DbTable tbl; - - /** Selected property. */ - private final BooleanProperty useProp; - - /** Previous name for key class. */ - private final String keyClsNamePrev; - - /** Key class name to show on screen. */ - private final StringProperty keyClsNameProp; - - /** Previous name for value class. */ - private final String valClsNamePrev; - - /** Value class name to show on screen. */ - private final StringProperty valClsNameProp; - - /** Parent item (schema name). */ - private final PojoDescriptor parent; - - /** Children items (tables names). */ - private Collection<PojoDescriptor> children = Collections.emptyList(); - - /** Indeterminate state of parent. */ - private final BooleanProperty indeterminateProp = new SimpleBooleanProperty(false); - - /** Full database name: schema + table. */ - private final String fullDbName; - - /** Java class fields. */ - private final ObservableList<PojoField> fields; - - /** Fields map for quick access. */ - private final Map<String, PojoField> fieldsMap; - - /** - * Constructor of POJO descriptor. - * - * @param prn Parent descriptor. - * @param tbl Database table Tab;e. - */ - public PojoDescriptor(PojoDescriptor prn, DbTable tbl) { - parent = prn; - - this.tbl = tbl; - - fullDbName = tbl.schema() + "." + tbl.table(); - - valClsNamePrev = toJavaClassName(tbl.table()); - valClsNameProp = new SimpleStringProperty(valClsNamePrev); - - keyClsNamePrev = valClsNamePrev.isEmpty() ? "" : valClsNamePrev + "Key"; - keyClsNameProp = new SimpleStringProperty(keyClsNamePrev); - - Collection<DbColumn> cols = tbl.columns(); - - List<PojoField> flds = new ArrayList<>(cols.size()); - - fieldsMap = new HashMap<>(cols.size()); - - for (DbColumn col : cols) { - String colName = col.name(); - - PojoField fld = new PojoField(colName, col.type(), - toJavaFieldName(colName), toJavaType(col.type(), col.nullable()).getName(), - col.key(), col.nullable()); - - fld.owner(this); - - flds.add(fld); - - fieldsMap.put(colName, fld); - } - - fields = FXCollections.observableList(flds); - - boolean isTbl = parent != null; - - boolean hasKeys = !isTbl || !keyFields().isEmpty(); - - useProp = new SimpleBooleanProperty(hasKeys); - - if (isTbl && !hasKeys && !parent.indeterminateProp.get()) - parent.indeterminateProp.set(true); - - useProp.addListener(new ChangeListener<Boolean>() { - @Override public void changed(ObservableValue<? extends Boolean> val, Boolean oldVal, Boolean newVal) { - for (PojoDescriptor child : children) - child.useProp.set(newVal); - - if (parent != null && !parent.children.isEmpty()) { - Iterator<PojoDescriptor> it = parent.children.iterator(); - - boolean parentIndeterminate = false; - boolean first = it.next().useProp.get(); - - while (it.hasNext()) { - if (it.next().useProp.get() != first) { - parentIndeterminate = true; - - break; - } - } - - parent.indeterminateProp.set(parentIndeterminate); - - if (!parentIndeterminate) - parent.useProp.set(first); - } - } - }); - } - - /** - * @return Parent descriptor. - */ - public PojoDescriptor parent() { - return parent; - } - - /** - * @return Full database name: schema + table. - */ - public String fullDbName() { - return fullDbName; - } - - /** - * @return {@code true} if POJO descriptor is a table descriptor and checked in GUI. - */ - public boolean checked() { - return parent != null && useProp.get(); - } - - /** - * @return Boolean property support for {@code use} property. - */ - public BooleanProperty useProperty() { - return useProp; - } - - /** - * @return Boolean property support for parent {@code indeterminate} property. - */ - public BooleanProperty indeterminate() { - return indeterminateProp; - } - - /** - * @return Key class name. - */ - public String keyClassName() { - return keyClsNameProp.get(); - } - - /** - * @param name New key class name. - */ - public void keyClassName(String name) { - keyClsNameProp.set(name); - } - - /** - * @return Value class name. - */ - public String valueClassName() { - return valClsNameProp.get(); - } - - /** - * @param name New value class name. - */ - public void valueClassName(String name) { - valClsNameProp.set(name); - } - - /** - * @return {@code true} if at least one field checked as "used". - */ - public boolean hasFields() { - for (PojoField field : fields) - if (field.use()) - return true; - - return false; - } - - /** - * @return {@code true} if at least one field checked as "used" and checked as "key". - */ - public boolean hasKeyFields() { - for (PojoField field : fields) - if (field.use() && field.key()) - return true; - - return false; - } - - /** - * @param includeKeys {@code true} if key fields should be included into value class. - * @return {@code true} if at least one field checked as "used" and not checked as "key". - */ - public boolean hasValueFields(boolean includeKeys) { - if (includeKeys) - return hasKeyFields(); - - for (PojoField field : fields) - if (field.use() && !field.key()) - return true; - - return false; - } - - /** - * @return Collection of key fields. - */ - public Collection<PojoField> keyFields() { - Collection<PojoField> keys = new ArrayList<>(); - - for (PojoField field : fields) - if (field.use() && field.key() ) - keys.add(field); - - return keys; - } - - /** - * @param includeKeys {@code true} if key fields should be included into value class. - * @return Collection of value fields. - */ - public Collection<PojoField> valueFields(boolean includeKeys) { - Collection<PojoField> vals = new ArrayList<>(); - - for (PojoField field : fields) - if (field.use() && (includeKeys || !field.key())) - vals.add(field); - - return vals; - } - - /** - * @return Ascending fields. - */ - public Collection<PojoField> ascendingFields() { - Collection<PojoField> res = new ArrayList<>(); - - Set<String> asc = tbl.ascendingColumns(); - - for (PojoField field : fields) - if (field.use() && asc.contains(field.dbName())) - res.add(field); - - return res; - } - - /** - * @return Descending fields. - */ - public Collection<PojoField> descendingFields() { - Collection<PojoField> res = new ArrayList<>(); - - Set<String> desc = tbl.descendingColumns(); - - for (PojoField field : fields) - if (field.use() && desc.contains(field.dbName())) - res.add(field); - - return res; - } - - /** - * Gets indexes groups. - */ - public Map<String, Map<String, IgniteBiTuple<String, Boolean>>> groups() { - Map<String, Map<String, Boolean>> idxs = tbl.indexes(); - - Map<String, Map<String, IgniteBiTuple<String, Boolean>>> groups = new LinkedHashMap<>(idxs.size()); - - for (Map.Entry<String, Map<String, Boolean>> idx : idxs.entrySet()) { - String idxName = idx.getKey(); - - Map<String, Boolean> idxCols = idx.getValue(); - - Map<String, IgniteBiTuple<String, Boolean>> grp = new LinkedHashMap<>(); - - groups.put(idxName, grp); - - for (Map.Entry<String, Boolean> idxCol : idxCols.entrySet()) { - PojoField fld = fieldsMap.get(idxCol.getKey()); - - grp.put(fld.javaName(), new IgniteBiTuple<>(fld.javaTypeName(), idxCol.getValue())); - } - } - - return groups; - } - - /** - * @return Key class name property. - */ - public StringProperty keyClassNameProperty() { - return keyClsNameProp; - } - - /** - * @return Value class name property. - */ - public StringProperty valueClassNameProperty() { - return valClsNameProp; - } - - /** - * @return Schema name. - */ - public String schema() { - return tbl.schema(); - } - - /** - * @return Table name. - */ - public String table() { - return tbl.table(); - } - - /** - * Sets children items. - * - * @param children Items to set. - */ - public void children(Collection<PojoDescriptor> children) { - this.children = children; - } - - /** - * @return {@code true} if descriptor was changed by user via GUI. - */ - public boolean changed() { - if (!keyClsNameProp.get().equals(keyClsNamePrev) || !valClsNameProp.get().equals(valClsNamePrev)) - return true; - - for (PojoField field : fields) - if (field.changed()) - return true; - - return false; - } - - /** - * Revert changes to key class name made by user. - */ - public void revertKeyClassName() { - keyClsNameProp.set(keyClsNamePrev); - } - - /** - * Revert changes to value class name made by user. - */ - public void revertValueClassName() { - valClsNameProp.set(valClsNamePrev); - } - - /** - * Revert changes to java names made by user. - */ - public void revertJavaNames() { - for (PojoField field : fields) - field.resetJavaName(); - } - - /** - * @return Java class fields. - */ - public ObservableList<PojoField> fields() { - return fields; - } - - /** - * @param name Source name. - * @return String converted to java class name notation. - */ - private static String toJavaClassName(String name) { - int len = name.length(); - - StringBuilder buf = new StringBuilder(len); - - boolean capitalizeNext = true; - - for (int i = 0; i < len; i++) { - char ch = name.charAt(i); - - if (Character.isWhitespace(ch) || '_' == ch) - capitalizeNext = true; - else if (capitalizeNext) { - buf.append(Character.toUpperCase(ch)); - - capitalizeNext = false; - } - else - buf.append(Character.toLowerCase(ch)); - } - - return buf.toString(); - } - - /** - * @param name Source name. - * @return String converted to java field name notation. - */ - private static String toJavaFieldName(String name) { - String javaName = toJavaClassName(name); - - return Character.toLowerCase(javaName.charAt(0)) + javaName.substring(1); - } - - /** - * Convert JDBC data type to java type. - * - * @param type JDBC SQL data type. - * @param nullable {@code true} if {@code NULL} is allowed for this field in database. - * @return Java data type. - */ - private static Class<?> toJavaType(int type, boolean nullable) { - switch (type) { - case BIT: - case BOOLEAN: - return nullable ? Boolean.class : boolean.class; - - case TINYINT: - return nullable ? Byte.class : byte.class; - - case SMALLINT: - return nullable ? Short.class : short.class; - - case INTEGER: - return nullable ? Integer.class : int.class; - - case BIGINT: - return nullable ? Long.class : long.class; - - case REAL: - return nullable ? Float.class : float.class; - - case FLOAT: - case DOUBLE: - return nullable ? Double.class : double.class; - - case NUMERIC: - case DECIMAL: - return BigDecimal.class; - - case CHAR: - case VARCHAR: - case LONGVARCHAR: - case NCHAR: - case NVARCHAR: - case LONGNVARCHAR: - return String.class; - - case DATE: - return java.sql.Date.class; - - case TIME: - return java.sql.Time.class; - - case TIMESTAMP: - return java.sql.Timestamp.class; - - // BINARY, VARBINARY, LONGVARBINARY, ARRAY, BLOB, CLOB, NCLOB, NULL, DATALINK - // OTHER, JAVA_OBJECT, DISTINCT, STRUCT, REF, ROWID, SQLXML - default: - return Object.class; - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoField.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoField.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoField.java deleted file mode 100644 index 10939d9..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/model/PojoField.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.model; - -import javafx.beans.property.*; -import javafx.beans.value.*; -import javafx.collections.*; - -import java.math.*; -import java.util.*; - -import static java.sql.Types.*; - -/** - * Field descriptor with properties for JavaFX GUI bindings. - */ -public class PojoField { - /** If this field should be used for code generation. */ - private final BooleanProperty useProp; - - /** If this field belongs to primary key. */ - private final BooleanProperty keyProp; - - /** If this field is an affinity key. */ - private final BooleanProperty akProp; - - /** If this field initially belongs to primary key. */ - private final boolean keyPrev; - - /** Field name in database. */ - private final StringProperty dbNameProp; - - /** Field type in database. */ - private final StringProperty dbTypeNameProp; - - /** Field name in POJO. */ - private final StringProperty javaNameProp; - - /** Initial field name in POJO. */ - private final String javaNamePrev; - - /** Field type in POJO. */ - private final StringProperty javaTypeNameProp; - - /** Initial field type in POJO. */ - private final String javaTypeNamePrev; - - /** Is {@code NULL} allowed for field in database. */ - private final boolean nullable; - - /** List of possible java type conversions. */ - private final ObservableList<String> conversions; - - /** Field owner. */ - private PojoDescriptor owner; - - /** - * @param clss List of classes to get class names. - * @return List of classes names to show in UI for manual select. - */ - private static List<String> classNames(Class<?>... clss) { - List<String> names = new ArrayList<>(clss.length); - - for (Class<?> cls : clss) - names.add(cls.getName()); - - return names; - } - - /** Null number conversions. */ - private static final ObservableList<String> NULL_NUM_CONVERSIONS = FXCollections.observableArrayList(); - - /** Not null number conversions. */ - private static final ObservableList<String> NOT_NULL_NUM_CONVERSIONS = FXCollections.observableArrayList(); - - /** Primitive types. */ - private static final List<String> PRIMITIVES = classNames(boolean.class, byte.class, short.class, - int.class, long.class, float.class, double.class); - - /** Object types. */ - private static final List<String> OBJECTS = classNames(Boolean.class, Byte.class, Short.class, Integer.class, - Long.class, Float.class, Double.class, BigDecimal.class); - - static { - NOT_NULL_NUM_CONVERSIONS.addAll(PRIMITIVES); - NOT_NULL_NUM_CONVERSIONS.addAll(OBJECTS); - - NULL_NUM_CONVERSIONS.addAll(OBJECTS); - } - - /** - * @param dbType Database type. - * @param nullable Nullable. - * @param dflt Default. - * @return List of possible type conversions. - */ - private static ObservableList<String> conversions(int dbType, boolean nullable, String dflt) { - switch (dbType) { - case TINYINT: - case SMALLINT: - case INTEGER: - case BIGINT: - case REAL: - case FLOAT: - case DOUBLE: - return nullable ? NULL_NUM_CONVERSIONS : NOT_NULL_NUM_CONVERSIONS; - - default: - return FXCollections.singletonObservableList(dflt); - } - } - - /** - * @param dbName Field name in database. - * @param dbType Field JDBC type in database. - * @param javaName Field name in POJO. - * @param javaTypeName Field type in POJO. - * @param key {@code true} if this field belongs to primary key. - * @param nullable {@code true} if {@code NULL} allowed for field in database. - */ - public PojoField(String dbName, int dbType, String javaName, String javaTypeName, boolean key, boolean nullable) { - dbNameProp = new SimpleStringProperty(dbName); - - dbTypeNameProp = new SimpleStringProperty(jdbcTypeName(dbType)); - - javaNamePrev = javaName; - - javaNameProp = new SimpleStringProperty(javaNamePrev); - - javaTypeNamePrev = javaTypeName; - - javaTypeNameProp = new SimpleStringProperty(javaTypeNamePrev); - - useProp = new SimpleBooleanProperty(true); - - keyPrev = key; - - keyProp = new SimpleBooleanProperty(keyPrev); - - this.nullable = nullable; - - akProp = new SimpleBooleanProperty(false); - - conversions = conversions(dbType, nullable, javaNamePrev); - - keyProp.addListener(new ChangeListener<Boolean>() { - @Override public void changed(ObservableValue<? extends Boolean> val, Boolean oldVal, Boolean newVal) { - if (newVal) { - if (!use()) - useProp.set(true); - } - else - akProp.set(false); - } - }); - - akProp.addListener(new ChangeListener<Boolean>() { - @Override public void changed(ObservableValue<? extends Boolean> val, Boolean oldVal, Boolean newVal) { - if (newVal && owner != null) { - keyProperty().set(true); - - for (PojoField field : owner.fields()) - if (field != PojoField.this && field.affinityKey()) - field.akProp.set(false); - } - } - }); - } - - /** - * @param jdbcType String name for JDBC type. - */ - private static String jdbcTypeName(int jdbcType) { - switch (jdbcType) { - case BIT: - return "BIT"; - case TINYINT: - return "TINYINT"; - case SMALLINT: - return "SMALLINT"; - case INTEGER: - return "INTEGER"; - case BIGINT: - return "BIGINT"; - case FLOAT: - return "FLOAT"; - case REAL: - return "REAL"; - case DOUBLE: - return "DOUBLE"; - case NUMERIC: - return "NUMERIC"; - case DECIMAL: - return "DECIMAL"; - case CHAR: - return "CHAR"; - case VARCHAR: - return "VARCHAR"; - case LONGVARCHAR: - return "LONGVARCHAR"; - case DATE: - return "DATE"; - case TIME: - return "TIME"; - case TIMESTAMP: - return "TIMESTAMP"; - case BINARY: - return "BINARY"; - case VARBINARY: - return "VARBINARY"; - case LONGVARBINARY: - return "LONGVARBINARY"; - case NULL: - return "NULL"; - case OTHER: - return "OTHER"; - case JAVA_OBJECT: - return "JAVA_OBJECT"; - case DISTINCT: - return "DISTINCT"; - case STRUCT: - return "STRUCT"; - case ARRAY: - return "ARRAY"; - case BLOB: - return "BLOB"; - case CLOB: - return "CLOB"; - case REF: - return "REF"; - case DATALINK: - return "DATALINK"; - case BOOLEAN: - return "BOOLEAN"; - case ROWID: - return "ROWID"; - case NCHAR: - return "NCHAR"; - case NVARCHAR: - return "NVARCHAR"; - case LONGNVARCHAR: - return "LONGNVARCHAR"; - case NCLOB: - return "NCLOB"; - case SQLXML: - return "SQLXML"; - default: - return "Unknown"; - } - } - - /** - * Revert changes to java names made by user. - */ - public void resetJavaName() { - javaNameProp.set(javaNamePrev); - } - - /** - * @param owner New field owner. - */ - public void owner(PojoDescriptor owner) { - this.owner = owner; - } - - /** - * @return {@code true} if filed should be used for code generation. - */ - public boolean use() { - return useProp.get(); - } - - /** - * @return {@code true} if this field belongs to primary key. - */ - public boolean key() { - return keyProp.get(); - } - - /** - * @param pk {@code true} if this field belongs to primary key. - */ - public void key(boolean pk) { - keyProp.set(pk); - } - - /** - * @return {@code true} if this field is an affinity key. - */ - public boolean affinityKey() { - return akProp.get(); - } - - /** - * @return POJO field java name. - */ - public String javaName() { - return javaNameProp.get(); - } - - /** - * @param name New POJO field java name. - */ - public void javaName(String name) { - javaNameProp.set(name); - } - - /** - * @return POJO field java type name. - */ - public String javaTypeName() { - return javaTypeNameProp.get(); - } - - /** - * @return Field name in database. - */ - public String dbName() { - return dbNameProp.get(); - } - - /** - * @return POJO field JDBC type name in database. - */ - public String dbTypeName() { - return dbTypeNameProp.get(); - } - - /** - * @return Is NULL allowed for field in database. - */ - public boolean nullable() { - return nullable; - } - - /** - * @return List of possible java type conversions. - */ - public ObservableList<String> conversions() { - return conversions; - } - - /** - * @return {@code true} if type of field is primitive type. - */ - public boolean primitive() { - return PRIMITIVES.contains(javaTypeName()); - } - - /** - * @return {@code true} if field was changed by user. - */ - public boolean changed() { - return keyPrev != key() || !javaNamePrev.equals(javaName()) || !javaTypeNamePrev.equals(javaTypeName()); - } - - /** - * @return Boolean property support for {@code use} property. - */ - public BooleanProperty useProperty() { - return useProp; - } - - /** - * @return Boolean property support for {@code key} property. - */ - public BooleanProperty keyProperty() { - return keyProp; - } - - /** - * @return Boolean property support for {@code affinityKey} property. - */ - public BooleanProperty affinityKeyProperty() { - return akProp; - } - - /** - * @return String property support for {@code javaName} property. - */ - public StringProperty javaNameProperty() { - return javaNameProp; - } - - /** - * @return String property support for {@code javaTypeName} property. - */ - public StringProperty javaTypeNameProperty() { - return javaTypeNameProp; - } - - /** - * @return String property support for {@code dbName} property. - */ - public StringProperty dbNameProperty() { - return dbNameProp; - } - - /** - * @return String property support for {@code dbName} property. - */ - public StringProperty dbTypeNameProperty() { - return dbTypeNameProp; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DatabaseMetadataParser.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DatabaseMetadataParser.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DatabaseMetadataParser.java deleted file mode 100644 index 696ca62..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DatabaseMetadataParser.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.parser; - -import javafx.collections.*; -import org.apache.ignite.schema.model.*; -import org.apache.ignite.schema.parser.dialect.*; - -import java.sql.*; -import java.util.*; -import java.util.logging.*; - -/** - * Database metadata parser. - */ -public class DatabaseMetadataParser { - /** Logger. */ - private static final Logger log = Logger.getLogger(DatabaseMetadataParser.class.getName()); - - /** - * Parse database metadata. - * - * @param conn Connection to database. - * @param tblsOnly If {@code true} then process tables only else process tables and views. - * @return Collection of POJO descriptors. - * @throws SQLException If parsing failed. - */ - public static ObservableList<PojoDescriptor> parse(Connection conn, boolean tblsOnly) throws SQLException { - DatabaseMetadataDialect dialect; - - try { - String dbProductName = conn.getMetaData().getDatabaseProductName(); - - if ("Oracle".equals(dbProductName)) - dialect = new OracleMetadataDialect(); - else if (dbProductName.startsWith("DB2/")) - dialect = new DB2MetadataDialect(); - else - dialect = new JdbcMetadataDialect(); - } - catch (SQLException e) { - log.log(Level.SEVERE, "Failed to resolve dialect (JdbcMetaDataDialect will be used.", e); - - dialect = new JdbcMetadataDialect(); - } - - Map<String, PojoDescriptor> parents = new HashMap<>(); - - Map<String, Collection<PojoDescriptor>> childrens = new HashMap<>(); - - for (DbTable tbl : dialect.tables(conn, tblsOnly)) { - String schema = tbl.schema(); - - PojoDescriptor parent = parents.get(schema); - Collection<PojoDescriptor> children = childrens.get(schema); - - if (parent == null) { - parent = new PojoDescriptor(null, new DbTable(schema, "", Collections.<DbColumn>emptyList(), - Collections.<String>emptySet(), Collections.<String>emptySet(), - Collections.<String, Map<String, Boolean>>emptyMap())); - - children = new ArrayList<>(); - - parents.put(schema, parent); - childrens.put(schema, children); - } - - children.add(new PojoDescriptor(parent, tbl)); - } - - List<PojoDescriptor> res = new ArrayList<>(); - - for (String schema : parents.keySet()) { - PojoDescriptor parent = parents.get(schema); - Collection<PojoDescriptor> children = childrens.get(schema); - - if (!children.isEmpty()) { - parent.children(children); - - res.add(parent); - res.addAll(children); - } - } - - Collections.sort(res, new Comparator<PojoDescriptor>() { - @Override public int compare(PojoDescriptor o1, PojoDescriptor o2) { - return o1.fullDbName().compareTo(o2.fullDbName()); - } - }); - - return FXCollections.observableList(res); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbColumn.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbColumn.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbColumn.java deleted file mode 100644 index 8b0c813..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbColumn.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.parser; - -/** - * Database table column. - */ -public class DbColumn { - /** Column name. */ - private final String name; - - /** Column JDBC type. */ - private final int type; - - /** Is this column belongs to primary key. */ - private final boolean key; - - /** Is {@code NULL} allowed for column in database. */ - private final boolean nullable; - - /** - * @param name Column name. - * @param type Column JDBC type. - * @param key {@code true} if this column belongs to primary key. - * @param nullable {@code true} if {@code NULL } allowed for column in database. - */ - public DbColumn(String name, int type, boolean key, boolean nullable) { - this.name = name; - this.type = type; - this.key = key; - this.nullable = nullable; - } - - /** - * @return Column name. - */ - public String name() { - return name; - } - - /** - * @return Column JDBC type. - */ - public int type() { - return type; - } - - /** - * @return {@code true} if this column belongs to primary key. - */ - public boolean key() { - return key; - } - - /** - * @return nullable {@code true} if {@code NULL } allowed for column in database. - */ - public boolean nullable() { - return nullable; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbTable.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbTable.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbTable.java deleted file mode 100644 index 35c7d91..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/DbTable.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.parser; - -import java.util.*; - -/** - * Database table. - */ -public class DbTable { - /** Schema name. */ - private final String schema; - - /** Table name. */ - private final String tbl; - - /** Columns. */ - private final Collection<DbColumn> cols; - - /** Columns in ascending order. */ - private final Set<String> ascCols; - - /** Columns in descending order. */ - private final Set<String> descCols; - - /** Indexes. */ - private final Map<String, Map<String, Boolean>> idxs; - - /** - * Default columns. - * - * @param schema Schema name. - * @param tbl Table name. - * @param cols Columns. - * @param ascCols Columns in ascending order. - * @param descCols Columns in descending order. - * @param idxs Indexes; - */ - public DbTable(String schema, String tbl, Collection<DbColumn> cols, Set<String> ascCols, Set<String> descCols, - Map<String, Map<String, Boolean>> idxs) { - this.schema = schema; - this.tbl = tbl; - this.cols = cols; - this.ascCols = ascCols; - this.descCols = descCols; - this.idxs = idxs; - } - - /** - * @return Schema name. - */ - public String schema() { - return schema; - } - - /** - * @return Table name. - */ - public String table() { - return tbl; - } - - /** - * @return Columns. - */ - public Collection<DbColumn> columns() { - return cols; - } - - /** - * @return Fields in ascending order - */ - public Set<String> ascendingColumns() { - return ascCols; - } - - /** - * @return Fields in descending order - */ - public Set<String> descendingColumns() { - return descCols; - } - - /** - * @return Indexes. - */ - public Map<String, Map<String, Boolean>> indexes() { - return idxs; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DB2MetadataDialect.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DB2MetadataDialect.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DB2MetadataDialect.java deleted file mode 100644 index 17eb8b2..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DB2MetadataDialect.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.parser.dialect; - -import java.util.*; - -/** - * DB2 specific metadata dialect. - */ -public class DB2MetadataDialect extends JdbcMetadataDialect { - /** {@inheritDoc} */ - @Override public Set<String> systemSchemas() { - return new HashSet<>(Arrays.asList("SYSIBM", "SYSCAT", "SYSSTAT", "SYSTOOLS")); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DatabaseMetadataDialect.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DatabaseMetadataDialect.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DatabaseMetadataDialect.java deleted file mode 100644 index 0d17567..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/DatabaseMetadataDialect.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.parser.dialect; - -import org.apache.ignite.schema.parser.*; - -import java.sql.*; -import java.util.*; - -/** - * Base class for database metadata dialect. - */ -public abstract class DatabaseMetadataDialect { - /** - * Gets tables from database. - * - * @param conn Database connection. - * @param tblsOnly If {@code true} then gets only tables otherwise gets tables and views. - * @return Collection of table descriptors. - * @throws SQLException If failed to get tables. - */ - public abstract Collection<DbTable> tables(Connection conn, boolean tblsOnly) throws SQLException; - - /** - * @return Collection of database system schemas. - */ - public Set<String> systemSchemas() { - return Collections.singleton("INFORMATION_SCHEMA"); - } - - /** - * Create table descriptor. - * - * @param schema Schema name. - * @param tbl Table name. - * @param cols Table columns. - * @param idxs Table indexes. - * @return New {@code DbTable} instance. - */ - protected DbTable table(String schema, String tbl, Collection<DbColumn> cols, Map<String, Map<String, Boolean>>idxs) { - Set<String> ascCols = new HashSet<>(); - - Set<String> descCols = new HashSet<>(); - - for (Map<String, Boolean> idx : idxs.values()) { - if (idx.size() == 1) - for (Map.Entry<String, Boolean> idxCol : idx.entrySet()) { - String colName = idxCol.getKey(); - - Boolean desc = idxCol.getValue(); - - if (desc != null) { - if (desc) - descCols.add(colName); - else - ascCols.add(colName); - } - } - } - - return new DbTable(schema, tbl, cols, ascCols, descCols, idxs); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/9cf45b43/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/JdbcMetadataDialect.java ---------------------------------------------------------------------- diff --git a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/JdbcMetadataDialect.java b/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/JdbcMetadataDialect.java deleted file mode 100644 index ab65e7a..0000000 --- a/modules/schema-load/src/main/java/org/apache/ignite/schema/parser/dialect/JdbcMetadataDialect.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.ignite.schema.parser.dialect; - -import org.apache.ignite.schema.parser.*; - -import java.sql.*; -import java.util.*; - -/** - * Metadata dialect that uses standard JDBC for reading metadata. - */ -public class JdbcMetadataDialect extends DatabaseMetadataDialect { - /** */ - private static final String[] TABLES_ONLY = {"TABLE"}; - - /** */ - private static final String[] TABLES_AND_VIEWS = {"TABLE", "VIEW"}; - - /** Schema catalog index. */ - private static final int TBL_CATALOG_IDX = 1; - - /** Schema name index. */ - private static final int TBL_SCHEMA_IDX = 2; - - /** Table name index. */ - private static final int TBL_NAME_IDX = 3; - - /** Primary key column name index. */ - private static final int PK_COL_NAME_IDX = 4; - - /** Column name index. */ - private static final int COL_NAME_IDX = 4; - - /** Column data type index. */ - private static final int COL_DATA_TYPE_IDX = 5; - - /** Column nullable index. */ - private static final int COL_NULLABLE_IDX = 11; - - /** Index name index. */ - private static final int IDX_NAME_IDX = 6; - - /** Index column name index. */ - private static final int IDX_COL_NAME_IDX = 9; - - /** Index column descend index. */ - private static final int IDX_ASC_OR_DESC_IDX = 10; - - /** {@inheritDoc} */ - @Override public Collection<DbTable> tables(Connection conn, boolean tblsOnly) throws SQLException { - DatabaseMetaData dbMeta = conn.getMetaData(); - - Set<String> sys = systemSchemas(); - - Collection<DbTable> tbls = new ArrayList<>(); - - try (ResultSet tblsRs = dbMeta.getTables(null, null, "%", - tblsOnly ? TABLES_ONLY : TABLES_AND_VIEWS)) { - while (tblsRs.next()) { - String tblCatalog = tblsRs.getString(TBL_CATALOG_IDX); - String tblSchema = tblsRs.getString(TBL_SCHEMA_IDX); - String tblName = tblsRs.getString(TBL_NAME_IDX); - - // In case of MySql we should use catalog. - String schema = tblSchema != null ? tblSchema : tblCatalog; - - // Skip system schemas. - if (sys.contains(schema)) - continue; - - Set<String> pkCols = new HashSet<>(); - - try (ResultSet pkRs = dbMeta.getPrimaryKeys(tblCatalog, tblSchema, tblName)) { - while (pkRs.next()) - pkCols.add(pkRs.getString(PK_COL_NAME_IDX)); - } - - List<DbColumn> cols = new ArrayList<>(); - - try (ResultSet colsRs = dbMeta.getColumns(tblCatalog, tblSchema, tblName, null)) { - while (colsRs.next()) { - String colName = colsRs.getString(COL_NAME_IDX); - - cols.add(new DbColumn( - colName, - colsRs.getInt(COL_DATA_TYPE_IDX), - pkCols.contains(colName), - colsRs.getInt(COL_NULLABLE_IDX) == DatabaseMetaData.columnNullable)); - } - } - - Map<String, Map<String, Boolean>> idxs = new LinkedHashMap<>(); - - try (ResultSet idxRs = dbMeta.getIndexInfo(tblCatalog, tblSchema, tblName, false, true)) { - while (idxRs.next()) { - String idxName = idxRs.getString(IDX_NAME_IDX); - - String colName = idxRs.getString(IDX_COL_NAME_IDX); - - if (idxName == null || colName == null) - continue; - - Map<String, Boolean> idx = idxs.get(idxName); - - if (idx == null) { - idx = new LinkedHashMap<>(); - - idxs.put(idxName, idx); - } - - String askOrDesc = idxRs.getString(IDX_ASC_OR_DESC_IDX); - - Boolean desc = askOrDesc != null ? "D".equals(askOrDesc) : null; - - idx.put(colName, desc); - } - } - - tbls.add(table(schema, tblName, cols, idxs)); - } - } - - return tbls; - } -}