· 9 years ago · Dec 15, 2016, 01:12 PM
1package databaseManager;
2
3import java.io.FileNotFoundException;
4import java.io.IOException;
5import java.nio.file.FileSystemNotFoundException;
6import java.sql.Date;
7import java.text.ParseException;
8import java.text.SimpleDateFormat;
9import java.util.ArrayList;
10import java.util.Arrays;
11import java.util.List;
12import java.util.regex.Matcher;
13import java.util.regex.Pattern;
14import javax.xml.parsers.ParserConfigurationException;
15import javax.xml.stream.XMLStreamException;
16import javax.xml.transform.TransformerException;
17
18import org.xml.sax.SAXException;
19import statementsClasses.*;
20
21/**
22 * This class parsers and conquers the SQL statements entered. To check if the
23 * entered statement is true, and send the creation order to the creation class
24 * or the operations to the operations class
25 *
26 * @author FNSY
27 *
28 */
29public class StatementsParser {
30 // private String statement;
31 private static StatementsParser statementsParser = null;
32 private String[] reservedWords;
33 private CreateDatabase createDatabaseObj;
34 private CreateTable createTableObj;
35 private UseDatabase useDatabaseObj;
36 private DeleteData deleteDataObj;
37 private DeleteAllData deleteAllDataObj;
38 private SimpleUpdateTable noWhereUpdateObj;
39 private WhereUpdateTable whereUpdateObj;
40 private DropDatabase dropDatabaseObj;
41 private DropTable dropTableObj;
42 private EnhancedInsertion columnsInsertObj;
43 private SimpleInsertion noColumnsInsertObj;
44 private AlterAddColumns alterAddColumnsObj;
45 private AlterDeleteColumns alterDeleteColumnsObj;
46 private SelectAllWhere selectAllWhereObj;
47 private SelectAllNoWhere selectAllNoWhereObj;
48 private SelectDedicatedWhere selectDedicatedWhereObj;
49 private SelectDedicatedNoWhere selectDedicatedNoWhereObj;
50 private SelectDistinctWhere selectDistinctWhereObj;
51 private SelectDistinctNoWhere selectDistinctNoWhereObj;
52 private String dbName = null;
53
54 /**
55 * current database name
56 */
57
58 public StatementsParser() {
59 initializeReservedWords();
60 }
61
62 public static synchronized StatementsParser createObject() {
63 if (statementsParser == null) {
64 statementsParser = new StatementsParser();
65 }
66 return statementsParser;
67 }
68
69 public final void enterStatement(final String statement) throws Exception {
70 String checkedStatement;
71 checkedStatement = removeWhiteSpaces(statement);
72
73 String upperCaseStatement = checkedStatement.toUpperCase();
74 // try {
75 selectRightAction(upperCaseStatement.split(" "), checkedStatement);
76 // } catch (Exception x) {
77 // System.out.println("PLEASE ENTER A VALID STATEMENT");
78 // }
79 }
80
81 private void selectRightAction(String[] upperCaseStatement, String checkedStatement)
82 throws ParserConfigurationException, SAXException, IOException, FileSystemNotFoundException,
83 XMLStreamException, TransformerException {
84 // if (isValidStatement(checkedStatement))
85 if (upperCaseStatement[0].equals("USE"))
86 useStatement(checkedStatement.split(" ")); // done
87 else if (upperCaseStatement[0].equals("CREATE"))
88 creationStatement(checkedStatement); // done
89 else if (upperCaseStatement[0].equals("DELETE"))
90 deletionStatement(checkedStatement);
91 else if (upperCaseStatement[0].equals("UPDATE"))
92 updateStatement(checkedStatement);
93 else if (upperCaseStatement[0].equals("DROP"))
94 dropStatement(checkedStatement);
95 else if (upperCaseStatement[0].equals("INSERT") && upperCaseStatement[1].equals("INTO"))
96 insertionStatement(checkedStatement);
97 else if (upperCaseStatement[0].equals("SELECT"))
98 selectStatement(checkedStatement);
99 else if (upperCaseStatement[0].equals("ALTER") && upperCaseStatement[1].equals("TABLE"))
100 alterStatement(checkedStatement);
101 else
102 throw new RuntimeException();
103 // else
104 // throw new RuntimeException();
105 }
106
107 /**
108 * This method checks if the SQL statement is written in right format. with
109 * no extra spaces and trailed by a semicolon
110 *
111 * @param statement
112 * @return
113 */
114
115 private void useStatement(String[] splitted) { // done check
116 splitted = filterSplittedArray(splitted);
117 if (splitted.length == 2) {
118 useDatabaseObj = new UseDatabase();
119 useDatabaseObj.setDatabaseName(splitted[1]);
120 dbName = splitted[1];
121 }
122 }
123
124 public UseDatabase getUseDatabaseObject() {
125 return useDatabaseObj;
126 }
127
128 /**
129 * create statement
130 *
131 * @param statement
132 * @throws IOException
133 * @throws SAXException
134 * @throws ParserConfigurationException
135 * @throws XMLStreamException
136 * @throws TransformerException
137 */
138 private final void creationStatement(final String statement)
139 throws ParserConfigurationException, SAXException, IOException, XMLStreamException, TransformerException {
140 String restOfTheString = statement.substring(7, statement.length() - 1);
141 try {
142 creationOfDatabase(restOfTheString);
143
144 } catch (RuntimeException x) {
145 creationOfTable(restOfTheString);
146 }
147
148 }
149
150 final void creationOfTable(String statement)
151 throws ParserConfigurationException, SAXException, IOException, XMLStreamException, TransformerException { // done
152
153 statement = replaceVarchar(statement);
154 statement = removeWhiteSpaces(statement);
155 String tableString = filterString(statement.substring(0, 5));
156 if (tableString.compareToIgnoreCase("TABLE") == 0) {
157 String[] tableDetails = statement.substring(6, statement.length()).split(" ");
158 tableDetails = filterSplittedArrayForTableCreation(tableDetails);
159 int length = tableDetails.length;
160 if (isValidName(tableDetails[0]) && !isReservedWord(tableDetails[0])) {
161
162 ArrayList<String> columnName = new ArrayList<>();
163 ArrayList<String> dataType = new ArrayList<>();
164 for (int i = 1; i < length; i++) {
165 if (i % 2 == 1) {
166 columnName.add(tableDetails[i]);
167 } else {
168 if (tableDetails[i].replace(",", "").equals("String")
169 || tableDetails[i].replace(",", "").equals("int")
170 || tableDetails[i].replace(",", "").equals("date")
171 || tableDetails[i].replace(",", "").equals("float")) {
172 // edited in the JDBC version added new datatypes
173 if (tableDetails[i].contains(",")) {
174 dataType.add(filterString(tableDetails[i]));
175
176 } else if (!tableDetails[i].contains(",")) {
177 try {
178 String checkLast = tableDetails[i + 1];
179 throw new RuntimeException();
180 } catch (ArrayIndexOutOfBoundsException x) {
181 dataType.add(tableDetails[i]);
182 }
183 }
184 } else
185 throw new RuntimeException();
186 }
187 }
188 if (validateEqualSize(columnName, dataType) && isValidNameInArrayList(columnName)) { // checking
189 // lengths
190 createTableObj = new CreateTable(); // and
191 createTableObj.setColumnsNames(columnName);
192 createTableObj.setDatabaseName(dbName);
193 createTableObj.setDataType(dataType);
194 createTableObj.setTableName(tableDetails[0]);
195
196 }
197 } else
198 throw new RuntimeException();
199
200 } else
201 throw new RuntimeException();
202 }
203
204 public CreateTable getCreateTableObject() {
205 return this.createTableObj;
206 }
207
208 private void creationOfDatabase(final String statement) { // done
209 // check
210 String databaseString = statement.substring(0, 8);
211 if (databaseString.compareToIgnoreCase("DATABASE") == 0) {
212 String databaseName = filterString(statement.substring(9, statement.length()));
213 if (isValidName(databaseName) && !isReservedWord(databaseName)) {
214 createDatabaseObj = new CreateDatabase();
215 createDatabaseObj.setDatabaseName(databaseName);
216
217 } else
218 throw new RuntimeException();
219 } else
220 throw new RuntimeException();
221 }
222
223 public CreateDatabase getCreateDatabaseObj() {
224 return this.createDatabaseObj;
225 }
226
227 // end of creation
228 private void deletionStatement(String statement) {
229 String deleteString = statement.substring(0, 11);
230 if (deleteString.compareToIgnoreCase("DELETE FROM") == 0 && statement.toUpperCase().contains("WHERE")) {
231 String restOfString = statement.substring(12, statement.length() - 1);
232 String tableName, conditionSymbol, columnName, valueIndicatingRow;
233 String[] splitted = restOfString.split(" ");
234 tableName = splitted[0];
235 for (int i = 0; i < splitted.length; i++) {
236 if (splitted[i].compareToIgnoreCase("WHERE") == 0 && (splitted[i + 2].equals("=")
237 || splitted[i + 2].equals("<") || splitted[i + 2].equals(">"))) {
238 columnName = splitted[i + 1];
239 conditionSymbol = splitted[i + 2];
240 valueIndicatingRow = schrodingarString(splitted[i + 3]);
241 try {
242 if (isValidName(tableName) && isValidName(columnName)) {
243 deleteDataObj = new DeleteData();
244 deleteDataObj.setTableName(tableName);
245 deleteDataObj.setColumnName(columnName);
246 deleteDataObj.setConditionSymbol(conditionSymbol);
247 deleteDataObj.setValueIndicatingRow(valueIndicatingRow);
248
249 } else
250 throw new RuntimeException();
251 } catch (FileSystemNotFoundException x) {
252 throw new RuntimeException();
253 }
254 break;
255 }
256 }
257 } else
258 try {
259 deleteAllTable(statement);
260 } catch (FileSystemNotFoundException | ParserConfigurationException | SAXException | IOException e) {
261 throw new RuntimeException();
262 }
263 }
264
265 public DeleteData getDeleteDataObject() {
266 return this.deleteDataObj;
267 }
268
269 private void deleteAllTable(String statement)
270 throws FileSystemNotFoundException, ParserConfigurationException, SAXException, IOException {
271 String deleteAllString = statement.substring(0, 11);
272 String deleteAllAstString = statement.substring(0, 13);
273 String tableName;
274 if (deleteAllString.compareToIgnoreCase("DELETE FROM") == 0) {
275 tableName = statement.substring(12, statement.length() - 1);
276 if (isValidName(tableName)) {
277 System.out.println(tableName);
278 deleteAllDataObj = new DeleteAllData();
279 deleteAllDataObj.setTableName(tableName);
280
281 } else
282 throw new RuntimeException();
283
284 } else if (deleteAllAstString.compareToIgnoreCase("DELETE * FROM") == 0) {
285 tableName = statement.substring(14, statement.length() - 1);
286 if (isValidName(tableName)) {
287 deleteAllDataObj = new DeleteAllData();
288 deleteAllDataObj.setTableName(tableName);
289
290 } else
291 throw new RuntimeException();
292 }
293
294 }
295
296 public DeleteAllData getDeleteAllDataObj() {
297 return this.deleteAllDataObj;
298 }
299 // end of delete
300
301 private void updateStatement(String statement) throws FileSystemNotFoundException, ParserConfigurationException,
302 SAXException, IOException, XMLStreamException {
303 String[] splitted = statement.substring(7, statement.length()).split(" ");
304 splitted = filterSplittedArray(splitted);
305 if (statement.toUpperCase().contains("SET") && statement.toUpperCase().contains("WHERE")) {
306 containingWhereUpdateStatement(splitted);
307 } else if (statement.toUpperCase().contains("SET") && !statement.toUpperCase().contains("WHERE")) {
308 notContainingWhereUpdateStatement(splitted);
309 }
310
311 }
312
313 private void containingWhereUpdateStatement(String[] splitted)
314 throws FileSystemNotFoundException, ParserConfigurationException, SAXException, IOException {
315 splitted = filterSplittedArray(splitted);
316 String conditionSymbol = null;
317 String tableName = splitted[0];
318 if (splitted[1].compareToIgnoreCase("SET") == 0) {
319 ArrayList<String> columnName = new ArrayList<>();
320 ArrayList<String> values = new ArrayList<>();
321 String guideColumn = null, guideValue = null;
322 for (int i = 2; i < splitted.length; i++) {
323 if (splitted[i].compareToIgnoreCase("WHERE") != 0) {
324 if (i % 3 == 0)
325 if (splitted[i].equals("=")) {
326 columnName.add(splitted[i - 1]);
327 if (splitted[i + 1].compareToIgnoreCase("WHERE") != 0)
328 values.add(splitted[i + 1]);
329 } else
330 throw new RuntimeException();
331
332 } else if (splitted[i + 2].equals("=") || splitted[i + 2].equals("<") || splitted[i + 2].equals(">")) {
333
334 guideColumn = splitted[i + 1];
335 conditionSymbol = splitted[i + 2];
336 guideValue = splitted[i + 3];
337 break;
338 } else {
339 throw new RuntimeException();
340 }
341 }
342 values = makeValuesValid(values);
343 System.out.println(values.get(0));
344 guideValue = schrodingarString(guideValue);
345 if (validateEqualSize(columnName, values) && isValidName(tableName) && isValidNameInArrayList(columnName)) {
346 whereUpdateObj = new WhereUpdateTable();
347 whereUpdateObj.setColumnName(columnName);
348 whereUpdateObj.setTableName(tableName);
349 whereUpdateObj.setValues(values);
350 whereUpdateObj.setGuideValue(guideValue);
351 whereUpdateObj.setConditionSymbol(conditionSymbol);
352 whereUpdateObj.setGuideColumn(guideColumn);
353
354 } else
355 throw new RuntimeException();
356
357 } else
358 throw new RuntimeException();
359
360 }
361
362 public WhereUpdateTable getWhereUpdateObject() {
363 return this.whereUpdateObj;
364 }
365
366 private void notContainingWhereUpdateStatement(String[] splitted) throws FileSystemNotFoundException,
367 FileNotFoundException, ParserConfigurationException, SAXException, IOException, XMLStreamException {
368 splitted = filterSplittedArray(splitted);
369 String tableName = splitted[0];
370 if (splitted[1].compareToIgnoreCase("SET") == 0) {
371 ArrayList<String> columnName = new ArrayList<>();
372 ArrayList<String> values = new ArrayList<>();
373 for (int i = 2; i < splitted.length; i++) {
374 if (splitted[i].equals("=")) {
375 columnName.add(splitted[i - 1]);
376 values.add(schrodingarString(splitted[i + 1])); // fnsy101
377 }
378 }
379 if (validateEqualSize(columnName, values) && isValidName(tableName) && isValidNameInArrayList(columnName)) {
380 noWhereUpdateObj.setTableName(tableName);
381 noWhereUpdateObj.setColumnName(columnName);
382 noWhereUpdateObj.setValues(values);
383 } else
384 throw new RuntimeException();
385 }
386
387 }
388
389 public SimpleUpdateTable getNoWhereUpdateObject() {
390 return this.noWhereUpdateObj;
391 }
392
393 // end of update
394 /**
395 * drop Statement
396 *
397 * @param statement
398 * @throws FileNotFoundException
399 */
400 private void dropStatement(final String statement) throws FileNotFoundException {
401 String[] splitted = statement.substring(5, statement.length()).split(" ");
402 splitted = filterSplittedArray(splitted);
403 try {
404 dropOfTable(splitted);
405 } catch (Exception x) {
406 dropOfDatabase(splitted);
407 }
408 }
409
410 private void dropOfDatabase(String[] splitted) {
411 if (splitted.length == 2) {
412 if (splitted[0].compareToIgnoreCase("DATABASE") == 0) {
413 dropDatabaseObj = new DropDatabase();
414 dropDatabaseObj.setDatabaseName(splitted[1]);
415 } else
416 throw new RuntimeException();
417 } else
418 throw new RuntimeException();
419 }
420
421 public DropDatabase getDropDatabaseObject() {
422 return this.dropDatabaseObj;
423 }
424
425 private void dropOfTable(String[] splitted) throws FileNotFoundException {
426 if (splitted.length == 2) {
427 if (splitted[0].compareToIgnoreCase("TABLE") == 0) {
428 dropTableObj = new DropTable();
429 dropTableObj.setTableName(splitted[1]);
430 } else
431 throw new RuntimeException();
432 } else
433 throw new RuntimeException();
434 }
435
436 public DropTable getDropTableObject() {
437 return this.dropTableObj;
438 }
439 // end of drop
440
441 private void insertionStatement(String statement) throws FileSystemNotFoundException, XMLStreamException,
442 ParserConfigurationException, SAXException, IOException {
443 if (statement.toUpperCase().contains("VALUES")) {
444 String[] splitted = statement.substring(12, statement.length()).split(" ");
445 splitted = filterSplittedArray(splitted);
446 try { // try catch block fnsy101
447 withColumnsNamesInsertionStatement(splitted);
448
449 } catch (Exception x) {
450 withoutColumnsNamesInsertionStatement(splitted);
451
452 }
453
454 } else
455 throw new RuntimeException();
456
457 }
458
459 private void withColumnsNamesInsertionStatement(String[] splitted) throws FileSystemNotFoundException,
460 ParserConfigurationException, SAXException, IOException, XMLStreamException {
461 // splitted[0] is the tableName
462 ArrayList<String> columnName = new ArrayList<>();
463 ArrayList<String> valuesToBeInserted = new ArrayList<>();
464 boolean valuesTurn = false;
465 for (int i = 1; i < splitted.length; i++) {
466 if (splitted[i].toUpperCase().equals("VALUES")) {
467 i += 1;
468 valuesTurn = true;
469 }
470 if (!valuesTurn)
471 columnName.add(splitted[i]);
472 else
473 valuesToBeInserted.add(schrodingarString(splitted[i])); // fnsy101
474 }
475 if (validateEqualSize(columnName, valuesToBeInserted) && isValidName(splitted[0])) {
476 columnsInsertObj = new EnhancedInsertion();
477 columnsInsertObj.setTableName(splitted[0]);
478 columnsInsertObj.setColumnName(columnName);
479 columnsInsertObj.setValuesToBeInserted(valuesToBeInserted);
480
481 }
482
483 else {
484 throw new RuntimeException();
485 }
486 }
487
488 public EnhancedInsertion getColumnsInsertionObject() {
489 return this.columnsInsertObj;
490 }
491
492 private void withoutColumnsNamesInsertionStatement(String[] splitted) throws XMLStreamException,
493 FileSystemNotFoundException, ParserConfigurationException, SAXException, IOException {
494 // splitted[0] is the tableName // splitted[1] is the word VALUES
495 ArrayList<String> valuesToBeInserted = new ArrayList<>();
496 for (int i = 2; i < splitted.length; i++) {
497 valuesToBeInserted.add(schrodingarString(splitted[i])); // fnsy101
498 }
499
500 if (isValidName(splitted[0])) { // fnsy101
501 noColumnsInsertObj = new SimpleInsertion();
502 noColumnsInsertObj.setTableName(splitted[0]);
503 noColumnsInsertObj.setValuesToBeInserted(valuesToBeInserted);
504 } else
505 throw new RuntimeException();
506 }
507
508 public SimpleInsertion getNoColumnsInsertObject() {
509 return this.noColumnsInsertObj;
510 }
511
512 // end insert
513
514 private void selectStatement(String statement) throws FileSystemNotFoundException, XMLStreamException,
515 ParserConfigurationException, SAXException, IOException {
516 if (statement.toUpperCase().contains("*")) {
517 selectAllStatement(statement);
518 } else {
519
520 String[] splitted = statement.replace(";", "").split(" ");
521 if (splitted[1].toUpperCase().equals("DISTINCT")) {
522 if (statement.toUpperCase().contains("FROM"))
523 if (statement.toUpperCase().contains("WHERE")) {
524 containsWhereSelectDistinctStatement(splitted);
525
526 } else {
527 notContainsWhereSelectDistinctStatement(splitted);
528
529 }
530
531 } else {
532 splitted = statement.substring(7, statement.length()).split(" ");
533 splitted = filterSplittedArray(splitted);
534 dedicatedSelectStatement(splitted);
535 }
536 } // add throw exception here JDBC
537
538 }
539
540 private void selectAllStatement(String statement) throws XMLStreamException, FileSystemNotFoundException,
541 ParserConfigurationException, SAXException, IOException {
542 String selectAllFromString = statement.substring(0, 13);
543 if (selectAllFromString.compareToIgnoreCase("SELECT * FROM") == 0) {
544 String restOfString = filterString(statement.substring(14, statement.length()));// filter
545 if (statement.toUpperCase().contains("WHERE")) {
546 String[] splitted = filterSplittedArray(restOfString.split(" "));
547
548 containsWhereSelectAllStatement(splitted[0], splitted);
549 } else if (!statement.toUpperCase().contains("WHERE")) {
550 // send tableName String: restOfString
551 selectAllNoWhereObj = new SelectAllNoWhere();
552 if (isValidName(restOfString)) {
553 selectAllNoWhereObj.setTableName(restOfString);
554 } else
555 throw new RuntimeException();
556 }
557 } else
558 throw new RuntimeException();
559 }
560
561 public SelectAllNoWhere getSelectAllNoWhereObject() {
562 return this.selectAllNoWhereObj;
563 }
564
565 private void dedicatedSelectStatement(String[] splitted) throws FileSystemNotFoundException, FileNotFoundException,
566 ParserConfigurationException, SAXException, IOException, XMLStreamException {
567 ArrayList<String> columnsName = new ArrayList<>();
568 int i = 0;
569 int holdIndex;
570 while (i < splitted.length && !splitted[i].toUpperCase().equals("FROM")) {
571 columnsName.add(splitted[i]);
572 i++;
573 }
574 String tableName = splitted[++i];
575 holdIndex = i;
576 try {
577 if (splitted[++i].compareToIgnoreCase("WHERE") == 0) {
578 ArrayList<String> afterFromString = new ArrayList<>();
579 for (int j = holdIndex; j < splitted.length; j++) {
580 afterFromString.add(splitted[j]);
581 }
582 String[] sendToWhere = new String[afterFromString.size()];
583 for (int j = 0; j < afterFromString.size(); j++)
584 sendToWhere[j] = afterFromString.get(j);
585
586 containsWhereDedicatedSelectStatement(tableName, columnsName, splitted);
587 } else
588 throw new RuntimeException();
589 } catch (ArrayIndexOutOfBoundsException x) {
590 if (isValidNameInArrayList(columnsName) && isValidName(tableName)) {
591 selectDedicatedNoWhereObj = new SelectDedicatedNoWhere();
592
593 selectDedicatedNoWhereObj.setColumnsName(columnsName);
594 selectDedicatedNoWhereObj.setTableName(tableName);
595
596 } else {
597 throw new RuntimeException();
598 }
599
600 // send ArrayList:columnName String:tableName
601 }
602
603 }
604
605 public SelectDedicatedNoWhere getSelectDedicatedNoWhereObject() {
606 return this.selectDedicatedNoWhereObj;
607
608 }
609
610 private void containsWhereDedicatedSelectStatement(String tableName, ArrayList<String> columnsName,
611 String[] splitted) throws XMLStreamException, FileSystemNotFoundException, ParserConfigurationException,
612 SAXException, IOException {
613 if (splitted.length == 5) {
614 // splitted array starts after the word FROM
615 // splitted[0] table name
616 String columnName = splitted[2];
617 String conditionSymbol = splitted[3];
618 String value = schrodingarString(splitted[4]);
619 if (isValidName(columnName)
620 && (conditionSymbol.equals("=") || conditionSymbol.equals("<") || conditionSymbol.equals(">"))) {
621 selectDedicatedWhereObj = new SelectDedicatedWhere();
622 selectDedicatedWhereObj.setTableName(tableName);
623 selectDedicatedWhereObj.setColumnName(columnName);
624 selectDedicatedWhereObj.setConditionSymbol(conditionSymbol);
625 selectDedicatedWhereObj.setTableName(tableName);
626 selectDedicatedWhereObj.setColumnsName(columnsName);
627
628 } else
629 throw new RuntimeException();
630
631 } else
632 throw new RuntimeException();
633 }
634
635 public SelectDedicatedWhere getSelectDedicatedWhereObject() {
636 return this.selectDedicatedWhereObj;
637 }
638
639 private void containsWhereSelectAllStatement(String tableName, String[] splitted)
640 throws FileSystemNotFoundException, ParserConfigurationException, SAXException, IOException,
641 XMLStreamException {
642 if (splitted.length == 5) {
643 // splitted array starts after the word FROM
644 // splitted[0] table name
645 String columnName = splitted[2];
646 String conditionSymbol = splitted[3];
647 splitted[4] = schrodingarString(splitted[4]);
648 String value = splitted[4];
649 if (conditionSymbol.equals("=") || conditionSymbol.equals("<") || conditionSymbol.equals(">")) {
650 selectAllWhereObj = new SelectAllWhere();
651 selectAllWhereObj.setTableName(tableName);
652 selectAllWhereObj.setColumnName(columnName);
653 selectAllWhereObj.setConditionSymbol(conditionSymbol);
654 selectAllWhereObj.setValue(value);
655
656 } else
657 throw new RuntimeException();
658
659 } else
660 throw new RuntimeException();
661 }
662
663 public SelectAllWhere getSelectAllWhereObject() {
664 return this.selectAllWhereObj;
665 }
666
667 private void containsWhereSelectDistinctStatement(String[] splitted) {
668 ArrayList<String> columnsNames = new ArrayList<>();
669 String tableName = new String();
670 String columnName = new String();
671 String conditionSymbol = new String();
672 String value = new String();
673
674 int i = 2;
675 while (!splitted[i].toUpperCase().equals("FROM")) {
676 if (splitted[i].contains(",") && !splitted[i + 1].toUpperCase().equals("FROM")) {
677 columnsNames.add(splitted[i].replace(",", ""));
678 } else if (!splitted[i].contains(",") && splitted[i + 1].toUpperCase().equals("FROM")) {
679 columnsNames.add(splitted[i]);
680 }
681 i++;
682 }
683 tableName = splitted[++i];
684 if (splitted[++i].toUpperCase().equals("WHERE")) {
685 columnName = splitted[++i];
686 conditionSymbol = splitted[++i];
687 value = schrodingarString(splitted[++i]);
688 }
689
690 // remove all prints and send to raafat
691 for (int j = 0; j < columnsNames.size(); j++) {
692 System.out.println(columnsNames.get(j));
693 }
694
695 selectDistinctWhereObj = new SelectDistinctWhere();
696 selectDistinctWhereObj.setTableName(tableName);
697 selectDistinctWhereObj.setColumnsNames(columnsNames);
698 selectDistinctWhereObj.setColumnName(columnName);
699 selectDistinctWhereObj.setConditionSymbol(conditionSymbol);
700 selectDistinctWhereObj.setValue(value);
701
702 }
703
704 private void notContainsWhereSelectDistinctStatement(String[] splitted) {
705 ArrayList<String> columnsNames = new ArrayList<>();
706 String tableName = new String();
707
708 int i = 2;
709 while (!splitted[i].toUpperCase().equals("FROM")) {
710 if (splitted[i].contains(",") && !splitted[i + 1].toUpperCase().equals("FROM")) {
711 columnsNames.add(splitted[i].replace(",", ""));
712 } else if (!splitted[i].contains(",") && splitted[i + 1].toUpperCase().equals("FROM")) {
713 columnsNames.add(splitted[i]);
714 }
715 i++;
716 }
717 tableName = splitted[++i];
718
719 // remove all prints and send to raafat
720 for (int j = 0; j < columnsNames.size(); j++) {
721 System.out.println(columnsNames.get(j));
722 }
723 System.out.println(tableName);
724
725 selectDistinctNoWhereObj = new SelectDistinctNoWhere();
726 selectDistinctNoWhereObj.setTableName(tableName);
727 selectDistinctNoWhereObj.setColumnsNames(columnsNames);
728
729 }
730
731 public SelectDistinctWhere getSelectDistinctWhereObject() {
732 return this.selectDistinctWhereObj;
733 }
734
735 public SelectDistinctNoWhere getSelectDistinctNoWhereObject() {
736 return this.selectDistinctNoWhereObj;
737 }
738 // end select
739
740 private void alterStatement(String statement) throws FileSystemNotFoundException, XMLStreamException,
741 ParserConfigurationException, SAXException, IOException {
742 statement = replaceVarchar(statement);
743 String[] splitted = statement.split(" ");
744 splitted = filterSplittedArray(splitted);
745 if (splitted.length == 6)
746 if (splitted[3].toUpperCase().equals("ADD")) {
747 addingColumnALter(splitted);
748 } else if (splitted[3].toUpperCase().equals("DROP")) {
749 droppingColumnALter(splitted);
750 } else {
751 throw new RuntimeException();
752 }
753 else
754 throw new RuntimeException();
755 }
756
757 private void addingColumnALter(String[] splitted) {
758 if (splitted[5].equals("String") || splitted[5].equals("int") || splitted[5].equals("float")
759 || splitted[5].equals("date")) {
760
761 alterAddColumnsObj.setTableName(splitted[2]);
762 alterAddColumnsObj.setColumnName(splitted[4]);
763 alterAddColumnsObj.setDataType(splitted[5]);
764 // send to raafat splitted[2] < tableName
765 // splitted [4] columnName
766 // splitted [5] dataType
767
768 } else {
769 throw new RuntimeException();
770 }
771
772 }
773
774 public AlterAddColumns getAlterAddColumnsObject() {
775 return this.alterAddColumnsObj;
776 }
777
778 private void droppingColumnALter(String[] splitted) {
779 if (splitted[4].toUpperCase().equals("COLUMN")) {
780 alterDeleteColumnsObj.setTableName(splitted[2]);
781 alterDeleteColumnsObj.setColumnName(splitted[5]);
782
783 // send to raafat splitted[2] tableName
784 // send to raafat splitted[5] columnName
785 } else {
786 throw new RuntimeException();
787 }
788
789 }
790
791 public AlterDeleteColumns getAlterDeleteColumnsObject() {
792 return this.alterDeleteColumnsObj;
793 }
794
795 private String[] filterSplittedArray(String[] splitted) {
796 String[] filtered = new String[splitted.length];
797 for (int i = 0; i < splitted.length; i++)
798 filtered[i] = filterString(splitted[i]);
799 return filtered;
800 }
801
802 private String filterString(String string) {
803 string = string.replace("(", "").replace(")", "").replace(";", "").replace(",", ""); // fnsy101
804 return string;
805 }
806
807 private String[] filterSplittedArrayForTableCreation(String[] splitted) {
808 String[] filtered = new String[splitted.length];
809 for (int i = 0; i < splitted.length; i++)
810 filtered[i] = splitted[i].replace("(", "").replace(")", "").replace(";", "");
811 return filtered;
812 }
813
814 private boolean validateEqualSize(ArrayList one, ArrayList two) {
815 if (one.size() != two.size())
816 return false;
817 return true;
818 }
819
820 @SuppressWarnings("deprecation")
821 private String schrodingarString(String check) {
822 // added Float.parseFloat(check); in the JDBC version
823 check = check.trim();
824 if (check.charAt(0) == '\'' && check.charAt(check.length() - 1) == '\''
825 || check.charAt(0) == '\"' && check.charAt(check.length() - 1) == '\"') {
826
827 check = check.replace("#", " ").replace("\"", "").replace("'", "").trim();
828 try {
829 try {
830 Integer.parseInt(check);
831 } catch (NumberFormatException dx) {
832 Float.parseFloat(check);
833 }
834 throw new RuntimeException();
835 } catch (NumberFormatException x) {
836 return check;
837 }
838 } else {
839 try {
840 Integer.parseInt(check);
841 } catch (NumberFormatException dx) {
842 Float.parseFloat(check);
843 }
844 return check;
845 }
846
847 }
848
849 private String handleSingleQuotes(String statement) { // fnsy101
850 return handleDoubleQuotes(statement);
851 }
852
853 private String handleDoubleQuotes(String statement) { // fnsy101
854 char buf[] = statement.toCharArray(), quote = ' ', c;
855 for (int i = 0; i < buf.length; i++) {
856 if ((c = buf[i]) == '"' || c == '\'')
857 quote = (quote == ' ' ? c : quote == c ? ' ' : quote);
858 else if (c == ' ' && quote != ' ')
859 buf[i] = '#';
860 }
861 return new String(buf).trim();
862 }
863
864 private void initializeReservedWords() {
865 this.reservedWords = new String[] { "ALL", "ALTER", "AND", "ANY", "ARRAY", "ARROW", "AS", "ASC", "AT", "BEGIN",
866 "BETWEEN", "BY", "CASE", "CHECK", "CLUSTERS", "CLUSTER", "COLAUTH", "COLUMNS", "COMPRESS", "CONNECT",
867 "CRASH", "CREATE", "CURRENT", "DECIMAL", "DECLARE", "DEFAULT", "DELETE", "DESC", "DISTINCT", "DROP",
868 "ELSE", "END", "EXCEPTION", "EXCLUSIVE", "EXISTS", "FETCH", "FORM", "FOR", "FROM", "GOTO", "GRANT",
869 "GROUP", "HAVING", "IDENTIFIED", "IF", "IN", "INDEXES", "INDEX", "INSERT", "INTERSECT", "INTO", "IS",
870 "LIKE", "LOCK", "MINUS", "MODE", "NOCOMPRESS", "NOT", "NOWAIT", "NULL", "OF", "ON", "OPTION", "OR",
871 "ORDER", "OVERLAPS", "PRIOR", "PROCEDURE", "RANGE", "RECORD", "RESOURCE", "REVOKE", "SELECT", "SHARE",
872 "SIZE", "SQL", "SUBTYPE", "TABAUTH", "TABLE", "THEN", "TO", "TYPE", "UNION", "UNIQUE", "UPDATE", "USE",
873 "VALUES", "VIEW", "VIEWS", "WHEN", "WHERE", "WITH" };
874
875 }
876
877 private final boolean isValidStatement(final String statement) {
878 int semiColonIndex = statement.length() - 1;
879 if (!(statement.charAt(semiColonIndex) == ';'))
880 return false;
881
882 return true;
883 }
884
885 private final boolean isValidName(String name) {
886 name = name.toUpperCase();
887 for (int i = 0; i < name.length(); i++) {
888 int singleChar = name.charAt(i);
889 if ((singleChar < 65 && singleChar != 36) || (singleChar > 90 && singleChar != 95)) {
890 if (singleChar < 48 || singleChar > 57)
891 return false;
892 }
893 }
894 return true;
895 }
896
897 private final boolean isValidNameInArrayList(ArrayList<String> list) {
898 for (int i = 0; i < list.size(); i++) {
899 if (!isValidName(list.get(i)))
900 return false;
901 }
902 return true;
903 }
904
905 private ArrayList<String> makeValuesValid(ArrayList<String> list) {
906 ArrayList<String> ret = new ArrayList<>();
907 for (int i = 0; i < list.size(); i++) {
908 ret.add(schrodingarString(list.get(i)));
909 }
910 return ret;
911
912 }
913
914 private boolean isReservedWord(String name) {
915 name = name.toUpperCase();
916 for (int i = 0; i < this.reservedWords.length; i++)
917 if (name.equals(this.reservedWords[i]))
918 return true;
919 return false;
920 }
921
922 private String replaceVarchar(String statement) {
923 Pattern pattern = Pattern.compile("\\(\\d+\\)");
924 Matcher matcher = pattern.matcher(statement);
925 while (matcher.find()) {
926 statement = statement.replace(matcher.group(), "");
927 }
928 return statement.replace("varchar", "String");
929 }
930
931 private static boolean isSQLDate(String date) throws ParseException {
932 date = date.replace("'", "").replace("/", "-");
933 String[] dateArray = date.split("-");
934 if (dateArray.length == 3) {
935 Integer month = Integer.parseInt(dateArray[1]);
936 Integer day = Integer.parseInt(dateArray[2]);
937 if (month >= 1 && month <= 12) {
938 if (day >= 1 && day <= 31) {
939 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
940 java.util.Date finalDate = formatter.parse(date);
941 java.sql.Date sqlStartDate = new java.sql.Date(finalDate.getTime());
942 return true;
943 }
944 }
945 }
946 return false;
947 }
948
949 private String removeWhiteSpaces(final String statement) {
950 String checkedStatement;
951 checkedStatement = statement.replaceAll("=", " = ");
952 checkedStatement = checkedStatement.replace("\n", " ");
953 checkedStatement = checkedStatement.replaceAll("`", "'"); // fnsy101
954 checkedStatement = checkedStatement.replaceAll("\t", " "); // fnsy101
955 checkedStatement = handleSingleQuotes(checkedStatement);
956 checkedStatement = handleDoubleQuotes(checkedStatement);
957 checkedStatement = checkedStatement.replace("(", " (");
958 checkedStatement = checkedStatement.replaceAll(">", " > ");
959 checkedStatement = checkedStatement.replaceAll("<", " < ");
960 checkedStatement = checkedStatement.replaceAll(" +", " ");
961 checkedStatement = checkedStatement.replaceAll(" ,", ", ");
962 checkedStatement = checkedStatement.replaceAll(",", ", ");
963 checkedStatement = checkedStatement.replaceAll(" ;", "; ");
964 checkedStatement = checkedStatement.replaceAll("\\( ", "\\(");
965 checkedStatement = checkedStatement.replaceAll(" \\)", "\\)");
966 checkedStatement = checkedStatement.replaceAll("\\*", " \\* ");
967 checkedStatement = checkedStatement.replaceAll("\n", " ");
968 checkedStatement = checkedStatement.replaceAll(" +", " ");
969 checkedStatement = checkedStatement.trim();
970 return checkedStatement;
971 }
972
973}