SelfHoster: Add some debug println messages to help when things fail.
[online-glom:gwt-glom.git] / src / test / java / org / glom / web / server / SelfHoster.java
1 /*
2  * Copyright (C) 2012 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
6  * GWT-Glom is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation, either version 3 of the License, or (at your
9  * option) any later version.
10  *
11  * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with GWT-Glom.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package org.glom.web.server;
21
22 import java.io.BufferedReader;
23 import java.io.File;
24 import java.io.FileNotFoundException;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.net.ServerSocket;
30 import java.sql.Connection;
31 import java.sql.DriverManager;
32 import java.sql.SQLException;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.Locale;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Properties;
39
40 import org.apache.commons.lang3.StringUtils;
41 import org.glom.web.server.libglom.Document;
42 import org.glom.web.shared.DataItem;
43 import org.glom.web.shared.libglom.Field;
44 import org.jooq.InsertResultStep;
45 import org.jooq.InsertSetStep;
46 import org.jooq.Record;
47 import org.jooq.SQLDialect;
48 import org.jooq.Table;
49 import org.jooq.exception.DataAccessException;
50 import org.jooq.impl.Factory;
51
52 import com.google.common.io.Files;
53 import com.ibm.icu.text.NumberFormat;
54
55 /**
56  * @author Murray Cumming <murrayc@murrayc.com>
57  * 
58  */
59 public class SelfHoster {
60         // private String tempFilepathDir = "";
61         private boolean selfHostingActive = false;
62         private Document document = null;
63         private String username = "";
64         private String password = "";
65
66         SelfHoster(final Document document) {
67                 this.document = document;
68         }
69
70         private static final int PORT_POSTGRESQL_SELF_HOSTED_START = 5433;
71         private static final int PORT_POSTGRESQL_SELF_HOSTED_END = 5500;
72
73         private static final String DEFAULT_CONFIG_PG_HBA_LOCAL_8p4 = "# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD\n"
74                         + "\n"
75                         + "# local is for Unix domain socket connections only\n"
76                         + "# trust allows connection from the current PC without a password:\n"
77                         + "local   all         all                               trust\n"
78                         + "local   all         all                               ident\n"
79                         + "local   all         all                               md5\n"
80                         + "\n"
81                         + "# TCP connections from the same computer, with a password:\n"
82                         + "host    all         all         127.0.0.1    255.255.255.255    md5\n"
83                         + "# IPv6 local connections:\n"
84                         + "host    all         all         ::1/128               md5\n";
85
86         private static final String DEFAULT_CONFIG_PG_IDENT = "";
87         private static final String FILENAME_DATA = "data";
88
89         public boolean createAndSelfHostFromExample(final Document.HostingMode hostingMode) {
90
91                 if (!createAndSelfHostNewEmpty(hostingMode)) {
92                         // std::cerr << G_STRFUNC << ": test_create_and_selfhost_new_empty() failed." << std::endl;
93                         return false;
94                 }
95
96                 final boolean recreated = recreateDatabaseFromDocument(); /* TODO: Progress callback */
97                 if (!recreated) {
98                         if(!cleanup()) {
99                                 return false;
100                         }
101                 }
102
103                 return recreated;
104         }
105
106         /**
107          * @param document
108          * @param
109          * @param subDirectoryPath
110          * @return
111          */
112         private boolean createAndSelfHostNewEmpty(final Document.HostingMode hostingMode) {
113                 if (hostingMode != Document.HostingMode.HOSTING_MODE_POSTGRES_SELF) {
114                         // TODO: std::cerr << G_STRFUNC << ": This test function does not support the specified hosting_mode: " <<
115                         // hosting_mode << std::endl;
116                         return false;
117                 }
118
119                 // Save a copy, specifying the path to file in a directory:
120                 // For instance, /tmp/testglom/testglom.glom");
121                 final String tempFilename = "testglom";
122                 final File tempFolder = Files.createTempDir();
123                 final File tempDir = new File(tempFolder, tempFilename);
124
125                 final String tempDirPath = tempDir.getPath();
126                 final String tempFilePath = tempDirPath + File.separator + tempFilename;
127                 final File file = new File(tempFilePath);
128
129                 // Make sure that the file does not exist yet:
130                 {
131                         tempDir.delete();
132                 }
133
134                 // Save the example as a real file:
135                 document.setFileURI(file.getPath());
136
137                 document.setHostingMode(hostingMode);
138                 document.setIsExampleFile(false);
139                 final boolean saved = document.save();
140                 if (!saved) {
141                         System.out.println("createAndSelfHostNewEmpty(): Document.save() failed.");
142                         return false; // TODO: Delete the directory.
143                 }
144
145                 // We must specify a default username and password:
146                 final String user = "glom_default_developer_user";
147                 final String password = "glom_default_developer_password";
148
149                 // Create the self-hosting files:
150                 if (!initialize(user, password)) {
151                         System.out.println("createAndSelfHostNewEmpty(): initialize failed.");
152                         // TODO: Delete directory.
153                 }
154
155                 // Check that it really created some files:
156                 if (!tempDir.exists()) {
157                         System.out.println("createAndSelfHostNewEmpty(): tempDir does not exist.");
158                         // TODO: Delete directory.
159                 }
160
161                 return selfHost(user, password);
162         }
163
164         /**
165          * @param document
166          * @param user
167          * @param password
168          * @return
169          */
170         private boolean selfHost(final String user, final String password) {
171                 // TODO: m_network_shared = network_shared;
172
173                 if (getSelfHostingActive()) {
174                         // TODO: std::cerr << G_STRFUNC << ": Already started." << std::endl;
175                         return false; // STARTUPERROR_NONE; //Just do it once.
176                 }
177
178                 final String dbDirData = getSelfHostingDataPath(false);
179                 if (StringUtils.isEmpty(dbDirData) || !fileExists(dbDirData)) {
180                         /*
181                          * final String dbDirBackup = dbDir + File.separator + FILENAME_BACKUP;
182                          * 
183                          * if(fileExists(dbDirBackup)) { //TODO: std::cerr << G_STRFUNC <<
184                          * ": There is no data, but there is backup data." << std::endl; //Let the caller convert the backup to real
185                          * data and then try again: return false; // STARTUPERROR_FAILED_NO_DATA_HAS_BACKUP_DATA; } else {
186                          */
187                         // TODO: std::cerr << "ConnectionPool::create_self_hosting(): The data sub-directory could not be found." <<
188                         // dbdir_data_uri << std::endl;
189                         return false; // STARTUPERROR_FAILED_NO_DATA;
190                         // }
191                 }
192
193                 final int availablePort = discoverFirstFreePort(PORT_POSTGRESQL_SELF_HOSTED_START,
194                                 PORT_POSTGRESQL_SELF_HOSTED_END);
195                 // std::cout << "debug: " << G_STRFUNC << ":() : debug: Available port for self-hosting: " << available_port <<
196                 // std::endl;
197                 if (availablePort == 0) {
198                         // TODO: Use a return enum or exception so we can tell the user about this:
199                         // TODO: std::cerr << G_STRFUNC << ": No port was available between " << PORT_POSTGRESQL_SELF_HOSTED_START
200                         // << " and " << PORT_POSTGRESQL_SELF_HOSTED_END << std::endl;
201                         return false; // STARTUPERROR_FAILED_UNKNOWN_REASON;
202                 }
203
204                 final NumberFormat format = NumberFormat.getInstance(Locale.US);
205                 format.setGroupingUsed(false); // TODO: Does this change it system-wide?
206                 final String portAsText = format.format(availablePort);
207
208                 // -D specifies the data directory.
209                 // -c config_file= specifies the configuration file
210                 // -k specifies a directory to use for the socket. This must be writable by us.
211                 // Make sure to use double quotes for the executable path, because the
212                 // CreateProcess() API used on Windows does not support single quotes.
213                 final String dbDir = getSelfHostingPath("", false);
214                 final String dbDirConfig = getSelfHostingPath("config", false);
215                 final String dbDirHba = dbDirConfig + File.separator + "pg_hba.conf";
216                 final String dbDirIdent = dbDirConfig + File.separator + "pg_ident.conf";
217                 final String dbDirPid = getSelfHostingPath("pid", false);
218
219                 // Note that postgres returns this error if we split the arguments more,
220                 // for instance splitting -D and dbDirData into separate strings:
221                 // too many command-line arguments (first is "(null)")
222                 // Note: If we use "-D " instead of "-D" then the initdb seems to make the space part of the filepath,
223                 // though that does not happen with the normal command line.
224                 // However, we must have a space after -k.
225                 // Also, the c hba_file=path argument must be split after -c, or postgres will get a " hba_file" configuration
226                 // parameter instead of "hba_file".
227                 final String commandPathStart = getPathToPostgresExecutable("postgres");
228                 if(StringUtils.isEmpty(commandPathStart)) {
229                         System.out.println("selfHost(): getPathToPostgresExecutable(postgres) failed.");
230                         return false;
231                 }
232                 final ProcessBuilder commandPostgresStart = new ProcessBuilder(commandPathStart, "-D"
233                                 + shellQuote(dbDirData), "-p", portAsText, "-i", // Equivalent to -h "*", which in turn is equivalent
234                                                                                                                                         // to
235                                 // listen_addresses in postgresql.conf. Listen to all IP addresses,
236                                 // so any client can connect (with a username+password)
237                                 "-c", "hba_file=" + shellQuote(dbDirHba), "-c", "ident_file=" + shellQuote(dbDirIdent), "-k"
238                                                 + shellQuote(dbDir), "--external_pid_file=" + shellQuote(dbDirPid));
239                 // std::cout << G_STRFUNC << ": debug: " << command_postgres_start << std::endl;
240
241                 // Make sure to use double quotes for the executable path, because the
242                 // CreateProcess() API used on Windows does not support single quotes.
243                 //
244                 // Note that postgres returns this error if we split the arguments more,
245                 // for instance splitting -D and dbDirData into separate strings:
246                 // too many command-line arguments (first is "(null)")
247                 // Note: If we use "-D " instead of "-D" then the initdb seems to make the space part of the filepath,
248                 // though that does not happen with the normal command line.
249                 final String commandPathCheck = getPathToPostgresExecutable("pg_ctl");
250                 if(StringUtils.isEmpty(commandPathCheck)) {
251                         System.out.println("selfHost(): getPathToPostgresExecutable(pg_ctl) failed.");
252                         return false;
253                 }
254                 final ProcessBuilder commandCheckPostgresHasStarted = new ProcessBuilder(commandPathCheck,
255                                 "status", "-D" + shellQuote(dbDirData));
256
257                 // For postgres 8.1, this is "postmaster is running".
258                 // For postgres 8.2, this is "server is running".
259                 // This is a big hack that we should avoid. murrayc.
260                 //
261                 // pg_ctl actually seems to return a 0 result code for "is running" and a 1 for not running, at least with
262                 // Postgres 8.2,
263                 // so maybe we can avoid this in future.
264                 // Please do test it with your postgres version, using "echo $?" to see the result code of the last command.
265                 final String secondCommandSuccessText = "is running"; // TODO: This is not a stable API. Also, watch out for
266                                                                                                                                 // localisation.
267
268                 // The first command does not return, but the second command can check whether it succeeded:
269                 // TODO: Progress
270                 final boolean result = executeCommandLineAndWaitUntilSecondCommandReturnsSuccess(commandPostgresStart,
271                                 commandCheckPostgresHasStarted, secondCommandSuccessText);
272                 if (!result) {
273                         System.out.println("selfHost(): Error while attempting to self-host a database.");
274                         return false; // STARTUPERROR_FAILED_UNKNOWN_REASON;
275                 }
276
277                 // Remember the port for later:
278                 document.setConnectionPort(availablePort);
279
280                 return true; // STARTUPERROR_NONE;
281         }
282
283         /**
284          * @param dbDirData
285          * @return
286          */
287         private String shellQuote(final String str) {
288                 // TODO: If we add the quotes then they seem to be used as part of the path, though that is not a problem with
289                 // the normal command line.
290                 return str;
291
292                 // TODO: Escape.
293                 // return "'" + str + "'";
294         }
295
296         private String getSelfHostingPath(final String subpath, final boolean create) {
297                 final String dbDir = document.getSelfHostedDirectoryPath();
298                 if (StringUtils.isEmpty(subpath)) {
299                         return dbDir;
300                 }
301
302                 final String dbDirData = dbDir + File.separator + subpath;
303                 final File file = new File(dbDirData);
304
305                 // Return the path regardless of whether it exists:
306                 if (!create) {
307                         return dbDirData;
308                 }
309
310                 if (!file.exists()) {
311                         try {
312                                 Files.createParentDirs(file);
313                         } catch (final IOException e) {
314                                 // TODO Auto-generated catch block
315                                 e.printStackTrace();
316                                 return "";
317                         }
318
319                         if (!file.mkdir()) {
320                                 return "";
321                         }
322                 }
323
324                 return dbDirData;
325         }
326
327         private String getSelfHostingDataPath(final boolean create) {
328                 return getSelfHostingPath(FILENAME_DATA, create);
329         }
330
331         private boolean executeCommandLineAndWait(final ProcessBuilder command) {
332
333                 command.redirectErrorStream(true);
334
335                 // Run the first command, and wait for it to return:
336                 Process process = null;
337                 try {
338                         process = command.start();
339                 } catch (final IOException e) {
340                         // TODO Auto-generated catch block
341                         e.printStackTrace();
342                         return false;
343                 }
344
345                 final InputStream stderr = process.getInputStream();
346                 final InputStreamReader isr = new InputStreamReader(stderr);
347                 final BufferedReader br = new BufferedReader(isr);
348                 String output = "";
349                 String line;
350                 try {
351                         while ((line = br.readLine()) != null) {
352                                 output += line + "\n";
353                         }
354                 } catch (final IOException e1) {
355                         e1.printStackTrace();
356                         return false;
357                 }
358
359                 int result = 0;
360                 try {
361                         result = process.waitFor();
362                 } catch (final InterruptedException e) {
363                         // TODO Auto-generated catch block
364                         e.printStackTrace();
365                         return false;
366                 }
367
368                 if (result != 0) {
369                         System.out.println("Command failed: " + command.command().toString());
370                         System.out.print("Output: " + output);
371                         return false;
372                 }
373
374                 return true;
375         }
376
377         private boolean executeCommandLineAndWaitUntilSecondCommandReturnsSuccess(final ProcessBuilder command,
378                         final ProcessBuilder commandSecond, final String secondCommandSuccessText) {
379                 command.redirectErrorStream(true);
380
381                 // Run the first command, and do not wait for it to return:
382                 Process process = null;
383                 try {
384                         process = command.start();
385                 } catch (final IOException e) {
386                         // TODO Auto-generated catch block
387                         e.printStackTrace();
388                         return false;
389                 }
390
391                 final InputStream stderr = process.getInputStream();
392                 final InputStreamReader isr = new InputStreamReader(stderr);
393                 final BufferedReader br = new BufferedReader(isr);
394
395                 /*
396                  * We do not wait, because this (postgres, for instance), does not return: final int result = process.waitFor();
397                  * if (result != 0) { // TODO: Warn. return false; }
398                  */
399
400                 // Now run the second command, usually to verify that the first command has really done its work:
401                 final boolean result = executeCommandLineAndWait(commandSecond);
402
403                 // Try to get the output:
404                 if (!result) {
405                         String output = "";
406                         String line;
407                         try {
408                                 while ((line = br.readLine()) != null) {
409                                         output += line + "\n";
410                                         System.out.println(line);
411                                 }
412                         } catch (final IOException e1) {
413                                 // TODO Auto-generated catch block
414                                 e1.printStackTrace();
415                                 return false;
416                         }
417
418                         System.out.print("Output of first command: " + output);
419                 }
420
421                 return result;
422         }
423
424         /**
425          * @param string
426          * @return
427          */
428         private static String getPathToPostgresExecutable(final String string) {
429                 final List<String> dirPaths = new ArrayList<String>();
430                 dirPaths.add("/usr/bin");
431                 dirPaths.add("/usr/lib/postgresql/9.1/bin");
432                 dirPaths.add("/usr/lib/postgresql/9.0/bin");
433                 dirPaths.add("/usr/lib/postgresql/8.4/bin");
434                 
435                 for(String dir : dirPaths) {
436                         final String path = dir + File.separator + string;
437                         if(fileExistsAndIsExecutable(path)) {
438                                 return path;
439                         }
440                 }
441                 
442                 return "";
443         }
444
445         /**
446          * @param path
447          * @return
448          */
449         private static boolean fileExistsAndIsExecutable(String path) {
450                 final File file = new File(path);
451                 if(!file.exists()) {
452                         return false;
453                 }
454                 
455                 if(!file.canExecute()) {
456                         return false;
457                 }
458                 
459                 return true;
460         }
461
462         /**
463          * @param start
464          * @param end
465          * @return
466          */
467         private static int discoverFirstFreePort(final int start, final int end) {
468                 for (int port = start; port <= end; ++port) {
469                         try {
470                                 final ServerSocket socket = new ServerSocket(port);
471
472                                 // If the instantiation succeeded then the port was free:
473                                 return socket.getLocalPort(); // This must equal port.
474                         } catch (final IOException ex) {
475                                 continue; // try next port
476                         }
477                 }
478
479                 return 0;
480         }
481
482         /**
483          * @param dbDir
484          * @return
485          */
486         private static boolean fileExists(final String filePath) {
487                 final File file = new File(filePath);
488                 return file.exists();
489         }
490
491         /**
492          * @return
493          */
494         private boolean getSelfHostingActive() {
495                 return selfHostingActive;
496         }
497
498         /**
499          * @param cpds
500          * @return
501          */
502         private boolean initialize(final String initialUsername, final String initialPassword) {
503                 if (!initializeConfFiles()) {
504                         System.out.println("initialize(): initializeConfFiles() failed.");
505                         return false;
506                 }
507
508                 // initdb creates a new postgres database cluster:
509
510                 // Get file:// URI for the tmp/ directory:
511                 File filePwFile = null;
512                 try {
513                         filePwFile = File.createTempFile("glom_initdb_pwfile", "");
514                 } catch (final IOException e) {
515                         // TODO Auto-generated catch block
516                         e.printStackTrace();
517                 }
518                 final String tempPwFile = filePwFile.getPath();
519
520                 final boolean pwfileCreationSucceeded = createTextFile(tempPwFile, initialPassword);
521                 if (!pwfileCreationSucceeded) {
522                         System.out.println("initialize(): createTextFile() failed.");
523                         return false;
524                 }
525
526                 // Make sure to use double quotes for the executable path, because the
527                 // CreateProcess() API used on Windows does not support single quotes.
528                 final String dbDirData = getSelfHostingDataPath(false /* create */);
529
530                 // Note that initdb returns this error if we split the arguments more,
531                 // for instance splitting -D and dbDirData into separate strings:
532                 // too many command-line arguments (first is "(null)")
533                 // TODO: If we quote tempPwFile then initdb says that it cannot find it.
534                 // Note: If we use "-D " instead of "-D" then the initdb seems to make the space part of the filepath,
535                 // though that does not happen with the normal command line.
536                 boolean result = false;
537                 final String commandPath = getPathToPostgresExecutable("initdb");
538                 if(StringUtils.isEmpty(commandPath)) {
539                         System.out.println("initialize(): getPathToPostgresExecutable(initdb) failed.");
540                 } else {
541                         final ProcessBuilder commandInitdb = new ProcessBuilder(commandPath, "-D"
542                                         + shellQuote(dbDirData), "-U", initialUsername, "--pwfile=" + tempPwFile);
543         
544                         // Note that --pwfile takes the password from the first line of a file. It's an alternative to supplying it when
545                         // prompted on stdin.
546                         result = executeCommandLineAndWait(commandInitdb);
547                 }
548
549                 // Of course, we don't want this to stay around. It would be a security risk.
550                 final File fileTempPwFile = new File(tempPwFile);
551                 if (!fileTempPwFile.delete()) {
552                         System.out.println("initialize(): Failed to delete the password file.");
553                 }
554                 
555                 if (!result) {
556                         System.out.println("initialize(): Error while attempting to create self-hosting database.");
557                         return false;
558                 }
559
560                 // Save the username and password for later;
561                 this.username = initialUsername;
562                 this.password = initialPassword;
563
564                 return result; // ? INITERROR_NONE : INITERROR_COULD_NOT_START_SERVER;
565
566         }
567
568         private boolean initializeConfFiles() {
569                 final String dataDirPath = document.getSelfHostedDirectoryPath();
570
571                 final String dbDirConfig = dataDirPath + File.separator + "config";
572                 // String defaultConfContents = "";
573
574                 // Choose the configuration contents based on the postgresql version
575                 // and whether we want to be network-shared:
576                 // final float postgresqlVersion = 9.0f; //TODO: get_postgresql_utils_version_as_number(slot_progress);
577                 // final boolean networkShared = true;
578                 // std::cout << "DEBUG: postgresql_version=" << postgresql_version << std::endl;
579
580                 // TODO: Support the other configurations, as in libglom.
581                 final String defaultConfContents = DEFAULT_CONFIG_PG_HBA_LOCAL_8p4;
582
583                 // std::cout << "DEBUG: default_conf_contents=" << default_conf_contents << std::endl;
584
585                 final boolean hbaConfCreationSucceeded = createTextFile(dbDirConfig + File.separator + "pg_hba.conf",
586                                 defaultConfContents);
587                 if (!hbaConfCreationSucceeded) {
588                         System.out.println("initialize(): createTextFile() failed.");
589                         return false;
590                 }
591
592                 final boolean identConfCreationSucceeded = createTextFile(dbDirConfig + File.separator + "pg_ident.conf",
593                                 DEFAULT_CONFIG_PG_IDENT);
594                 if (!identConfCreationSucceeded) {
595                         System.out.println("initialize(): createTextFile() failed.");
596                         return false;
597                 }
598
599                 return true;
600         }
601
602         /**
603          * @param path
604          * @param contents
605          * @return
606          */
607         private static boolean createTextFile(final String path, final String contents) {
608                 final File file = new File(path);
609                 final File parent = file.getParentFile();
610                 if (parent == null) {
611                         System.out.println("initialize(): getParentFile() failed.");
612                         return false;
613                 }
614
615                 parent.mkdirs();
616                 try {
617                         file.createNewFile();
618                 } catch (final IOException e) {
619                         // TODO Auto-generated catch block
620                         e.printStackTrace();
621                         return false;
622                 }
623
624                 FileOutputStream output = null;
625                 try {
626                         output = new FileOutputStream(file);
627                 } catch (final FileNotFoundException e) {
628                         // TODO Auto-generated catch block
629                         e.printStackTrace();
630                         return false;
631                 }
632
633                 try {
634                         output.write(contents.getBytes());
635                 } catch (final IOException e) {
636                         // TODO Auto-generated catch block
637                         e.printStackTrace();
638                         return false;
639                 }
640
641                 return true;
642         }
643
644         /**
645          * @param document
646          * @return
647          */
648         private boolean recreateDatabaseFromDocument() {
649                 // Check whether the database exists already.
650                 final String dbName = document.getConnectionDatabase();
651                 if (StringUtils.isEmpty(dbName)) {
652                         return false;
653                 }
654
655                 document.setConnectionDatabase(dbName);
656                 Connection connection = createConnection();
657                 if (connection != null) {
658                         // Connection to the database succeeded, so the database
659                         // exists already.
660                         try {
661                                 connection.close();
662                         } catch (final SQLException e) {
663                                 // TODO Auto-generated catch block
664                                 e.printStackTrace();
665                         }
666                         return false;
667                 }
668
669                 // Create the database:
670                 progress();
671                 document.setConnectionDatabase("");
672
673                 connection = createConnection();
674                 if (connection == null) {
675                         System.out.println("recreatedDatabase(): createConnection() failed, before creating the database.");
676                         return false;
677                 }
678
679                 final boolean dbCreated = createDatabase(connection, dbName);
680
681                 if (!dbCreated) {
682                         return false;
683                 }
684
685                 progress();
686
687                 // Check that we can connect:
688                 try {
689                         connection.close();
690                 } catch (final SQLException e) {
691                         // TODO Auto-generated catch block
692                         e.printStackTrace();
693                 }
694                 connection = null;
695
696                 document.setConnectionDatabase(dbName);
697                 connection = createConnection();
698                 if (connection == null) {
699                         System.out.println("recreatedDatabase(): createConnection() failed, after creating the database.");
700                         return false;
701                 }
702
703                 progress();
704
705                 // Create each table:
706                 final List<String> tables = document.getTableNames();
707                 for (final String tableName : tables) {
708
709                         // Create SQL to describe all fields in this table:
710                         final List<Field> fields = document.getTableFields(tableName);
711
712                         progress();
713                         final boolean tableCreationSucceeded = createTable(connection, document, tableName, fields);
714                         progress();
715                         if (!tableCreationSucceeded) {
716                                 // TODO: std::cerr << G_STRFUNC << ": CREATE TABLE failed with the newly-created database." <<
717                                 // std::endl;
718                                 return false;
719                         }
720                 }
721
722                 // Note that create_database() has already called add_standard_tables() and add_standard_groups(document).
723
724                 // Add groups from the document:
725                 progress();
726                 if (!addGroupsFromDocument(document)) {
727                         // TODO: std::cerr << G_STRFUNC << ": add_groups_from_document() failed." << std::endl;
728                         return false;
729                 }
730
731                 // Set table privileges, using the groups we just added:
732                 progress();
733                 if (!setTablePrivilegesGroupsFromDocument(document)) {
734                         // TODO: std::cerr << G_STRFUNC << ": set_table_privileges_groups_from_document() failed." << std::endl;
735                         return false;
736                 }
737
738                 for (final String tableName : tables) {
739                         // Add any example data to the table:
740                         progress();
741
742                         // try
743                         // {
744                         progress();
745                         final boolean tableInsertSucceeded = insertExampleData(connection, document, tableName);
746
747                         if (!tableInsertSucceeded) {
748                                 // TODO: std::cerr << G_STRFUNC << ": INSERT of example data failed with the newly-created database." <<
749                                 // std::endl;
750                                 return false;
751                         }
752                         // }
753                         // catch(final std::exception& ex)
754                         // {
755                         // std::cerr << G_STRFUNC << ": exception: " << ex.what() << std::endl;
756                         // HandleError(ex);
757                         // }
758
759                 } // for(tables)
760
761                 return true; // All tables created successfully.
762         }
763
764         /**
765          * @return
766          * @throws SQLException
767          */
768         private Connection createConnection() {
769                 final Properties connectionProps = new Properties();
770                 connectionProps.put("user", this.username);
771                 connectionProps.put("password", this.password);
772
773                 String jdbcURL = "jdbc:postgresql://" + document.getConnectionServer() + ":" + document.getConnectionPort();
774                 String db = document.getConnectionDatabase();
775                 if (StringUtils.isEmpty(db)) {
776                         // Use the default PostgreSQL database, because ComboPooledDataSource.connect() fails otherwise.
777                         db = "template1";
778                 }
779                 jdbcURL += "/" + db; // TODO: Quote the database name?
780
781                 Connection conn = null;
782                 try {
783                         conn = DriverManager.getConnection(jdbcURL + "/", connectionProps);
784                 } catch (final SQLException e) {
785                         //e.printStackTrace();
786                         return null;
787                 }
788
789                 return conn;
790         }
791
792         /**
793          *
794          */
795         private void progress() {
796                 // TODO Auto-generated method stub
797
798         }
799
800         /**
801          * @param document
802          * @param tableName
803          * @return
804          */
805         private boolean insertExampleData(final Connection connection, final Document document, final String tableName) {
806
807                 final Factory factory = new Factory(connection, SQLDialect.POSTGRES);
808                 final Table<Record> table = Factory.tableByName(tableName);
809
810                 final List<Map<String, DataItem>> exampleRows = document.getExampleRows(tableName);
811                 for (final Map<String, DataItem> row : exampleRows) {
812                         InsertSetStep<Record> insertStep = factory.insertInto(table);
813
814                         for (final Entry<String, DataItem> entry : row.entrySet()) {
815                                 final String fieldName = entry.getKey();
816                                 final DataItem value = entry.getValue();
817                                 if (value == null) {
818                                         continue;
819                                 }
820
821                                 final Field field = document.getField(tableName, fieldName);
822                                 if (field == null) {
823                                         continue;
824                                 }
825
826                                 final org.jooq.Field<Object> jooqField = Factory.fieldByName(field.getName());
827                                 if (jooqField == null) {
828                                         continue;
829                                 }
830
831                                 final Object fieldValue = value.getValue(field.getGlomType());
832                                 insertStep = insertStep.set(jooqField, fieldValue);
833                         }
834
835                         if (!(insertStep instanceof InsertResultStep<?>)) {
836                                 continue;
837                         }
838
839                         // We suppress the warning because we _do_ check the cast above.
840                         @SuppressWarnings("unchecked")
841                         final InsertResultStep<Record> insertResultStep = (InsertResultStep<Record>) insertStep;
842
843                         try {
844                                 insertResultStep.fetchOne();
845                         } catch (final DataAccessException e) {
846                                 // e.printStackTrace();
847                                 return false;
848                         }
849                         // TODO: Check that it worked.
850                 }
851
852                 return true;
853         }
854
855         /**
856          * @param document2
857          * @return
858          */
859         private boolean setTablePrivilegesGroupsFromDocument(final Document document2) {
860                 // TODO Auto-generated method stub
861                 return true;
862         }
863
864         /**
865          * @param document2
866          * @return
867          */
868         private boolean addGroupsFromDocument(final Document document2) {
869                 // TODO Auto-generated method stub
870                 return true;
871         }
872
873         /**
874          * @param document
875          * @param tableName
876          * @param fields
877          * @return
878          */
879         private boolean createTable(final Connection connection, final Document document, final String tableName,
880                         final List<Field> fields) {
881                 boolean tableCreationSucceeded = false;
882
883                 /*
884                  * TODO: //Create the standard field too: //(We don't actually use this yet) if(std::find_if(fields.begin(),
885                  * fields.end(), predicate_FieldHasName<Field>(GLOM_STANDARD_FIELD_LOCK)) == fields.end()) { sharedptr<Field>
886                  * field = sharedptr<Field>::create(); field->set_name(GLOM_STANDARD_FIELD_LOCK);
887                  * field->set_glom_type(Field::TYPE_TEXT); fields.push_back(field); }
888                  */
889
890                 // Create SQL to describe all fields in this table:
891                 String sqlFields = "";
892                 for (final Field field : fields) {
893                         // Create SQL to describe this field:
894                         String sqlFieldDescription = escapeSqlId(field.getName()) + " " + field.getSqlType();
895
896                         if (field.getPrimaryKey()) {
897                                 sqlFieldDescription += " NOT NULL  PRIMARY KEY";
898                         }
899
900                         // Append it:
901                         if (!StringUtils.isEmpty(sqlFields)) {
902                                 sqlFields += ", ";
903                         }
904
905                         sqlFields += sqlFieldDescription;
906                 }
907
908                 if (StringUtils.isEmpty(sqlFields)) {
909                         // TODO: std::cerr << G_STRFUNC << ": sql_fields is empty." << std::endl;
910                 }
911
912                 // Actually create the table
913                 final String query = "CREATE TABLE " + escapeSqlId(tableName) + " (" + sqlFields + ");";
914                 final Factory factory = new Factory(connection, SQLDialect.POSTGRES);
915                 factory.execute(query);
916                 tableCreationSucceeded = true;
917                 if (!tableCreationSucceeded) {
918                         System.out.println("recreatedDatabase(): CREATE TABLE() failed.");
919                 }
920
921                 return tableCreationSucceeded;
922         }
923
924         /**
925          * @param name
926          * @return
927          */
928         private String escapeSqlId(final String name) {
929                 // TODO:
930                 return "\"" + name + "\"";
931         }
932
933         /**
934          * @return
935          */
936         private static boolean createDatabase(final Connection connection, final String databaseName) {
937
938                 final String query = "CREATE DATABASE \"" + databaseName + "\""; // TODO: Escaping.
939                 final Factory factory = new Factory(connection, SQLDialect.POSTGRES);
940
941                 factory.execute(query);
942
943                 return true;
944         }
945
946         /**
947          *
948          */
949         public boolean cleanup() {
950                 boolean result = true;
951
952                 // Stop the server:
953                 if ((document != null) && (document.getConnectionPort() != 0)) {
954                         final String dbDirData = getSelfHostingDataPath(false);
955
956                         // -D specifies the data directory.
957                         // -c config_file= specifies the configuration file
958                         // -k specifies a directory to use for the socket. This must be writable by us.
959                         // We use "-m fast" instead of the default "-m smart" because that waits for clients to disconnect (and
960                         // sometimes never succeeds).
961                         // TODO: Warn about connected clients on other computers? Warn those other users?
962                         // Make sure to use double quotes for the executable path, because the
963                         // CreateProcess() API used on Windows does not support single quotes.
964                         final String commandPath = getPathToPostgresExecutable("pg_ctl");
965                         if(StringUtils.isEmpty(commandPath)) {
966                                 System.out.println("cleanup(): getPathToPostgresExecutable(pg_ctl) failed.");
967                         } else {
968                                 final ProcessBuilder commandPostgresStop = new ProcessBuilder(commandPath, "-D"
969                                                 + shellQuote(dbDirData), "stop", "-m", "fast");
970                                 result = executeCommandLineAndWait(commandPostgresStop);
971                                 if (!result) {
972                                         System.out.println("cleanup(): Failed to stop the PostgreSQL server.");
973                                 }
974                         }
975
976                         document.setConnectionPort(0);
977                 }
978
979                 // Delete the files:
980                 final String selfhostingPath = getSelfHostingPath("", false);
981                 final File fileSelfHosting = new File(selfhostingPath);
982                 fileSelfHosting.delete();
983
984                 final String docPath = document.getFileURI();
985                 final File fileDoc = new File(docPath);
986                 fileDoc.delete();
987                 
988                 return result;
989         }
990 }