Java Code Examples for org.apache.maven.settings.Server#getUsername()

The following examples show how to use org.apache.maven.settings.Server#getUsername() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MavenUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static List<RegistryServerConfiguration> getRegistryServerFromMavenSettings(Settings settings) {
    List<RegistryServerConfiguration> registryServerConfigurations = new ArrayList<>();
    for (Server server : settings.getServers()) {
        if (server.getUsername() != null) {
            registryServerConfigurations.add(RegistryServerConfiguration.builder()
                    .id(server.getId())
                    .username(server.getUsername())
                    .password(server.getPassword())
                    .configuration(MavenConfigurationExtractor.extract((Xpp3Dom) server.getConfiguration()))
                    .build());
        }
    }
    return registryServerConfigurations;
}
 
Example 2
Source File: ConfigurationHelper.java    From LicenseScout with Apache License 2.0 5 votes vote down vote up
/**
 * Converts Maven database configuration to execution database configuration.
 * 
 * <p>This resolves the server definition given by ID from the settings and takes the DB connection
 * credentials from there.</p>
 * 
 * @param databaseConfiguration
 * @param settings the settings.xml object
 * @param log the logger
 * @return a database configuration for the execution engine
 * @throws MojoExecutionException if the server ID is not found in settings, or username or password are not specified in the server definition
 */
public static ExecutionDatabaseConfiguration getExecutionDatabaseConfiguration(final DatabaseConfiguration databaseConfiguration,
                                                                               final Settings settings,
                                                                               final ILSLog log)
        throws MojoExecutionException {
    if (databaseConfiguration == null) {
        return null;
    }
    final ExecutionDatabaseConfiguration executionDatabaseConfiguration = new ExecutionDatabaseConfiguration();
    executionDatabaseConfiguration.setJdbcUrl(databaseConfiguration.getJdbcUrl());
    final String serverId = databaseConfiguration.getServerId();
    log.info("Resolving database server ID: " + serverId);
    final Server server = settings.getServer(serverId);
    if (server == null) {
        throw new MojoExecutionException(
                String.format("No definition found for server ID %s in settings.xml", serverId));
    }
    final String username = server.getUsername();
    final String password = server.getPassword();
    if (username == null) {
        throw new MojoExecutionException(
                String.format("No username defined in server specification with ID %s in settings.xml", serverId));
    }
    if (password == null) {
        throw new MojoExecutionException(
                String.format("No password defined in server specification with ID %s in settings.xml", serverId));
    }
    executionDatabaseConfiguration.setUsername(username);
    executionDatabaseConfiguration.setPassword(password);
    return executionDatabaseConfiguration;
}
 
Example 3
Source File: AbstractHelmMojo.java    From helm-maven-plugin with MIT License 5 votes vote down vote up
/**
 * Get credentials for given helm repo. If username is not provided the repo
 * name will be used to search for credentials in <code>settings.xml</code>.
 *
 * @param repository Helm repo with id and optional credentials.
 * @return Authentication object or <code>null</code> if no credentials are present.
 * @throws IllegalArgumentException Unable to get authentication because of misconfiguration.
 * @throws MojoExecutionException Unable to get password from settings.xml
 */
PasswordAuthentication getAuthentication(HelmRepository repository)
		throws IllegalArgumentException, MojoExecutionException
{
	String id = repository.getName();

	if (repository.getUsername() != null) {
		if (repository.getPassword() == null) {
			throw new IllegalArgumentException("Repo " + id + " has a username but no password defined.");
		}
		getLog().debug("Repo " + id + " has credentials definded, skip searching in server list.");
		return new PasswordAuthentication(repository.getUsername(), repository.getPassword().toCharArray());
	}

	Server server = settings.getServer(id);
	if (server == null) {
		getLog().info("No credentials found for " + id + " in configuration or settings.xml server list.");
		return null;
	}

	getLog().debug("Use credentials from server list for " + id + ".");
	if (server.getUsername() == null || server.getPassword() == null) {
		throw new IllegalArgumentException("Repo "
				+ id
				+ " was found in server list but has no username/password.");
	}

	try {
		return new PasswordAuthentication(server.getUsername(),
				getSecDispatcher().decrypt(server.getPassword()).toCharArray());
	} catch (SecDispatcherException e) {
		throw new MojoExecutionException(e.getMessage());
	}
}
 
Example 4
Source File: AbstractBaseConfluenceMojo.java    From maven-confluence-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Issue 39
 *
 * Load username password from settings if user has not set them in JVM properties
 *
 * @throws MojoExecutionException
 */
private void loadUserInfoFromSettings() throws MojoExecutionException {

    if ((getUsername() == null || getPassword() == null) && (mavenSettings != null)) {
        if (this.serverId == null)
            throw new MojoExecutionException("'serverId' must be set! (username and/or password are not provided)");

        Server server = this.mavenSettings.getServer(this.serverId);

        if (server == null)
            throw new MojoExecutionException(String.format("server with id [%s] not found in settings!", this.serverId));

        if (getUsername() == null && server.getUsername() != null) username = server.getUsername();

        if (getPassword() == null && server.getPassword() != null) {
            try {
                //
                // FIX to resolve
                // org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException:
                // java.io.FileNotFoundException: ~/.settings-security.xml (No such file or directory)
                //
                if (securityDispatcher instanceof DefaultSecDispatcher) {


                    //System.setProperty( DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, sb.toString() );

                    ((DefaultSecDispatcher) securityDispatcher).setConfigurationFile("~/.m2/settings-security.xml");
                }

                password = securityDispatcher.decrypt(server.getPassword());
            } catch (SecDispatcherException e) {
                throw new MojoExecutionException(e.getMessage());
            }
        }
    }
}
 
Example 5
Source File: BaseMojo.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
protected CredentialsProvider getCredentialsProvider(final Log log) throws ValidationException {
    if (serverId != null) {
        Server server = settings.getServer(serverId);
        if (server == null) {
            log.warn(format("No server configuration in Maven settings found with id %s", serverId));
        }
        if (server.getUsername() != null && server.getPassword() != null) {
            return new UsernamePasswordCredentialsProvider(server.getUsername(), server.getPassword());
        }
    }
    return null;
}
 
Example 6
Source File: AuthConfigFactory.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private AuthConfig createAuthConfigFromServer(Server server) throws MojoExecutionException {
    return new AuthConfig(
            server.getUsername(),
            decrypt(server.getPassword()),
            extractFromServerConfiguration(server.getConfiguration(), AuthConfig.AUTH_EMAIL),
            extractFromServerConfiguration(server.getConfiguration(), AuthConfig.AUTH_AUTH)
    );
}
 
Example 7
Source File: AbstractDockerMojo.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the registryAuth object from server details.
 * @return {@link RegistryAuth}
 * @throws MojoExecutionException
 */
protected RegistryAuth registryAuth() throws MojoExecutionException {
  if (settings != null && serverId != null) {
    final Server server = settings.getServer(serverId);
    if (server != null) {
      final RegistryAuth.Builder registryAuthBuilder = RegistryAuth.builder();

      final String username = server.getUsername();
      String password = server.getPassword();
      if (secDispatcher != null) {
        try {
          password = secDispatcher.decrypt(password);
        } catch (SecDispatcherException ex) {
          throw new MojoExecutionException("Cannot decrypt password from settings", ex);
        }
      }
      final String email = getEmail(server);

      if (!isNullOrEmpty(username)) {
        registryAuthBuilder.username(username);
      }
      if (!isNullOrEmpty(email)) {
        registryAuthBuilder.email(email);
      }
      if (!isNullOrEmpty(password)) {
        registryAuthBuilder.password(password);
      }
      if (!isNullOrEmpty(registryUrl)) {
        registryAuthBuilder.serverAddress(registryUrl);
      }

      return registryAuthBuilder.build();
    } else {
      // settings.xml has no entry for the configured serverId, warn the user
      getLog().warn("No entry found in settings.xml for serverId=" + serverId
                    + ", cannot configure authentication for that registry");
    }
  }
  return null;
}
 
Example 8
Source File: JibHelper.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
public void hackyPush(final String tag, final String repository, final String imageName, final Server credentials)
        throws IOException, InterruptedException, MojoExecutionException {
    log
            .warn("Using push workaround for nasty registries (using exec directly on 'docker'), "
                    + "it is highly recommended to not use laggyPushWorkaround configuration if you can");

    if (credentials != null) {
        final File credFile = new File(tempDir, "talend-component-docker-credentials.temp");
        credFile.getParentFile().mkdirs(); // should be useless but just in case
        try (final FileWriter writer = new FileWriter(credFile)) {
            writer.write(credentials.getPassword());
        }
        try {
            final ProcessBuilder processBuilder = new ProcessBuilder("docker", "login", repository, "--username",
                    credentials.getUsername(), "--password-stdin");
            processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
            processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
            processBuilder.redirectInput(ProcessBuilder.Redirect.from(credFile));
            final int exitCode = processBuilder.start().waitFor();
            if (exitCode != 0) {
                log.warn("Can't login, got status: " + exitCode);
            }
        } finally {
            if (!credFile.delete()) {
                credFile.deleteOnExit();
            }
        }
    }

    boolean ok = false;
    for (int i = 0; i < laggyPushWorkaround; i++) {
        final int exit = new ProcessBuilder("docker", "push", imageName).inheritIO().start().waitFor();
        if (exit == 0) {
            ok = true;
            log.info("Pushed image='" + imageName + "', tag='" + tag + "'");
            break;
        } else {
            log.warn("Push #" + (i + 1) + " got " + exit + " exit status");
        }
    }
    if (!ok) {
        throw new MojoExecutionException("Push didn't succeed");
    }
}
 
Example 9
Source File: WebsiteBuilderMojo.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
private void pulishGhPages(final Path root) {
    final Server server = session.getSettings().getServer(githubPagesServerId);
    final Server decryptedServer = ofNullable(server)
            .map(s -> settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(s)))
            .map(SettingsDecryptionResult::getServer)
            .orElse(server);

    final Path gitCloneBase =
            mkdirs(PathFactory.get(project.getBuild().getDirectory()).resolve(UUID.randomUUID().toString()));
    final UsernamePasswordCredentialsProvider credentialsProvider =
            new UsernamePasswordCredentialsProvider(decryptedServer.getUsername(), decryptedServer.getPassword());
    try (final Git git = Git
            .cloneRepository()
            .setCredentialsProvider(credentialsProvider)
            .setURI(githubPagesUrl)
            .setDirectory(gitCloneBase.toFile())
            .setBranchesToClone(singleton(githubPagesBranch))
            .setBranch(githubPagesBranch)
            .call()) {

        // clean up repo
        deleteFolder(gitCloneBase);

        // copy new files
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
                final String relative = root.relativize(file).toString();
                final Path target = gitCloneBase.resolve(relative);
                mkdirs(target.getParent());
                Files.copy(file, target);
                return super.visitFile(file, attrs);
            }
        });

        final String message =
                "Updating the website with version " + project.getVersion() + " // " + new Date().toString();
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage(message).call();
        git.status().call();
        git.push().setCredentialsProvider(credentialsProvider).add(githubPagesBranch).call();
        getLog().info("Updated the website on " + ZonedDateTime.now());
    } catch (final GitAPIException | IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 10
Source File: AbstractUnleashMojo.java    From unleash-maven-plugin with Eclipse Public License 1.0 4 votes vote down vote up
private Authentication createServerAuthentication(Server server) {
  Authentication authentication = new Authentication(server.getUsername(), server.getPassword());
  authentication.setPrivateKey(server.getPrivateKey());
  authentication.setPassphrase(server.getPassphrase());
  return authentication;
}
 
Example 11
Source File: AbstractServerConnection.java    From wildfly-maven-plugin with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Gets a client configuration used to create a new {@link ModelControllerClient}.
 *
 * @return the configuration to use
 */
protected synchronized MavenModelControllerClientConfiguration getClientConfiguration() {
    final Log log = getLog();
    String username = this.username;
    String password = this.password;
    if (username == null && password == null) {
        if (id != null) {
            if (settings != null) {
                Server server = settings.getServer(id);
                if (server != null) {
                    log.debug(DEBUG_MESSAGE_SETTINGS_HAS_ID);
                    password = decrypt(server);
                    username = server.getUsername();
                    if (username != null && password != null) {
                        log.debug(DEBUG_MESSAGE_SETTINGS_HAS_CREDS);
                    } else {
                        log.debug(DEBUG_MESSAGE_NO_CREDS);
                    }
                } else {
                    log.debug(DEBUG_MESSAGE_NO_SERVER_SECTION);
                }
            } else {
                log.debug(DEBUG_MESSAGE_NO_SETTINGS_FILE);
            }
        } else {
            log.debug(DEBUG_MESSAGE_NO_ID);
        }
    } else {
        log.debug(DEBUG_MESSAGE_POM_HAS_CREDS);
    }
    final ModelControllerClientConfiguration.Builder builder = new ModelControllerClientConfiguration.Builder()
            .setProtocol(protocol)
            .setHostName(hostname)
            .setPort(port)
            .setConnectionTimeout(timeout * 1000);
    if (authenticationConfig != null) {
        try {
            builder.setAuthenticationConfigUri(authenticationConfig.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException("Failed to create URI from " + authenticationConfig, e);
        }
    }
    return new MavenModelControllerClientConfiguration(builder.build(), username, password);
}