use of org.apache.maven.wagon.authentication.AuthenticationInfo in project querydsl by querydsl.
the class AbstractMetaDataExportMojo method execute.
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (isForTest()) {
project.addTestCompileSourceRoot(targetFolder);
} else {
project.addCompileSourceRoot(targetFolder);
}
if (skip) {
return;
}
try {
Configuration configuration = new Configuration(SQLTemplates.DEFAULT);
NamingStrategy namingStrategy;
if (namingStrategyClass != null) {
namingStrategy = (NamingStrategy) Class.forName(namingStrategyClass).newInstance();
} else {
namingStrategy = new DefaultNamingStrategy();
}
// defaults for Scala
if (createScalaSources) {
if (serializerClass == null) {
serializerClass = "com.querydsl.scala.sql.ScalaMetaDataSerializer";
}
if (exportBeans && beanSerializerClass == null) {
beanSerializerClass = "com.querydsl.scala.ScalaBeanSerializer";
}
}
MetaDataExporter exporter = new MetaDataExporter();
exporter.setNamePrefix(emptyIfSetToBlank(namePrefix));
exporter.setNameSuffix(StringUtils.nullToEmpty(nameSuffix));
exporter.setBeanPrefix(StringUtils.nullToEmpty(beanPrefix));
exporter.setBeanSuffix(StringUtils.nullToEmpty(beanSuffix));
if (beansTargetFolder != null) {
exporter.setBeansTargetFolder(new File(beansTargetFolder));
}
exporter.setCreateScalaSources(createScalaSources);
exporter.setPackageName(packageName);
exporter.setBeanPackageName(beanPackageName);
exporter.setInnerClassesForKeys(innerClassesForKeys);
exporter.setTargetFolder(new File(targetFolder));
exporter.setNamingStrategy(namingStrategy);
exporter.setCatalogPattern(catalogPattern);
exporter.setSchemaPattern(processBlankValues(schemaPattern));
exporter.setTableNamePattern(tableNamePattern);
exporter.setColumnAnnotations(columnAnnotations);
exporter.setValidationAnnotations(validationAnnotations);
exporter.setSchemaToPackage(schemaToPackage);
exporter.setLowerCase(lowerCase);
exporter.setExportTables(exportTables);
exporter.setExportViews(exportViews);
exporter.setExportAll(exportAll);
exporter.setTableTypesToExport(tableTypesToExport);
exporter.setExportPrimaryKeys(exportPrimaryKeys);
exporter.setExportForeignKeys(exportForeignKeys);
exporter.setExportDirectForeignKeys(exportDirectForeignKeys);
exporter.setExportInverseForeignKeys(exportInverseForeignKeys);
exporter.setSpatial(spatial);
exporter.setGeneratedAnnotationClass(generatedAnnotationClass);
if (imports != null && imports.length > 0) {
exporter.setImports(imports);
}
if (serializerClass != null) {
try {
exporter.setSerializerClass((Class) Class.forName(serializerClass));
} catch (ClassNotFoundException e) {
getLog().error(e);
throw new MojoExecutionException(e.getMessage(), e);
}
}
if (exportBeans) {
if (beanSerializerClass != null) {
exporter.setBeanSerializerClass((Class) Class.forName(beanSerializerClass));
} else {
BeanSerializer serializer = new BeanSerializer();
if (beanInterfaces != null) {
for (String iface : beanInterfaces) {
int sepIndex = iface.lastIndexOf('.');
if (sepIndex < 0) {
serializer.addInterface(new SimpleType(iface));
} else {
String packageName = iface.substring(0, sepIndex);
String simpleName = iface.substring(sepIndex + 1);
serializer.addInterface(new SimpleType(iface, packageName, simpleName));
}
}
}
serializer.setAddFullConstructor(beanAddFullConstructor);
serializer.setAddToString(beanAddToString);
serializer.setPrintSupertype(beanPrintSupertype);
exporter.setBeanSerializer(serializer);
}
}
String sourceEncoding = (String) project.getProperties().get("project.build.sourceEncoding");
if (sourceEncoding != null) {
exporter.setSourceEncoding(sourceEncoding);
}
if (customTypes != null) {
for (String cl : customTypes) {
configuration.register((Type<?>) Class.forName(cl).newInstance());
}
}
if (typeMappings != null) {
for (TypeMapping mapping : typeMappings) {
mapping.apply(configuration);
}
}
if (numericMappings != null) {
for (NumericMapping mapping : numericMappings) {
mapping.apply(configuration);
}
}
if (renameMappings != null) {
for (RenameMapping mapping : renameMappings) {
mapping.apply(configuration);
}
}
if (columnComparatorClass != null) {
try {
exporter.setColumnComparatorClass((Class) Class.forName(this.columnComparatorClass).asSubclass(Comparator.class));
} catch (ClassNotFoundException e) {
getLog().error(e);
throw new MojoExecutionException(e.getMessage(), e);
}
}
exporter.setConfiguration(configuration);
Class.forName(jdbcDriver);
String user;
String password;
if (server == null) {
user = jdbcUser;
password = jdbcPassword;
} else {
AuthenticationInfo info = wagonManager.getAuthenticationInfo(server);
if (info == null) {
throw new MojoExecutionException("No authentication info for server " + server);
}
user = info.getUserName();
if (user == null) {
throw new MojoExecutionException("Missing username from server " + server);
}
password = info.getPassword();
if (password == null) {
throw new MojoExecutionException("Missing password from server " + server);
}
}
try (Connection conn = DriverManager.getConnection(jdbcUrl, user, password)) {
exporter.export(conn.getMetaData());
}
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
use of org.apache.maven.wagon.authentication.AuthenticationInfo in project maven-plugins by apache.
the class DefaultRepositoryCopier method copy.
public void copy(Repository sourceRepository, Repository targetRepository, String version) throws WagonException, IOException {
String prefix = "staging-plugin";
String fileName = prefix + "-" + version + ".zip";
String tempdir = System.getProperty("java.io.tmpdir");
logger.debug("Writing all output to " + tempdir);
// Create the renameScript script
String renameScriptName = prefix + "-" + version + "-rename.sh";
File renameScript = new File(tempdir, renameScriptName);
// Work directory
File basedir = new File(tempdir, prefix + "-" + version);
FileUtils.deleteDirectory(basedir);
basedir.mkdirs();
Wagon sourceWagon = wagonManager.getWagon(sourceRepository);
AuthenticationInfo sourceAuth = wagonManager.getAuthenticationInfo(sourceRepository.getId());
sourceWagon.connect(sourceRepository, sourceAuth);
logger.info("Looking for files in the source repository.");
List<String> files = new ArrayList<String>();
scan(sourceWagon, "", files);
logger.info("Downloading files from the source repository to: " + basedir);
for (String s : files) {
if (s.contains(".svn")) {
continue;
}
File f = new File(basedir, s);
FileUtils.mkdir(f.getParentFile().getAbsolutePath());
logger.info("Downloading file from the source repository: " + s);
sourceWagon.get(s, f);
}
// ----------------------------------------------------------------------------
// Now all the files are present locally and now we are going to grab the
// metadata files from the targetRepositoryUrl and pull those down locally
// so that we can merge the metadata.
// ----------------------------------------------------------------------------
logger.info("Downloading metadata from the target repository.");
Wagon targetWagon = wagonManager.getWagon(targetRepository);
if (!(targetWagon instanceof CommandExecutor)) {
throw new CommandExecutionException("Wagon class '" + targetWagon.getClass().getName() + "' in use for target repository is not a CommandExecutor");
}
AuthenticationInfo targetAuth = wagonManager.getAuthenticationInfo(targetRepository.getId());
targetWagon.connect(targetRepository, targetAuth);
PrintWriter rw = new PrintWriter(new FileWriter(renameScript));
File archive = new File(tempdir, fileName);
for (String s : files) {
if (s.startsWith("/")) {
s = s.substring(1);
}
if (s.endsWith(MAVEN_METADATA)) {
File emf = new File(basedir, s + IN_PROCESS_MARKER);
try {
targetWagon.get(s, emf);
} catch (ResourceDoesNotExistException e) {
continue;
}
try {
mergeMetadata(emf);
} catch (XmlPullParserException e) {
throw new IOException("Metadata file is corrupt " + s + " Reason: " + e.getMessage());
}
}
}
Set moveCommands = new TreeSet();
// ----------------------------------------------------------------------------
// Create the Zip file that we will deploy to the targetRepositoryUrl stage
// ----------------------------------------------------------------------------
logger.info("Creating zip file.");
OutputStream os = new FileOutputStream(archive);
ZipOutputStream zos = new ZipOutputStream(os);
scanDirectory(basedir, basedir, zos, version, moveCommands);
// ----------------------------------------------------------------------------
// Create the renameScript script. This is as atomic as we can
// ----------------------------------------------------------------------------
logger.info("Creating rename script.");
for (Object moveCommand : moveCommands) {
String s = (String) moveCommand;
// We use an explicit unix '\n' line-ending here instead of using the println() method.
// Using println() will cause files and folders to have a '\r' at the end if the plugin is run on Windows.
rw.print(s + "\n");
}
rw.close();
ZipEntry e = new ZipEntry(renameScript.getName());
zos.putNextEntry(e);
InputStream is = new FileInputStream(renameScript);
IOUtil.copy(is, zos);
zos.close();
is.close();
sourceWagon.disconnect();
// Push the Zip to the target system
logger.info("Uploading zip file to the target repository.");
targetWagon.put(archive, fileName);
logger.info("Unpacking zip file on the target machine.");
String targetRepoBaseDirectory = targetRepository.getBasedir();
// We use the super quiet option here as all the noise seems to kill/stall the connection
String command = "unzip -o -qq -d " + targetRepoBaseDirectory + " " + targetRepoBaseDirectory + "/" + fileName;
((CommandExecutor) targetWagon).executeCommand(command);
logger.info("Deleting zip file from the target repository.");
command = "rm -f " + targetRepoBaseDirectory + "/" + fileName;
((CommandExecutor) targetWagon).executeCommand(command);
logger.info("Running rename script on the target machine.");
command = "cd " + targetRepoBaseDirectory + "; sh " + renameScriptName;
((CommandExecutor) targetWagon).executeCommand(command);
logger.info("Deleting rename script from the target repository.");
command = "rm -f " + targetRepoBaseDirectory + "/" + renameScriptName;
((CommandExecutor) targetWagon).executeCommand(command);
targetWagon.disconnect();
}
use of org.apache.maven.wagon.authentication.AuthenticationInfo in project maven-plugins by apache.
the class RepositoryUtils method dependencyExistsInRepo.
/**
* @param repo not null
* @param artifact not null
* @return <code>true</code> if the artifact exists in the given repo, <code>false</code> otherwise or if
* the repo is blacklisted.
*/
public boolean dependencyExistsInRepo(ArtifactRepository repo, Artifact artifact) {
if (repo.isBlacklisted()) {
if (log.isDebugEnabled()) {
log.debug("The repo '" + repo.getId() + "' is black listed - Ignored it");
}
return false;
}
if (UNKNOWN_HOSTS.contains(repo.getUrl())) {
if (log.isDebugEnabled()) {
log.debug("The repo url '" + repo.getUrl() + "' is unknown - Ignored it");
}
return false;
}
repo = wagonManager.getMirrorRepository(repo);
String id = repo.getId();
Repository repository = new Repository(id, repo.getUrl());
Wagon wagon;
try {
wagon = wagonManager.getWagon(repository);
} catch (UnsupportedProtocolException e) {
logError("Unsupported protocol: '" + repo.getProtocol() + "'", e);
return false;
} catch (WagonConfigurationException e) {
logError("Unsupported protocol: '" + repo.getProtocol() + "'", e);
return false;
}
wagon.setTimeout(1000);
if (log.isDebugEnabled()) {
Debug debug = new Debug();
wagon.addSessionListener(debug);
wagon.addTransferListener(debug);
}
try {
// FIXME when upgrading to maven 3.x : this must be changed.
AuthenticationInfo auth = wagonManager.getAuthenticationInfo(repo.getId());
ProxyInfo proxyInfo = getProxyInfo();
if (proxyInfo != null) {
wagon.connect(repository, auth, proxyInfo);
} else {
wagon.connect(repository, auth);
}
return wagon.resourceExists(StringUtils.replace(getDependencyUrlFromRepository(artifact, repo), repo.getUrl(), ""));
} catch (ConnectionException e) {
logError("Unable to connect to: " + repo.getUrl(), e);
return false;
} catch (AuthenticationException e) {
logError("Unable to connect to: " + repo.getUrl(), e);
return false;
} catch (TransferFailedException e) {
if (e.getCause() instanceof UnknownHostException) {
log.error("Unknown host " + e.getCause().getMessage() + " - ignored it");
UNKNOWN_HOSTS.add(repo.getUrl());
} else {
logError("Unable to determine if resource " + artifact + " exists in " + repo.getUrl(), e);
}
return false;
} catch (AuthorizationException e) {
logError("Unable to connect to: " + repo.getUrl(), e);
return false;
} catch (AbstractMethodError e) {
log.error("Wagon " + wagon.getClass().getName() + " does not support the resourceExists method");
return false;
} finally {
try {
wagon.disconnect();
} catch (ConnectionException e) {
logError("Error disconnecting wagon - ignored", e);
}
}
}
use of org.apache.maven.wagon.authentication.AuthenticationInfo in project liquibase by liquibase.
the class AbstractLiquibaseMojo method execute.
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (StringUtil.trimToNull(logging) != null) {
getLog().error("The liquibase-maven-plugin now manages logging via the standard maven logging config, not the 'logging' configuration. Use the -e, -X or -q flags or see https://maven.apache.org/maven-logging.html");
}
try {
Scope.child(Scope.Attr.logService, new MavenLogService(getLog()), () -> {
getLog().info(MavenUtils.LOG_SEPARATOR);
if (server != null) {
AuthenticationInfo info = wagonManager.getAuthenticationInfo(server);
if (info != null) {
username = info.getUserName();
password = info.getPassword();
}
}
processSystemProperties();
if (!LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentValue()) {
getLog().info("Liquibase did not run because " + LiquibaseCommandLineConfiguration.SHOULD_RUN.getKey() + " was set to false");
return;
}
if (skip) {
getLog().warn("Liquibase skipped due to Maven configuration");
return;
}
ClassLoader mavenClassLoader = getClassLoaderIncludingProjectClasspath();
Map<String, Object> scopeValues = new HashMap<>();
scopeValues.put(Scope.Attr.resourceAccessor.name(), getResourceAccessor(mavenClassLoader));
scopeValues.put(Scope.Attr.classLoader.name(), getClassLoaderIncludingProjectClasspath());
IntegrationDetails integrationDetails = new IntegrationDetails();
integrationDetails.setName("maven");
final PluginDescriptor pluginDescriptor = (PluginDescriptor) getPluginContext().get("pluginDescriptor");
for (MojoDescriptor descriptor : pluginDescriptor.getMojos()) {
if (!descriptor.getImplementationClass().equals(this.getClass())) {
continue;
}
for (Parameter param : descriptor.getParameters()) {
final String name = param.getName();
if (name.equalsIgnoreCase("project") || name.equalsIgnoreCase("systemProperties")) {
continue;
}
final Field field = getField(this.getClass(), name);
if (field == null) {
getLog().debug("Cannot read current maven value for. Will not send the value to hub " + name);
} else {
field.setAccessible(true);
final Object value = field.get(this);
if (value != null) {
try {
integrationDetails.setParameter("maven__" + param.getName().replaceAll("[${}]", ""), String.valueOf(value));
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}
}
scopeValues.put("integrationDetails", integrationDetails);
final Map pluginContext = this.getPluginContext();
System.out.println(pluginContext.keySet());
Scope.child(scopeValues, () -> {
configureFieldsAndValues();
//
// Check for a LiquibasePro license
//
hasProLicense = MavenUtils.checkProLicense(liquibaseProLicenseKey, commandName, getLog());
getLog().info(CommandLineUtils.getBanner());
// Displays the settings for the Mojo depending of verbosity mode.
displayMojoSettings();
// Check that all the parameters that must be specified have been by the user.
checkRequiredParametersAreSpecified();
Database database = null;
try {
String dbPassword = (emptyPassword || (password == null)) ? "" : password;
String driverPropsFile = (driverPropertiesFile == null) ? null : driverPropertiesFile.getAbsolutePath();
database = CommandLineUtils.createDatabaseObject(mavenClassLoader, url, username, dbPassword, driver, defaultCatalogName, defaultSchemaName, outputDefaultCatalog, outputDefaultSchema, databaseClass, driverPropsFile, propertyProviderClass, changelogCatalogName, changelogSchemaName, databaseChangeLogTableName, databaseChangeLogLockTableName);
liquibase = createLiquibase(database);
configureChangeLogProperties();
getLog().debug("expressionVars = " + String.valueOf(expressionVars));
if (expressionVars != null) {
for (Map.Entry<Object, Object> var : expressionVars.entrySet()) {
this.liquibase.setChangeLogParameter(var.getKey().toString(), var.getValue());
}
}
getLog().debug("expressionVariables = " + String.valueOf(expressionVariables));
if (expressionVariables != null) {
for (Map.Entry var : (Set<Map.Entry>) expressionVariables.entrySet()) {
if (var.getValue() != null) {
this.liquibase.setChangeLogParameter(var.getKey().toString(), var.getValue());
}
}
}
if (clearCheckSums) {
getLog().info("Clearing the Liquibase checksums on the database");
liquibase.clearCheckSums();
}
getLog().info("Executing on Database: " + url);
if (isPromptOnNonLocalDatabase()) {
getLog().info("NOTE: The promptOnLocalDatabase functionality has been removed");
}
setupBindInfoPackage();
performLiquibaseTask(liquibase);
} catch (LiquibaseException e) {
cleanup(database);
throw new MojoExecutionException("\nError setting up or running Liquibase:\n" + e.getMessage(), e);
}
cleanup(database);
getLog().info(MavenUtils.LOG_SEPARATOR);
getLog().info("");
});
});
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
use of org.apache.maven.wagon.authentication.AuthenticationInfo in project liquibase by liquibase.
the class LiquibaseDatabaseDiff method execute.
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.referenceServer != null) {
AuthenticationInfo referenceInfo = wagonManager.getAuthenticationInfo(referenceServer);
if (referenceInfo != null) {
referenceUsername = referenceInfo.getUserName();
referencePassword = referenceInfo.getPassword();
}
}
super.execute();
}
Aggregations