Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.apache.maven.continuum.management;
  
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
  * with the License.  You may obtain a copy of the License at
  *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
An application for performing database upgrades from old Continuum and Redback versions. A suitable tool until it is natively incorporated into Continuum itself.

Version:
$Id: DataManagementCli.java 1372260 2012-08-13 04:29:09Z brett $
 
 public class DataManagementCli
 {
     private static final Logger LOGGER = Logger.getLoggerDataManagementCli.class );
 
     private static final String JAR_FILE_PREFIX = "jar:file:";
 
     private static final String FILE_PREFIX = "file:";
 
     private static final String SPRING_CONTEXT_LOC = "!/**/META-INF/spring-context.xml";
 
     private static final String PLEXUS_XML_LOC = "!/**/META-INF/plexus/components.xml";
 
     public static void mainString[] args )
         throws Exception
     {
         Commands command = new Commands();
 
         DatabaseFormat databaseFormat;
         OperationMode mode;
         SupportedDatabase databaseType;
 
        try
        {
            Args.parsecommandargs );
            if ( command.help )
            {
                Args.usagecommand );
                return;
            }
            if ( command.version )
            {
                ..print"continuum-data-management version " + getVersion() );
                return;
            }
            databaseFormat = DatabaseFormat.valueOfcommand.databaseFormat );
            mode = OperationMode.valueOfcommand.mode );
            databaseType = SupportedDatabase.valueOfcommand.databaseType );
        }
        catch ( IllegalArgumentException e )
        {
            ..printlne.getMessage() );
            Args.usagecommand );
            return;
        }
        if ( command.directory.exists() && !command.directory.isDirectory() )
        {
            ..printlncommand.directory + " already exists and is not a directory." );
            Args.usagecommand );
            return;
        }
        if ( !command.overwrite && mode == . && command.directory.exists() )
        {
            ..println(
                command.directory + " already exists and will not be overwritten unless the -overwrite flag is used." );
            Args.usagecommand );
            return;
        }
        if ( command.buildsJdbcUrl == null && command.usersJdbcUrl == null )
        {
            ..println"You must specify one of -buildsJdbcUrl and -usersJdbcUrl" );
            Args.usagecommand );
            return;
        }
        if ( command.usersJdbcUrl != null && databaseFormat == . )
        {
            ..println"The -usersJdbcUrl option can not be used with Continuum 1.0.3 databases" );
            Args.usagecommand );
            return;
        }
        if ( ..equalsdatabaseType ) )
        {
            if ( command.driverClass == null || command.artifactId == null || command.groupId == null ||
                command.artifactVersion == null || command.password == null || command.username == null )
            {
                ..println(
                    "If OTHER databaseType is selected, -driverClass, -artifactId, -groupId, -artifactVersion, -username and -password must be provided together" );
                Args.usagecommand );
                return;
            }
            databaseType.defaultParams = new DatabaseParamscommand.driverClasscommand.groupIdcommand.artifactId,
                                                             command.artifactVersioncommand.username,
                                                             command.password );
        }
        BasicConfigurator.configure();
        if ( command.debug )
        {
            Logger.getRootLogger().setLevel. );
            Logger.getLogger"JPOX" ).setLevel. );
        }
        else
        {
            Logger.getRootLogger().setLevel. );
            Logger.getLogger"JPOX" ).setLevel. );
        }
        if ( command.settings != null && !command.settings.isFile() )
        {
            ..printlncommand.settings + " not exists or is not a file." );
            Args.usagecommand );
            return;
        }
        if ( command.buildsJdbcUrl != null )
        {
            .info"Processing Continuum database..." );
            processDatabasedatabaseTypedatabaseFormatmodecommand.buildsJdbcUrlcommand.directory,
                             command.settingsdatabaseFormat.getContinuumToolRoleHint(), "data-management-jdo",
                             "continuum"command.strict );
        }
        if ( command.usersJdbcUrl != null )
        {
            .info"Processing Redback database..." );
            processDatabasedatabaseTypedatabaseFormatmodecommand.usersJdbcUrlcommand.directory,
                             command.settingsdatabaseFormat.getRedbackToolRoleHint(), "data-management-redback-jdo",
                             "redback"command.strict );
        }
    }
    private static void processDatabaseSupportedDatabase databaseTypeDatabaseFormat databaseFormat,
                                         OperationMode modeString jdbcUrlFile directoryFile setting,
                                         String toolRoleHintString managementArtifactIdString configRoleHint,
                                         boolean strict )
    {
        String applicationVersion = getVersion();
        DatabaseParams params = new DatabaseParamsdatabaseType.defaultParams );
        params.setUrljdbcUrl );
        PlexusClassPathXmlApplicationContext classPathApplicationContext = new PlexusClassPathXmlApplicationContext(
            new String[]{"classpath*:/META-INF/spring-context.xml""classpath*:/META-INF/plexus/components.xml",
                "classpath*:/META-INF/plexus/plexus.xml"} );
        PlexusContainerAdapter container = new PlexusContainerAdapter();
        container.setApplicationContextclassPathApplicationContext );
        initializeWagoncontainersetting );
        List<Artifactartifacts = new ArrayList<Artifact>();
        artifacts.addAlldownloadArtifactcontainerparams.getGroupId(), params.getArtifactId(), params.getVersion(),
                                            setting ) );
        artifacts.addAlldownloadArtifactcontainer"org.apache.continuum"managementArtifactIdapplicationVersion,
                                            setting ) );
        artifacts.addAlldownloadArtifactcontainer"jpox""jpox"databaseFormat.getJpoxVersion(), setting ) );
        List<Stringjars = new ArrayList<String>();
        // Little hack to make it work more nicely in the IDE
        List<Stringexclusions = new ArrayList<String>();
        List<URLjarUrls = new ArrayList<URL>();
        for ( URL url : cp.getURLs() )
        {
            String urlEF = url.toExternalForm();
            if ( urlEF.endsWith"target/classes/" ) )
            {
                int idEndIdx = urlEF.length() - 16;
                String id = urlEF.substringurlEF.lastIndexOf'/'idEndIdx - 1 ) + 1, idEndIdx );
                // continuum-legacy included because the IDE doesn't do the proper assembly of enhanced classes and JDO metadata
                if ( !"data-management-api".equalsid ) && !"data-management-cli".equalsid ) &&
                    !"continuum-legacy".equalsid ) && !"continuum-model".equalsid ) &&
                    !"redback-legacy".equalsid ) )
                {
                    .debug"[IDE Help] Adding '" + id + "' as an exclusion and using one from classpath" );
                    exclusions.add"org.apache.continuum:" + id );
                    jars.addurl.getPath() );
                    jarUrls.addurl );
                }
            }
            // Sometimes finds its way into the IDE. Make sure it is loaded in the extra classloader too
            if ( urlEF.contains"jpox-enhancer" ) )
            {
                .debug"[IDE Help] Adding 'jpox-enhancer' as an exclusion and using one from classpath" );
                jars.addurl.getPath() );
                jarUrls.addurl );
            }
        }
        ArtifactFilter filter = new ExcludesArtifactFilterexclusions );
        for ( Artifact a : artifacts )
        {
            if ( "jpox".equalsa.getGroupId() ) && "jpox".equalsa.getArtifactId() ) )
            {
                if ( a.getVersion().equalsdatabaseFormat.getJpoxVersion() ) )
                {
                    .debug"Adding artifact: " + a.getFile() );
                    jars.add + a.getFile().getAbsolutePath() +  );
                    jars.add + a.getFile().getAbsolutePath() +  );
                    jarUrls.addnew URL + a.getFile().getAbsolutePath() ) );
                }
            }
            else if ( filter.includea ) )
            {
                .debug"Adding artifact: " + a.getFile() );
                jars.add + a.getFile().getAbsolutePath() +  );
                jars.add + a.getFile().getAbsolutePath() +  );
                jarUrls.addnew URL + a.getFile().getAbsolutePath() ) );
            }
        }
        URLClassLoader newClassLoader = new URLClassLoader( (URL[]) jarUrls.toArraynew URL[jarUrls.size()] ), cp );
        Thread.currentThread().setContextClassLoadernewClassLoader );
        classPathApplicationContext.setClassLoadernewClassLoader );
        PlexusFileSystemXmlApplicationContext fileSystemApplicationContext = new PlexusFileSystemXmlApplicationContext(
            (String[]) jars.toArraynew String[jars.size()] ), classPathApplicationContext );
        fileSystemApplicationContext.setClassLoadernewClassLoader );
        container.setApplicationContextfileSystemApplicationContext );
        DatabaseFactoryConfigurator configurator = (DatabaseFactoryConfiguratorcontainer.lookup(
            DatabaseFactoryConfigurator.class.getName(), configRoleHint );
        configurator.configureparams );
        DataManagementTool manager = (DataManagementToolcontainer.lookupDataManagementTool.class.getName(),
                                                                            toolRoleHint );
        if ( mode == . )
        {
            manager.backupDatabasedirectory );
        }
        else if ( mode == . )
        {
            manager.eraseDatabase();
            manager.restoreDatabasedirectorystrict );
        }
    }
    private static void initializeWagonPlexusContainerAdapter containerFile setting )
    {
        WagonManager wagonManager = (WagonManagercontainer.lookup. );
        Settings settings = getSettingscontainersetting );
        try
        {
            Proxy proxy = settings.getActiveProxy();
            if ( proxy != null )
            {
                if ( proxy.getHost() == null )
                {
                    throw new IOException"Proxy in settings.xml has no host" );
                }
                wagonManager.addProxyproxy.getProtocol(), proxy.getHost(), proxy.getPort(), proxy.getUsername(),
                                       proxy.getPassword(), proxy.getNonProxyHosts() );
            }
            for ( Iterator i = settings.getServers().iterator(); i.hasNext(); )
            {
                Server server = (Serveri.next();
                wagonManager.addAuthenticationInfoserver.getId(), server.getUsername(), server.getPassword(),
                                                    server.getPrivateKey(), server.getPassphrase() );
                wagonManager.addPermissionInfoserver.getId(), server.getFilePermissions(),
                                                server.getDirectoryPermissions() );
                if ( server.getConfiguration() != null )
                {
                    wagonManager.addConfigurationserver.getId(), (Xpp3Domserver.getConfiguration() );
                }
            }
            RepositoryPermissions defaultPermissions = new RepositoryPermissions();
            defaultPermissions.setDirectoryMode"775" );
            defaultPermissions.setFileMode"664" );
            wagonManager.setDefaultRepositoryPermissionsdefaultPermissions );
            for ( Iterator i = settings.getMirrors().iterator(); i.hasNext(); )
            {
                Mirror mirror = (Mirrori.next();
                wagonManager.addMirrormirror.getId(), mirror.getMirrorOf(), mirror.getUrl() );
            }
        }
        finally
        {
            container.releasewagonManager );
        }
    }
    private static Collection<ArtifactdownloadArtifactPlexusContainer containerString groupIdString artifactId,
                                                          String versionFile setting )
    {
        ArtifactRepositoryFactory factory = (ArtifactRepositoryFactorycontainer.lookup(
            . );
                                                                                     "default" );
        ArtifactRepository localRepository = factory.createArtifactRepository"local"getLocalRepositoryURL(
            containersetting ), layoutnullnull );
        List<ArtifactRepositoryremoteRepositories = new ArrayList<ArtifactRepository>();
        remoteRepositories.addfactory.createArtifactRepository"central""http://repo1.maven.org/maven2"layout,
                                                                  nullnull ) );
        //Load extra repositories from active profile
        Settings settings = getSettingscontainersetting );
        List<StringprofileIds = settings.getActiveProfiles();
        Map<StringProfileprofilesAsMap = settings.getProfilesAsMap();
        if ( profileIds != null && !profileIds.isEmpty() )
        {
            for ( String profileId : profileIds )
            {
                Profile profile = profilesAsMap.getprofileId );
                if ( profile != null )
                {
                    List<Repositoryrepos = profile.getRepositories();
                    if ( repos != null && !repos.isEmpty() )
                    {
                        for ( Repository repo : repos )
                        {
                            remoteRepositories.addfactory.createArtifactRepositoryrepo.getId(), repo.getUrl(),
                                                                                      layoutnullnull ) );
                        }
                    }
                }
            }
        }
        ArtifactFactory artifactFactory = (ArtifactFactorycontainer.lookup. );
        Artifact artifact = artifactFactory.createArtifactgroupIdartifactIdversion.,
                                                            "jar" );
        Artifact dummyArtifact = artifactFactory.createProjectArtifact"dummy""dummy""1.0" );
        if ( artifact.isSnapshot() )
        {
            remoteRepositories.addfactory.createArtifactRepository"apache.snapshots",
                                                                      "http://people.apache.org/repo/m2-snapshot-repository",
                                                                      layoutnullnull ) );
        }
        ArtifactResolver resolver = (ArtifactResolvercontainer.lookup. );
        List<Stringexclusions = new ArrayList<String>();
        exclusions.add"org.apache.continuum:data-management-api" );
        exclusions.add"org.codehaus.plexus:plexus-component-api" );
        exclusions.add"org.codehaus.plexus:plexus-container-default" );
        exclusions.add"org.slf4j:slf4j-api" );
        exclusions.add"log4j:log4j" );
        ArtifactFilter filter = new ExcludesArtifactFilterexclusions );
        List<? extends ResolutionListenerlisteners;
        if ( .isDebugEnabled() )
        {
            listeners = Collections.singletonListnew DebugResolutionListenercontainer.getLogger() ) );
        }
        else
        {
            listeners = Collections.emptyList();
        }
                                                                                   "maven" );
        ArtifactResolutionResult result = resolver.resolveTransitively( Collections.singletonartifact ),
                                                                        dummyArtifact, Collections.emptyMap(),
                                                                        localRepositoryremoteRepositoriessource,
                                                                        filterlisteners );
        return result.getArtifacts();
    }
    private static String getLocalRepositoryURLPlexusContainer containerFile setting )
        throws ComponentLookupExceptionIOException
    {
        String repositoryPath;
        File settingsFile = new File( System.getProperty"user.home" ), ".m2/settings.xml" );
        if ( setting != null )
        {
            Settings settings = getSettingscontainersetting );
            repositoryPath = new Filesettings.getLocalRepository() ).toURL().toString();
        }
        else if ( !settingsFile.exists() )
        {
            repositoryPath = new File( System.getProperty"user.home" ), ".m2/repository" ).toURL().toString();
        }
        else
        {
            Settings settings = getSettingscontainernull );
            repositoryPath = new Filesettings.getLocalRepository() ).toURL().toString();
        }
        return repositoryPath;
    }
    private static Settings getSettingsPlexusContainer containerFile setting )
        throws ComponentLookupExceptionIOException
    {
        MavenSettingsBuilder mavenSettingsBuilder = (MavenSettingsBuildercontainer.lookup(
            MavenSettingsBuilder.class.getName() );
        try
        {
            if ( setting != null )
            {
                return mavenSettingsBuilder.buildSettingssettingfalse );
            }
            else
            {
                return mavenSettingsBuilder.buildSettingsfalse );
            }
        }
        catch ( XmlPullParserException e )
        {
            e.printStackTrace();
            throw new IOException"Can't read settings.xml. " + e.getMessage() );
        }
    }
    private static String getVersion()
        throws IOException
    {
        Properties properties = new Properties();
        properties.loadDataManagementCli.class.getResourceAsStream(
            "/META-INF/maven/org.apache.continuum/data-management-api/pom.properties" ) );
        return properties.getProperty"version" );
    }
    private static class Commands
    {
        @Argument( description = "Display help information", value = "help", alias = "h" )
        private boolean help;
        @Argument( description = "Display version information", value = "version", alias = "v" )
        private boolean version;
        @Argument(
            description = "The JDBC URL for the Continuum database that contains the data to convert, or to import the data into",
            value = "buildsJdbcUrl" )
        private String buildsJdbcUrl;
        @Argument(
            description = "The JDBC URL for the Redback database that contains the data to convert, or to import the data into",
            value = "usersJdbcUrl" )
        private String usersJdbcUrl;
        // TODO: ability to use the enum directly would be nice
        @Argument(
            description = "Format of the database. Valid values are CONTINUUM_103, CONTINUUM_109, CONTINUUM_11. Default is CONTINUUM_11." )
/* TODO: not yet supported
        @Argument(
            description = "Format of the backup directory. Valid values are CONTINUUM_103, CONTINUUM_109, CONTINUUM_11. Default is CONTINUUM_11.")
        private String dataFileFormat = DatabaseFormat.CONTINUUM_11.toString();
*/
        @Argument(
            description = "The directory to export the data to, or import the data from. Default is 'backups' in the current working directory.",
            value = "directory" )
        private File directory = new File"backups" );
        @Argument(
            description = "Mode of operation. Valid values are IMPORT and EXPORT. Default is EXPORT.",
            value = "mode" )
        private String mode = ..toString();
        @Argument(
            description = "Whether to overwrite the designated directory if it already exists in export mode. Default is false.",
            value = "overwrite" )
        private boolean overwrite;
        @Argument(
            description = "The type of database to use. Currently supported values are DERBY_10_1. The default value is DERBY_10_1.",
            value = "databaseType" )
        @Argument( description = "JDBC driver class", value = "driverClass", required = false )
        private String driverClass;
        @Argument( description = "JDBC driver groupId", value = "groupId", required = false )
        private String groupId;
        @Argument( description = "JDBC driver artifactId", value = "artifactId", required = false )
        private String artifactId;
        @Argument( description = "Artifact version of the JDBC driver class",
                   value = "artifactVersion",
                   required = false )
        private String artifactVersion;
        @Argument( description = "Username", value = "username", required = false )
        private String username;
        @Argument( description = "Password", value = "password", required = false )
        private String password;
        @Argument(
            description = "Turn on debugging information. Default is off.",
            value = "debug" )
        private boolean debug;
        @Argument( description = "Alternate path for the user settings file", value = "settings", required = false,
                   alias = "s" )
        private File settings;
        @Argument( description = "Run on strict mode. Default is false.", value = "strict" )
        private boolean strict;
    }
    private enum OperationMode
    {
        IMPORT, EXPORT
    }
    private enum SupportedDatabase
    {
        DERBY_10_1( new DatabaseParams"org.apache.derby.jdbc.EmbeddedDriver""org.apache.derby""derby""10.1.3.1",
                                        "sa""" ) ),
        OTHER( new DatabaseParamsnullnullnullnullnullnull ) );
        private DatabaseParams defaultParams;
        SupportedDatabaseDatabaseParams defaultParams )
        {
            this. = defaultParams;
        }
    }
New to GrepCode? Check out our FAQ X