2

I receive a package from my manager in compressed format, and below file path structure would be there upon extracting the same. These files must be copied in a specific sequence to a Database.

--DDL
-----abc.sql
--Table
-----def.sql
--Function
-----ghi.sql
--Stored Procedure
-----jkl.sql
-----mno.sql

The requirement is such that contents of folder DDL must be applied first, then Table, then Functions and finally Stored Procedure.

Sometimes there would be only two folders like below

--Function
----abc.sql
--Stored Procedure
----jkl.sql
----mno.sql

In such cases too, stored procedure must be applied at the end. The order cannot be changed irrespective of what folders are there in the extracted file.

How to achieve this with Java? I have easily implemented this in Python.

Note: Is it possible to mix filevisitor interface in this case considering there would be sub dirs and multiple files within each directories?

CK5
  • 1,055
  • 3
  • 16
  • 29

1 Answers1

0

Assuming content is already decompressed, I would implement it in following way:

  1. With Files.walk() method traverse through whole directory

  2. Filter out only SQL files

  3. Map paths to type which contains the path itself and directory priority so that type is sortable

  4. Sort results

  5. Apply SQL

In short

final Path sourcePath = Paths.get("/tmp/extracted-sql-import-root/");
try (Stream<Path> walk = Files.walk(sourcePath)) {

  walk.filter(isSqlFile)
    .map(filePath -> new SqlFile(sourcePath, filePath))
    .sorted()
    .forEach(processSqlFile);

} catch (IOException iOException) {
  // TODO handle exception
}

I did not use FileVisitor as I assume you can not influence the order in which the files are being visited, and then it becomes oboslete, as you are concerned about the order.

Link to full code, I didn't handle all of the actual edge-cases.

From the algorithm I left out the SQL part, I guess you are interested only in file processing.

RenatoIvancic
  • 1,798
  • 3
  • 21
  • 36
  • @Renatolvancic Thank you for the code snippet :) But how to run this program? – CK5 Apr 21 '20 at 05:49
  • I recommend you to check other answers on how to run java applications from command line or in IDE Examples: http://www.eclipseonetips.com/2014/06/16/run-a-single-junit-test-method-in-eclipse/ https://stackoverflow.com/questions/2235276/how-to-run-junit-test-cases-from-the-command-line – RenatoIvancic Apr 21 '20 at 09:50