@Test public void autoDiscoverWithOneCompleteLocationFromMirrorWithEncryptedPassword() throws NexusDiscoveryException { Settings settings = new Settings(); String url = "http://nexus.somewhere.com/"; testClientManager.testUrl = url; testClientManager.testUser = "******"; testClientManager.testPassword = "******"; Mirror mirror = new Mirror(); mirror.setId("some-mirror"); mirror.setName("A Mirror"); mirror.setUrl(url); settings.addMirror(mirror); Server server = new Server(); server.setId("some-mirror"); server.setUsername("user"); server.setPassword(encryptedPassword); settings.addServer(server); Model model = new Model(); model.setModelVersion("4.0.0"); model.setGroupId("group.id"); model.setArtifactId("artifact-id"); model.setVersion("1"); MavenProject project = new MavenProject(model); discovery.discover(settings, project, "blah", true); }
/** * Get server with given id * * @param settings * @param serverId must be non-null and non-empty * @return server or null if none matching */ protected Server getServer(final Settings settings, final String serverId) { if (settings == null) return null; List<Server> servers = settings.getServers(); if (servers == null || servers.isEmpty()) return null; for (Server server : servers) if (serverId.equals(server.getId())) return server; return null; }
private static RemoteRepository makeRemoteRepository( Metadata.Repository info, Server server, boolean snapshot) { return new RemoteRepository(info.getId(), "default", info.getUri()) .setPolicy( true, new RepositoryPolicy( snapshot, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_FAIL)) .setPolicy( false, new RepositoryPolicy( !snapshot, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_FAIL)) .setAuthentication(new Authentication(server.getUsername(), server.getPassword())); }
public InputStream getInputStream() throws CoreException { if (filePath != null) { File file = new File(filePath); if (file.isFile()) { IMaven maven = MavenPlugin.getDefault().getMaven(); Settings settings = maven.buildSettings(null, filePath); List<Server> servers = settings.getServers(); if (servers != null) { for (Server server : servers) { server.setUsername(obfuscate(server.getUsername())); server.setPassword(obfuscate(server.getPassword())); server.setPassphrase(obfuscate(server.getPassphrase())); } } List<Proxy> proxies = settings.getProxies(); if (proxies != null) { for (Proxy proxy : proxies) { proxy.setUsername(obfuscate(proxy.getUsername())); proxy.setPassword(obfuscate(proxy.getPassword())); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 4); maven.writeSettings(settings, baos); return new ByteArrayInputStream(baos.toByteArray()); } } return null; }
protected Expose exposeSettings(String serverId) throws MojoFailureException { Server server = settings.getServer(serverId); Expose expose = new Expose(); if (null != server) { expose.setServerId(serverId); expose.setAccessKey(server.getUsername()); expose.setSharedKey(getDecryptedAwsKey(server.getPassword().trim())); } else { getLog().warn(format("serverId['%s'] not found. Using runtime defaults", serverId)); expose.setServerId("runtime"); expose.setAccessKey(getAWSCredentials().getCredentials().getAWSAccessKeyId()); expose.setSharedKey(getAWSCredentials().getCredentials().getAWSSecretKey()); } return expose; }
@Test public void autoDiscoverWithOneCompleteLocationFromSnapshotPOMDistMgmt() throws NexusDiscoveryException { Settings settings = new Settings(); String url = "http://nexus.somewhere.com/"; String id = "some-mirror"; String user = "******"; String password = "******"; testClientManager.testUrl = url; testClientManager.testUser = user; testClientManager.testPassword = password; Server server = new Server(); server.setId(id); server.setUsername(user); server.setPassword(password); settings.addServer(server); Model model = new Model(); model.setModelVersion("4.0.0"); model.setGroupId("group.id"); model.setArtifactId("artifact-id"); model.setVersion("1-SNAPSHOT"); DistributionManagement dm = new DistributionManagement(); DeploymentRepository repo = new DeploymentRepository(); repo.setId(id); repo.setUrl(url); dm.setSnapshotRepository(repo); model.setDistributionManagement(dm); MavenProject project = new MavenProject(model); project.setArtifact(factory.create(project)); discovery.discover(settings, project, "blah", true); }
@Test public void autoDiscoverWithOneCompleteLocationFromSettingsProfileRepoWithConfirmation() throws NexusDiscoveryException { Settings settings = new Settings(); String url = "http://nexus.somewhere.com/"; String id = "some-mirror"; String user = "******"; String password = "******"; testClientManager.testUrl = url; testClientManager.testUser = user; testClientManager.testPassword = password; Server server = new Server(); server.setId(id); server.setUsername(user); server.setPassword(password); settings.addServer(server); org.apache.maven.settings.Repository repo = new org.apache.maven.settings.Repository(); repo.setId(id); repo.setUrl(url); repo.setName("Profile Repository"); org.apache.maven.settings.Profile profile = new org.apache.maven.settings.Profile(); profile.addRepository(repo); settings.addProfile(profile); Model model = new Model(); model.setModelVersion("4.0.0"); model.setGroupId("group.id"); model.setArtifactId("artifact-id"); model.setVersion("1"); MavenProject project = new MavenProject(model); prompter.addExpectation("Use this connection?", "y"); discovery.discover(settings, project, "blah", false); }
public void configureAuthentication(String githubAPIServerId, Settings settings, Log log) { boolean configured = false; List<Server> servers = settings.getServers(); for (Server server : servers) { if (server.getId().equals(githubAPIServerId)) { String user = server.getUsername(); String password = server.getPassword(); this.client.setCredentials(user, password); configured = true; break; } } if (!configured) { log.warn("Can't find server id [" + githubAPIServerId + "] configured in githubAPIServerId."); } }
private AuthenticationSelector getAuthSelector() { DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector(); Collection<String> ids = new HashSet<String>(); for (Authentication auth : authentications) { List<String> servers = auth.getServers(); if (!servers.isEmpty()) { org.sonatype.aether.repository.Authentication a = ConverterUtils.toAuthentication(auth); for (String server : servers) { if (ids.add(server)) { selector.add(server, a); } } } } Settings settings = getSettings(); for (Server server : settings.getServers()) { org.sonatype.aether.repository.Authentication auth = new org.sonatype.aether.repository.Authentication( server.getUsername(), server.getPassword(), server.getPrivateKey(), server.getPassphrase()); selector.add(server.getId(), auth); } return new ConservativeAuthenticationSelector(selector); }
/** * @param goals * @param serverProperties * @param module * @param monitor * @return * @throws CoreException */ public static boolean runBuild( List<String> goals, Properties serverProperties, IModule module, IProgressMonitor monitor) throws CoreException { IMaven maven = MavenPlugin.getMaven(); IMavenExecutionContext executionContext = maven.createExecutionContext(); MavenExecutionRequest executionRequest = executionContext.getExecutionRequest(); executionRequest.setPom(getModelFile(module)); if (serverProperties != null && serverProperties.isEmpty() == false) { Server fabric8Server = new Server(); fabric8Server.setId(serverProperties.getProperty(SERVER_ID)); fabric8Server.setUsername(serverProperties.getProperty(SERVER_USER)); fabric8Server.setPassword(serverProperties.getProperty(SERVER_PASSWORD)); executionRequest.addServer(fabric8Server); } executionRequest.setGoals(goals); MavenExecutionResult result = maven.execute(executionRequest, monitor); for (Throwable t : result.getExceptions()) { Activator.getLogger().error(t); } return !result.hasExceptions(); }
@SuppressWarnings("unchecked") protected void uploadAppZip(boolean newUserAdded) throws Exception { File file = getZipFile(); if (!file.exists()) { getLog() .error( "No App Zip file at " + file.getAbsolutePath() + ". Did you execute the fabric8:zip goal?"); return; } if (!file.isFile()) { getLog() .error( "Invalid App Zip file at " + file.getAbsolutePath() + ". This should be a file not a directory!"); return; } String user = fabricServer.getUsername(); String password = fabricServer.getPassword(); if (Strings.isNullOrBlank(user)) { getLog() .warn( "No <username> value defined for the server " + serverId + " in your ~/.m2/settings.xml. Please add a value!"); } if (Strings.isNullOrBlank(password)) { getLog() .warn( "No <password> value defined for the server " + serverId + " in your ~/.m2/settings.xml. Please add a value!"); } Apps.postFileToGit(file, user, password, consoleUrl, branch, deployPath, LOG); }
@Test public void autoDiscoverWithOneCompleteLocationFromPOMRepo() throws NexusDiscoveryException { Settings settings = new Settings(); String url = "http://nexus.somewhere.com/"; String id = "some-mirror"; String user = "******"; String password = "******"; testClientManager.testUrl = url; testClientManager.testUser = user; testClientManager.testPassword = password; Server server = new Server(); server.setId(id); server.setUsername(user); server.setPassword(password); settings.addServer(server); Model model = new Model(); model.setModelVersion("4.0.0"); model.setGroupId("group.id"); model.setArtifactId("artifact-id"); model.setVersion("1"); Repository repo = new Repository(); repo.setId(id); repo.setUrl(url); model.addRepository(repo); MavenProject project = new MavenProject(model); discovery.discover(settings, project, "blah", true); }
/** * Retrieves the credentials for the given server or null if none could be found * * @param serverID * @return */ public Credentials findCredentials(String serverID) { List<Server> decryptedServers = getDecryptedServers(); for (Server ds : decryptedServers) { if (ds.getId().equals(serverID)) { getLog() .debug( "credentials have been found for server: " + serverID + ", login:"******", password:"******"no credentials found for server: " + serverID); return null; }
/** * Configure client with credentials from given server id * * @param client * @param serverId * @param settings * @param session * @return true if configured, false otherwise * @throws MojoExecutionException */ protected boolean configureServerCredentials( final GitHubClient client, final String serverId, final Settings settings, final MavenSession session) throws MojoExecutionException { if (StringUtils.isEmpty(serverId)) return false; String serverUsername = null; String serverPassword = null; // Maven 3.1.0 - It's now impossible to retrieve the username and password from the remote // repository. // if (session != null) { // RepositorySystemSession systemSession = session // .getRepositorySession(); // if (systemSession != null) { // RemoteRepository.Builder builder = new RemoteRepository.Builder(serverId, "", // ""); // Authentication authInfo = // systemSession.getAuthenticationSelector().getAuthentication // (builder.build()); // if (authInfo != null) { // serverUsername = authInfo.getUsername(); // serverPassword = authInfo.getPassword(); // } // } // } // Always true. // if (StringUtils.isEmpty(serverPassword)) { Server server = getServer(settings, serverId); if (server == null) throw new MojoExecutionException( MessageFormat.format("Server ''{0}'' not found in settings", serverId)); if (isDebug()) debug(MessageFormat.format("Using ''{0}'' server credentials", serverId)); serverUsername = server.getUsername(); serverPassword = server.getPassword(); // } if (!StringUtils.isEmpty(serverUsername, serverPassword)) { if (isDebug()) debug("Using basic authentication with username: "******"Using OAuth2 access token authentication"); client.setOAuth2Token(serverPassword); return true; } if (isDebug()) debug( MessageFormat.format( "Server ''{0}'' is missing username/password credentials", serverId)); return false; }
@Override public void execute() throws MojoExecutionException, MojoFailureException { if (isIgnoreProject()) return; try { boolean newUserAdded = false; fabricServer = mavenSettings.getServer(serverId); if (Strings.isNullOrBlank(consoleUrl)) { consoleUrl = DEFAULT_CONSOLE_URL; } // we may have username and password from consoleUrl String jolokiaUsername = null; String jolokiaPassword = null; try { URL url = new URL(consoleUrl); String s = url.getUserInfo(); if (Strings.isNotBlank(s) && s.indexOf(':') > 0) { int idx = s.indexOf(':'); jolokiaUsername = s.substring(0, idx); jolokiaPassword = s.substring(idx + 1); } } catch (MalformedURLException e) { throw new IllegalArgumentException("Option consoleUrl is invalid due " + e.getMessage()); } // jolokia url overrides username/password configured in maven settings if (jolokiaUsername != null) { if (fabricServer == null) { fabricServer = new Server(); } getLog() .info( "Using username: "******" and password from provided consoleUrl option"); fabricServer.setUsername(jolokiaUsername); fabricServer.setPassword(jolokiaPassword); } if (fabricServer == null) { boolean create = false; if (mavenSettings.isInteractiveMode() && mavenSettingsWriter != null) { System.out.println("Maven settings file: " + mavenSettingsFile.getAbsolutePath()); System.out.println(); System.out.println(); System.out.println( "There is no <server> section in your ~/.m2/settings.xml file for the server id: " + serverId); System.out.println(); System.out.println( "You can enter the username/password now and have the settings.xml updated or you can do this by hand if you prefer."); System.out.println(); while (true) { String value = readInput("Would you like to update the settings.xml file now? (y/n): ") .toLowerCase(); if (value.startsWith("n")) { System.out.println(); System.out.println(); break; } else if (value.startsWith("y")) { create = true; break; } } if (create) { System.out.println("Please let us know the login details for this server: " + serverId); System.out.println(); String userName = readInput("Username: "******"Password: "******"Repeat Password: "******"Passwords do not match, please try again."); password = readPassword("Password: "******"Repeat Password: "******".backup-" + counter++ + ".xml"); if (!backupFile.exists()) { System.out.println( "Copied original: " + mavenSettingsFile.getAbsolutePath() + " to: " + backupFile.getAbsolutePath()); Files.copy(mavenSettingsFile, backupFile); break; } } } Map<String, Object> config = new HashMap<String, Object>(); mavenSettingsWriter.write(mavenSettingsFile, config, mavenSettings); System.out.println("Updated settings file: " + mavenSettingsFile.getAbsolutePath()); System.out.println(); newUserAdded = true; } } } if (fabricServer == null) { String message = "No <server> element can be found in ~/.m2/settings.xml for the server <id>" + serverId + "</id> so we cannot connect to fabric8!\n\n" + "Please add the following to your ~/.m2/settings.xml file (using the correct user/password values):\n\n" + "<servers>\n" + " <server>\n" + " <id>" + serverId + "</id>\n" + " <username>admin</username>\n" + " <password>admin</password>\n" + " </server>\n" + "</servers>\n"; getLog().error(message); throw new MojoExecutionException(message); } if (!isIgnoreProject()) { uploadAppZip(newUserAdded); } else { getLog().info("Ignoring this project so not uploading the App Zip"); } } catch (MojoExecutionException e) { throw e; } catch (Exception e) { throw new MojoExecutionException("Error executing", e); } }
private void addTargetFileContentToTargetPlatform( TargetPlatformConfiguration configuration, TargetPlatformBuilder resolutionContext, MavenSession session) { final TargetDefinitionFile target; try { target = TargetDefinitionFile.read(configuration.getTarget()); } catch (TargetDefinitionSyntaxException e) { throw new RuntimeException( "Invalid syntax in target definition " + configuration.getTarget() + ": " + e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e); } Set<URI> uris = new HashSet<URI>(); for (Location location : target.getLocations()) { if (!(location instanceof InstallableUnitLocation)) { continue; } for (TargetDefinition.Repository repository : ((InstallableUnitLocation) location).getRepositories()) { try { URI uri = getMirror(repository, session.getRequest().getMirrors()); if (uris.add(uri)) { if (!session.isOffline()) { String id = repository.getId(); if (id != null) { Server server = session.getSettings().getServer(id); if (server != null) { // TODO don't do this via magic side-effects, but when loading repositories resolutionContext.setCredentials(uri, server.getUsername(), server.getPassword()); } else { getLogger() .info( "Unknown server id=" + id + " for repository location=" + repository.getLocation()); } } // TODO mirrors are no longer considered -> lookup mirrors when loading p2 // repositories } } } catch (URISyntaxException e) { throw new RuntimeException(e); } } try { getLogger().debug("Resolving target definition file \"" + configuration.getTarget() + "\""); resolutionContext.addTargetDefinition(target, getEnvironments(configuration)); } catch (TargetDefinitionSyntaxException e) { throw new RuntimeException( "Invalid syntax in target definition " + configuration.getTarget() + ": " + e.getMessage(), e); } catch (TargetDefinitionResolutionException e) { throw new RuntimeException( "Failed to resolve target definition " + configuration.getTarget(), e); } } }