org.apache.maven.settings.building.SettingsBuildingException Java Examples

The following examples show how to use org.apache.maven.settings.building.SettingsBuildingException. 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: MavenSettingsReader.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private Settings loadSettings() {
	File settingsFile = new File(this.homeDir, ".m2/settings.xml");
	if (settingsFile.exists()) {
		log.debug("Reading settings from: " + settingsFile);
	}
	else {
		log.debug("No settings found at: " + settingsFile);
	}
	SettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
	request.setUserSettingsFile(settingsFile);
	request.setSystemProperties(System.getProperties());
	try {
		return new DefaultSettingsBuilderFactory().newInstance().build(request)
				.getEffectiveSettings();
	}
	catch (SettingsBuildingException ex) {
		throw new IllegalStateException(
				"Failed to build settings from " + settingsFile, ex);
	}
}
 
Example #2
Source File: Utils.java    From gate-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Settings loadMavenSettings()
    throws SettingsBuildingException {
  // http://stackoverflow.com/questions/27818659/loading-mavens-settings-xml-for-jcabi-aether-to-use
  SettingsBuildingRequest settingsBuildingRequest =
      new DefaultSettingsBuildingRequest();
  settingsBuildingRequest.setSystemProperties(System.getProperties());
  settingsBuildingRequest.setUserSettingsFile(new File(settingsXml));
  settingsBuildingRequest.setGlobalSettingsFile(DEFAULT_GLOBAL_SETTINGS_FILE);

  SettingsBuildingResult settingsBuildingResult;
  DefaultSettingsBuilderFactory mvnSettingBuilderFactory =
      new DefaultSettingsBuilderFactory();
  DefaultSettingsBuilder settingsBuilder =
      mvnSettingBuilderFactory.newInstance();
  settingsBuildingResult = settingsBuilder.build(settingsBuildingRequest);

  Settings effectiveSettings = settingsBuildingResult.getEffectiveSettings();
  return effectiveSettings;
}
 
Example #3
Source File: MavenSettingsReader.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
private Settings loadSettings() {
	File settingsFile = new File(this.homeDir, ".m2/settings.xml");
	if (settingsFile.exists()) {
		log.info("Reading settings from: " + settingsFile);
	}
	else {
		log.info("No settings found at: " + settingsFile);
	}
	SettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
	request.setUserSettingsFile(settingsFile);
	request.setSystemProperties(System.getProperties());
	try {
		return new DefaultSettingsBuilderFactory().newInstance().build(request)
				.getEffectiveSettings();
	}
	catch (SettingsBuildingException ex) {
		throw new IllegalStateException(
				"Failed to build settings from " + settingsFile, ex);
	}
}
 
Example #4
Source File: MavenPluginRepository.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
private Settings loadDefaultUserSettings() {
	String userHome = System.getProperty("user.home");
    File userMavenConfigurationHome = new File(userHome, ".m2");
    String envM2Home = System.getenv("M2_HOME");
    File DEFAULT_USER_SETTINGS_FILE = new File(userMavenConfigurationHome, "settings.xml");
    File DEFAULT_GLOBAL_SETTINGS_FILE = new File(System.getProperty("maven.home", envM2Home != null ? envM2Home : ""), "conf/settings.xml");
    SettingsBuildingRequest settingsBuildingRequest = new DefaultSettingsBuildingRequest();
    settingsBuildingRequest.setSystemProperties(System.getProperties());
    settingsBuildingRequest.setUserSettingsFile(DEFAULT_USER_SETTINGS_FILE);
    settingsBuildingRequest.setGlobalSettingsFile(DEFAULT_GLOBAL_SETTINGS_FILE);

    DefaultSettingsBuilderFactory mvnSettingBuilderFactory = new DefaultSettingsBuilderFactory();
    DefaultSettingsBuilder settingsBuilder = mvnSettingBuilderFactory.newInstance();
    try {
		SettingsBuildingResult settingsBuildingResult = settingsBuilder.build(settingsBuildingRequest);
		Settings settings = settingsBuildingResult.getEffectiveSettings();
		return settings;
	} catch (SettingsBuildingException e) {
		e.printStackTrace();
	}
    return null;
}
 
Example #5
Source File: ConfigurationHelperTest.java    From LicenseScout with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a settings instance for testing.
 * @return a settings instance
 * @throws SettingsBuildingException
 */
private Settings createSettings() throws SettingsBuildingException {
    DefaultSettingsBuilderFactory settingsBuilderFactory = new DefaultSettingsBuilderFactory();
    SettingsBuilder settingsBuilder = settingsBuilderFactory.newInstance();
    DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
    final File userSettingsFile = new File("src/test/resources/ConfigurationHelperTest/settings.xml");
    request.setUserSettingsFile(userSettingsFile);
    SettingsBuildingResult settingsBuildingResult = settingsBuilder.build(request);
    return settingsBuildingResult.getEffectiveSettings();
}
 
Example #6
Source File: MavenMvnSettings.java    From galleon with Apache License 2.0 5 votes vote down vote up
private static Settings buildMavenSettings(Path settingsPath) throws ArtifactException {
    SettingsBuildingRequest settingsBuildingRequest = new DefaultSettingsBuildingRequest();
    settingsBuildingRequest.setSystemProperties(System.getProperties());
    settingsBuildingRequest.setUserSettingsFile(settingsPath.toFile());
    SettingsBuildingResult settingsBuildingResult;
    DefaultSettingsBuilderFactory mvnSettingBuilderFactory = new DefaultSettingsBuilderFactory();
    DefaultSettingsBuilder settingsBuilder = mvnSettingBuilderFactory.newInstance();
    try {
        settingsBuildingResult = settingsBuilder.build(settingsBuildingRequest);
    } catch (SettingsBuildingException ex) {
        throw new ArtifactException(ex.getLocalizedMessage());
    }

    return settingsBuildingResult.getEffectiveSettings();
}
 
Example #7
Source File: BootstrapMavenContext.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Settings getEffectiveSettings() throws BootstrapMavenException {
    if (settings != null) {
        return settings;
    }

    final Settings effectiveSettings;
    try {
        final SettingsBuildingResult result = new DefaultSettingsBuilderFactory()
                .newInstance().build(new DefaultSettingsBuildingRequest()
                        .setSystemProperties(System.getProperties())
                        .setUserSettingsFile(getUserSettings())
                        .setGlobalSettingsFile(getGlobalSettings()));
        final List<SettingsProblem> problems = result.getProblems();
        if (!problems.isEmpty()) {
            for (SettingsProblem problem : problems) {
                switch (problem.getSeverity()) {
                    case ERROR:
                    case FATAL:
                        throw new BootstrapMavenException("Settings problem encountered at " + problem.getLocation(),
                                problem.getException());
                    default:
                        log.warn("Settings problem encountered at " + problem.getLocation(), problem.getException());
                }
            }
        }
        effectiveSettings = result.getEffectiveSettings();
    } catch (SettingsBuildingException e) {
        throw new BootstrapMavenException("Failed to initialize Maven repository settings", e);
    }
    return settings = effectiveSettings;
}
 
Example #8
Source File: SimpleMavenCache.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void cacheArtifact(Artifact artifact)
    throws IOException, SettingsBuildingException,
    DependencyCollectionException, DependencyResolutionException,
    ArtifactResolutionException, ModelBuildingException {

  // setup a maven resolution hierarchy that uses the main local repo as
  // a remote repo and then cache into a new local repo
  List<RemoteRepository> repos = Utils.getRepositoryList();
  RepositorySystem repoSystem = Utils.getRepositorySystem();
  DefaultRepositorySystemSession repoSession =
      Utils.getRepositorySession(repoSystem, null);

  // treat the usual local repository as if it were a remote, ignoring checksum
  // failures as the local repo doesn't have checksums as a rule
  RemoteRepository localAsRemote =
      new RemoteRepository.Builder("localAsRemote", "default",
          repoSession.getLocalRepository().getBasedir().toURI().toString())
              .setPolicy(new RepositoryPolicy(true,
                      RepositoryPolicy.UPDATE_POLICY_NEVER,
                      RepositoryPolicy.CHECKSUM_POLICY_IGNORE))
              .build();

  repos.add(0, localAsRemote);

  repoSession.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(
      repoSession, new LocalRepository(head.getAbsolutePath())));

  Dependency dependency = new Dependency(artifact, "runtime");

  CollectRequest collectRequest = new CollectRequest(dependency, repos);

  DependencyNode node =
      repoSystem.collectDependencies(repoSession, collectRequest).getRoot();

  DependencyRequest dependencyRequest = new DependencyRequest();
  dependencyRequest.setRoot(node);

  repoSystem.resolveDependencies(repoSession, dependencyRequest);

}
 
Example #9
Source File: Utils.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static DefaultRepositorySystemSession getRepositorySession(RepositorySystem repoSystem, WorkspaceReader workspace) {
  
  DefaultRepositorySystemSession repoSystemSession = MavenRepositorySystemUtils.newSession();
  
  String repoLocation = System.getProperty("user.home") + File.separator
          + ".m2" + File.separator + "repository/";
  ChainedProxySelector proxySelector = new ChainedProxySelector();
  try {
    Settings effectiveSettings = loadMavenSettings();
    if(effectiveSettings.getLocalRepository() != null) {
      repoLocation = effectiveSettings.getLocalRepository();
    }

    List<Mirror> mirrors = effectiveSettings.getMirrors();
    if(!mirrors.isEmpty()) {
      DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector();
      for (Mirror mirror : mirrors) mirrorSelector.add(
              String.valueOf(mirror.getId()), mirror.getUrl(), mirror.getLayout(), false,
              mirror.getMirrorOf(), mirror.getMirrorOfLayouts());
      repoSystemSession.setMirrorSelector(mirrorSelector);
    }

    List<Server> servers = effectiveSettings.getServers();
    if(!servers.isEmpty()) {
      DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector();
      for (Server server : servers) {
        AuthenticationBuilder auth = new AuthenticationBuilder();
        auth.addUsername(server.getUsername()).addPassword(PASSWORD_DECRYPTER.decrypt(server.getPassword()));
        auth.addPrivateKey(server.getPrivateKey(), PASSWORD_DECRYPTER.decrypt(server.getPassphrase()));
        selector.add(server.getId(), auth.build());
      }
      repoSystemSession.setAuthenticationSelector(new ConservativeAuthenticationSelector(selector));
    }

    // extract any proxies configured in the settings - we need to pass these
    // on so that any repositories declared in a dependency POM file can be
    // accessed through the proxy too.
    List<org.apache.maven.settings.Proxy> proxies =
        effectiveSettings.getProxies().stream().filter((p) -> p.isActive())
            .collect(Collectors.toList());
    
    if(!proxies.isEmpty()) {
      DefaultProxySelector defaultSelector = new DefaultProxySelector();
      for (org.apache.maven.settings.Proxy proxy : proxies) {
        defaultSelector.add(
            new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(),
                new AuthenticationBuilder().addUsername(proxy.getUsername())
                    .addPassword(PASSWORD_DECRYPTER.decrypt(proxy.getPassword())).build()),
            proxy.getNonProxyHosts());
      }

      proxySelector.addSelector(defaultSelector);
    }

    // pass through the "offline" setting
    repoSystemSession.setOffline(effectiveSettings.isOffline());
  } catch(SettingsBuildingException | SecDispatcherException | RuntimeException e) {
    log.warn(
            "Unable to load Maven settings, using default repository location, and no mirrors, proxy or authentication settings.",
            e);
  }

  LocalRepository localRepo = new LocalRepository(repoLocation);
  log.debug("Using local repository at: " + repoLocation);
  repoSystemSession.setLocalRepositoryManager(repoSystem
          .newLocalRepositoryManager(repoSystemSession, localRepo));
  
  //repoSystemSession.setWorkspaceReader(new SimpleMavenCache(new File("repo")));      
  if (workspace != null) repoSystemSession.setWorkspaceReader(workspace);

  // try JRE proxies after any configured in settings
  proxySelector.addSelector(new JreProxySelector());

  // set proxy selector for any repositories discovered in dependency poms
  repoSystemSession.setProxySelector(proxySelector);

  return repoSystemSession;
}
 
Example #10
Source File: DockerRule.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
/**
 * Docker data container with unique name based on docker data-image (also unique).
 * If we are refreshing container, then it makes sense rebuild data-image.
 */
public String getDataContainerId(boolean forceRefresh) throws SettingsBuildingException,
        InterruptedException, IOException {
    final Map<String, File> pluginFiles = getPluginFiles();
    String dataContainerId = null;
    String dataContainerImage = null;

    LOG.debug("Checking whether data-container exist...");
    final List<Container> containers = getDockerCli().listContainersCmd().withShowAll(true).exec();
    OUTER:
    for (Container container : containers) {
        final String[] names = container.getNames();
        for (String name : names) {
            // docker adds "/" before container name
            if (name.equals("/" + DATA_CONTAINER_NAME)) {
                dataContainerId = container.getId();
                dataContainerImage = container.getImage();
                LOG.debug("Data container exists {}, based on image {}", dataContainerId, dataContainerImage);
                break OUTER;
            }
        }
    }

    final String dataImage = getDataImage(forceRefresh, pluginFiles, DATA_IMAGE);
    final boolean dataImagesEquals = dataImage.equals(dataContainerImage);
    LOG.debug("Data image is the same: {}", dataImagesEquals);

    if (nonNull(dataContainerId) && (forceRefresh || !dataImagesEquals)) {
        LOG.info("Removing data-container. ForceRefresh: {}", forceRefresh);
        try {
            getDockerCli().removeContainerCmd(dataContainerId)
                    .withForce(true) // force is not good
                    .withRemoveVolumes(true)
                    .exec();
        } catch (NotFoundException ignored) {
        }
        dataContainerId = null;
    }

    if (isNull(dataContainerId)) {
        LOG.debug("Data container doesn't exist, creating...");
        final CreateContainerResponse containerResponse = getDockerCli().createContainerCmd(dataImage)
                .withName(DATA_CONTAINER_NAME)
                .withCmd("/bin/true")
                .exec();
        dataContainerId = containerResponse.getId();
    }

    if (isNull(dataContainerId)) {
        throw new IllegalStateException("Container id can't be null.");
    }

    getDockerCli().inspectContainerCmd(dataContainerId).exec().getId();

    LOG.debug("Data containerId: '{}'", dataContainerId);
    return dataContainerId;
}
 
Example #11
Source File: DockerRule.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
/**
     * Ensures that data-image exist on docker.
     * Rebuilds data image if content (plugin hashes) doesn't match.
     *
     * @param forceUpdate rebuild data image.
     */
    public String getDataImage(boolean forceUpdate, final Map<String, File> pluginFiles, String imageName)
            throws IOException, SettingsBuildingException, InterruptedException {
        String existedDataImage = null;

        final List<Image> images = getDockerCli().listImagesCmd()
                .withShowAll(true)
                .exec();
        OUTER:
        for (Image image : images) {
            final String[] repoTags = image.getRepoTags();
            if (nonNull(repoTags)) {
                for (String repoTag : repoTags) {
                    if (repoTag.equals(imageName)) {
                        existedDataImage = image.getId();
                        break OUTER;
                    }
                }
            }
        }

        if (nonNull(existedDataImage) && (forceUpdate || !isActualDataImage(pluginFiles, existedDataImage))) {
            LOG.info("Removing data-image.");
            //TODO https://github.com/docker-java/docker-java/issues/398
            getDockerCli().removeImageCmd(existedDataImage).withForce(true).exec();
            existedDataImage = null;
        }

        if (isNull(existedDataImage)) {
            LOG.debug("Preparing plugin files for");

//            final Set<Artifact> artifactResults = resolvePluginsFor(THIS_PLUGIN);
//            LOG.debug("Resolved plugins: {}", artifactResults);
////            System.out.println(artifactResults);
//            artifactResults.stream().forEach(artifact ->
//                            pluginFiles.put(
//                                    // {@link hudson.PluginManager.copyBundledPlugin()}
////                            artifact.getArtifactId() + "." + artifact.getExtension(),
//                                    artifact.getArtifactId() + ".jpi",
//                                    artifact.getFile()
//                            )
//            );
            existedDataImage = buildImage(pluginFiles);
        }

        return existedDataImage;
    }
 
Example #12
Source File: DockerRule.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
/**
     * Run, record and remove after test container with jenkins.
     *
     * @param forceRefresh enforce data container and data image refresh
     */
    public String runFreshJenkinsContainer(DockerImagePullStrategy pullStrategy, boolean forceRefresh)
            throws IOException, SettingsBuildingException, InterruptedException {
        LOG.debug("Entering run fresh jenkins container.");
        pullImage(pullStrategy, JENKINS_DEFAULT.getDockerImageName());

        // labels attached to container allows cleanup container if it wasn't removed
        final Map<String, String> labels = new HashMap<>();
        labels.put("test.displayName", description.getDisplayName());

        LOG.debug("Removing existed container before");
        try {
            final List<Container> containers = getDockerCli().listContainersCmd().withShowAll(true).exec();
            for (Container c : containers) {
                if (c.getLabels().equals(labels)) { // equals? container labels vs image labels?
                    LOG.debug("Removing {}, for labels: '{}'", c, labels);
                    getDockerCli().removeContainerCmd(c.getId())
                            .withForce(true)
                            .exec();
                    break;
                }
            }
        } catch (NotFoundException ex) {
            LOG.debug("Container wasn't found, that's ok");
        }

        LOG.debug("Recreating data container without data-image doesn't make sense, so reuse boolean.");
        String dataContainerId = getDataContainerId(forceRefresh);
        final String id = getDockerCli().createContainerCmd(JENKINS_DEFAULT.getDockerImageName())
                .withEnv(CONTAINER_JAVA_OPTS)
                .withExposedPorts(new ExposedPort(JENKINS_DEFAULT.tcpPort))
                .withPortSpecs(String.format("%d/tcp", JENKINS_DEFAULT.tcpPort))
                .withHostConfig(HostConfig.newHostConfig()
                        .withPortBindings(PortBinding.parse("0.0.0.0:48000:48000"))
                        .withVolumesFrom(new VolumesFrom(dataContainerId))
                        .withPublishAllPorts(true))
                .withLabels(labels)
//                .withPortBindings(PortBinding.parse("0.0.0.0:48000:48000"), PortBinding.parse("0.0.0.0:50000:50000"))
                .exec()
                .getId();
        provisioned.add(id);

        LOG.debug("Starting container");
        getDockerCli().startContainerCmd(id).exec();
        return id;
    }
 
Example #13
Source File: SettingsIO.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
public void update( Settings settings, File settingsFile )
    throws ManipulationException
{
    try
    {
        Settings defaultSettings = new Settings();

        if ( settingsFile.exists() )
        {
            DefaultSettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
            settingsRequest.setGlobalSettingsFile( settingsFile );
            defaultSettings = settingsBuilder.build( settingsRequest ).getEffectiveSettings();
        }

        for ( Profile profile : settings.getProfiles() )
        {
            defaultSettings.getProfiles().removeIf( profile1 -> profile1.getId().equals( profile.getId() ) );
            defaultSettings.addProfile( profile );
        }
        for ( String activeProfile : settings.getActiveProfiles() )
        {
            defaultSettings.getActiveProfiles().removeIf( s -> s.equals( activeProfile ) );
            defaultSettings.addActiveProfile( activeProfile );
        }
        for ( Mirror mirror : settings.getMirrors() )
        {
            defaultSettings.addMirror( mirror );
        }
        for ( Proxy proxy : settings.getProxies() )
        {
            defaultSettings.addProxy( proxy );
        }
        for ( Server server : settings.getServers() )
        {
            defaultSettings.addServer( server );
        }
        for ( String pluginGroup : settings.getPluginGroups() )
        {
            defaultSettings.addPluginGroup( pluginGroup );
        }
        if ( settings.getLocalRepository() != null )
        {
            defaultSettings.setLocalRepository( settings.getLocalRepository() );
        }

        write( defaultSettings, settingsFile );
    }
    catch ( SettingsBuildingException e )
    {
        throw new ManipulationException( "Failed to build existing settings.xml for repo removal backup.", settingsFile, e.getMessage(), e );
    }
}
 
Example #14
Source File: MavenContainer.java    From furnace with Eclipse Public License 1.0 4 votes vote down vote up
public Settings getSettings()
{
   try
   {
      SettingsBuilder settingsBuilder = new DefaultSettingsBuilderFactory().newInstance();
      SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
      String userSettingsLocation = System.getProperty(ALT_USER_SETTINGS_XML_LOCATION);
      // TeamCity sets the settings.xml in a different system property
      String teamCitySettingsLocation = System.getProperty("teamcity.maven.userSettings.path");
      if (userSettingsLocation != null)
      {
         settingsRequest.setUserSettingsFile(new File(userSettingsLocation));
      }
      else if (teamCitySettingsLocation != null)
      {
         settingsRequest.setUserSettingsFile(new File(teamCitySettingsLocation));
      }
      else
      {
         settingsRequest.setUserSettingsFile(new File(getUserHomeDir(), "/.m2/settings.xml"));
      }
      String globalSettingsLocation = System.getProperty(ALT_GLOBAL_SETTINGS_XML_LOCATION);
      if (globalSettingsLocation != null)
      {
         settingsRequest.setGlobalSettingsFile(new File(globalSettingsLocation));
      }
      else
      {
         if (M2_HOME != null)
         {
            settingsRequest.setGlobalSettingsFile(new File(M2_HOME, "/conf/settings.xml"));
         }
      }
      SettingsBuildingResult settingsBuildingResult = settingsBuilder.build(settingsRequest);
      Settings effectiveSettings = settingsBuildingResult.getEffectiveSettings();

      if (effectiveSettings.getLocalRepository() == null)
      {
         String userRepositoryLocation = System.getProperty(ALT_LOCAL_REPOSITORY_LOCATION);
         if (userRepositoryLocation != null)
         {
            effectiveSettings.setLocalRepository(userRepositoryLocation);
         }
         else
         {
            effectiveSettings.setLocalRepository(getUserHomePath() + "/.m2/repository");
         }
      }

      return effectiveSettings;
   }
   catch (SettingsBuildingException e)
   {
      throw new RuntimeException(e);
   }
}