org.fao.geonet.lib.Lib.db - java examples

Here are the examples of the java api org.fao.geonet.lib.Lib.db taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3 Examples 7

17 View Complete Implementation : DatabaseMigration.java
Copyright GNU General Public License v2.0
Author : geonetwork
boolean doMigration(String webappVersion, String subVersion, ServletContext servletContext, Path path, Connection conn, Statement statement) throws Exception {
    // Get db version and subversion
    Pair<String, String> dbVersionInfo = getDatabaseVersion(statement);
    String dbVersion = dbVersionInfo.one();
    String dbSubVersion = dbVersionInfo.two();
    boolean anyMigrationError = false;
    // Migrate db if needed
    _logger.info("      Webapp   version:" + webappVersion + " subversion:" + subVersion);
    _logger.info("      Database version:" + dbVersion + " subversion:" + dbSubVersion);
    if (dbVersion == null) {
        _logger.warning("      Unable to retrieve the current GeoNetwork version from the database. " + "If this is an initial run of the software, then the database will be auto-populated. " + "Else check that the database is properly configured");
        return true;
    } else if (webappVersion == null) {
        _logger.warning("      Unable to retrieve the GeoNetwork version from the application code.");
        return true;
    }
    Version from = new Version(), to = new Version();
    try {
        from = parseVersionNumber(dbVersion);
    } catch (Exception e) {
        _logger.warning("      Error parsing the GeoNetwork version (" + dbVersion + "." + dbSubVersion + ") from the database: " + e.getMessage());
        _logger.error(e);
    }
    try {
        to = parseVersionNumber(webappVersion);
    } catch (Exception e) {
        _logger.warning("      Error parsing GeoNetwork version (" + webappVersion + "." + subVersion + ") from the application code: " + e.getMessage());
        _logger.error(e);
    }
    switch(from.compareTo(to)) {
        case 1:
            _logger.info("      Running on a newer database version.");
            break;
        case 0:
            _logger.info("      Application version equals the Database version, no migration task to apply.");
            break;
        case -1:
            boolean anyMigrationAction = false;
            // Migrating from 2.0 to 2.5 could be done 2.0 -> 2.3 -> 2.4 -> 2.5
            String dbType = DatabaseType.lookup(conn).toString();
            _logger.debug("      Migrating from " + from + " to " + to + " (dbtype:" + dbType + ")...");
            _logger.info("      Loading SQL migration step configuration from <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n ...");
            for (Map.Entry<String, List<String>> migrationEntry : _migration.call().entrySet()) {
                Version versionNumber = parseVersionNumber(migrationEntry.getKey());
                if (versionNumber.compareTo(from) > 0 && versionNumber.compareTo(to) < 1) {
                    _logger.info("       - running tasks for " + versionNumber + "...");
                    for (String file : migrationEntry.getValue()) {
                        if (file.startsWith(JAVA_MIGRATION_PREFIX)) {
                            anyMigrationAction = true;
                            anyMigrationError |= runJavaMigration(conn, file);
                        } else {
                            int lastSep = file.lastIndexOf('/');
                            replacedert.isTrue(lastSep > -1, file + " has the wrong format");
                            Path filePath = path.resolve(file.substring(0, lastSep));
                            String filePrefix = file.substring(lastSep + 1);
                            anyMigrationAction = true;
                            _logger.info("         - SQL migration file:" + filePath + " prefix:" + filePrefix + " ...");
                            try {
                                Lib.db.insertData(servletContext, statement, path, filePath, filePrefix);
                            } catch (Exception e) {
                                _logger.info("          Errors occurs during SQL migration file: " + e.getMessage());
                                _logger.error(e);
                                anyMigrationError = true;
                            }
                        }
                    }
                }
            }
            if (anyMigrationAction && !anyMigrationError) {
                _logger.info("      Successfull migration.\n" + "      Catalogue administrator still need to update the catalogue\n" + "      logo and data directory in order to complete the migration process.\n" + "      Lucene index rebuild is also recommended after migration.");
            }
            if (!anyMigrationAction) {
                _logger.warning("      No migration task found between webapp and database version.\n" + "      The system may be unstable or may failed to start if you try to run \n" + "      the current GeoNetwork " + webappVersion + " with an older database (ie. " + dbVersion + "\n" + "      ). Try to run the migration task manually on the current database\n" + "      before starting the application or start with a new empty database.\n" + "      Sample SQL scripts for migration could be found in WEB-INF/sql/migrate folder.\n");
            }
            if (anyMigrationError) {
                _logger.warning("      Error occurs during migration. Check the log file for more details.");
            }
            // TODO : Maybe some migration stuff has to be done in Java ?
            break;
        default:
            throw new Error("Unrecognized value: " + to.compareTo(from) + " when comparing " + to + " -> " + from);
    }
    return anyMigrationError;
}

13 View Complete Implementation : LanguagesApi.java
Copyright GNU General Public License v2.0
Author : geonetwork
@ApiOperation(value = "Add a language", notes = "Add all default translations from all *Desc tables in the database. " + "This operation will only add translations for a default catalog installation. " + "Defaults can be customized in SQL scripts located in " + "WEB-INF/clreplacedes/setup/sql/data/*.", authorizations = { @Authorization(value = "basicAuth") }, nickname = "addLanguage")
@RequestMapping(value = "/{langCode}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.CREATED)
@PreAuthorize("hasRole('Administrator')")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Language translations added."), @ApiResponse(code = 404, message = "Resource not found. eg. No SQL file available for that langugae."), @ApiResponse(code = 403, message = "Operation not allowed. Only Administrator can access it.") })
public void addLanguages(@ApiParam(value = ApiParams.API_PARAM_ISO_3_LETTER_CODE, required = true) @PathVariable String langCode, @ApiIgnore HttpServletRequest request) throws IOException, ResourceNotFoundException {
    Language lang = languageRepository.findOne(langCode);
    if (lang == null) {
        String languageDataFile = "loc-" + langCode + "-default.sql";
        Path templateFile = dataDirectory.getWebappDir().resolve("WEB-INF").resolve("clreplacedes").resolve("setup").resolve("sql").resolve("data").resolve(languageDataFile);
        if (Files.exists(templateFile)) {
            List<String> data = new ArrayList<>();
            try (BufferedReader br = new BufferedReader(new FileReader(templateFile.toFile()))) {
                String line;
                while ((line = br.readLine()) != null) {
                    data.add(line);
                }
            }
            if (data.size() > 0) {
                ServiceContext context = ApiUtils.createServiceContext(request);
                Lib.db.runSQL(context, data);
                return;
            }
        }
        throw new ResourceNotFoundException(String.format("Language data file '%s' not found in clreplacedes/setup/sql/data.", languageDataFile));
    } else {
        throw new RuntimeException(String.format("Language '%s' already available.", lang.getId()));
    }
}

12 View Complete Implementation : LanguagesApi.java
Copyright GNU General Public License v2.0
Author : geonetwork
@ApiOperation(value = "Remove a language", notes = "Delete all translations from all *Desc tables in the database. " + "Warning: This will also remove all translations you may have done " + "to those objects (eg. custom groups).", authorizations = { @Authorization(value = "basicAuth") }, nickname = "deleteLanguage")
@RequestMapping(value = "/{langCode}", method = RequestMethod.DELETE)
@PreAuthorize("hasRole('Administrator')")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiResponses(value = { @ApiResponse(code = 204, message = "Language translations removed."), @ApiResponse(code = 404, message = "Resource not found."), @ApiResponse(code = 403, message = "Operation not allowed. Only Administrator can access it.") })
public void deleteLanguage(@ApiParam(value = ApiParams.API_PARAM_ISO_3_LETTER_CODE, required = true) @PathVariable String langCode, HttpServletRequest request) throws IOException, ResourceNotFoundException {
    Language lang = languageRepository.findOne(langCode);
    if (lang == null) {
        throw new ResourceNotFoundException(String.format("Language '%s' not found.", langCode));
    } else {
        final String LANGUAGE_DELETE_SQL = "language-delete.sql";
        Path templateFile = dataDirectory.getWebappDir().resolve("WEB-INF").resolve("clreplacedes").resolve("setup").resolve("sql").resolve("template").resolve(LANGUAGE_DELETE_SQL);
        if (Files.exists(templateFile)) {
            List<String> data = new ArrayList<>();
            try (BufferedReader br = new BufferedReader(new FileReader(templateFile.toFile()))) {
                String line;
                while ((line = br.readLine()) != null) {
                    data.add(String.format(line, lang.getId()));
                }
            }
            if (data.size() > 0) {
                ServiceContext context = ApiUtils.createServiceContext(request);
                Lib.db.runSQL(context, data);
                return;
            }
        }
        throw new ResourceNotFoundException(String.format("Template file '%s' not found in clreplacedes/setup/sql/template.", LANGUAGE_DELETE_SQL));
    }
}