Java Examples for org.apache.maven.settings.Proxy
The following java examples will help you to understand the usage of org.apache.maven.settings.Proxy. These source code samples are taken from different open source projects.
Example 1
| Project: autorelease-master File: WagonUtils.java View source code |
/**
* Convenience method to map a <code>Proxy</code> object from the user system settings to a <code>ProxyInfo</code>
* object.
*
* @return a proxyInfo object or null if no active proxy is define in the settings.xml
*/
public static ProxyInfo getProxyInfo(Settings settings) {
ProxyInfo proxyInfo = null;
if (settings != null && settings.getActiveProxy() != null) {
Proxy settingsProxy = settings.getActiveProxy();
proxyInfo = new ProxyInfo();
proxyInfo.setHost(settingsProxy.getHost());
proxyInfo.setType(settingsProxy.getProtocol());
proxyInfo.setPort(settingsProxy.getPort());
proxyInfo.setNonProxyHosts(settingsProxy.getNonProxyHosts());
proxyInfo.setUserName(settingsProxy.getUsername());
proxyInfo.setPassword(settingsProxy.getPassword());
}
return proxyInfo;
}Example 2
| Project: codehaus-mojo-master File: TransformMojo.java View source code |
public void execute() throws MojoExecutionException, MojoFailureException {
Log log = this.getLog();
// System.setProperty( TRANSFORMER_FACTORY_PROPERTY_NAME, TRANSFORMER_FACTORY_CLASS );
Proxy activeProxy = this.settings.getActiveProxy();
String httpProxyHost = System.getProperty("http.proxyHost");
String httpProxyPort = System.getProperty("http.proxyPort");
String httpNonProxyHosts = System.getProperty("http.nonProxyHosts");
if (activeProxy != null) {
System.setProperty("http.proxyHost", activeProxy.getHost());
System.setProperty("http.proxyPort", new Integer(activeProxy.getPort()).toString());
System.setProperty("http.nonProxyHosts", activeProxy.getNonProxyHosts());
}
// Set XInclude Xerces parser so we're able to process master olink database file
String xercesParser = System.getProperty(TransformMojo.XERCES_PARSER_CONFIG);
System.setProperty(TransformMojo.XERCES_PARSER_CONFIG, TransformMojo.XERCES_XINCLUDE_PARSER);
String entityResolver = System.getProperty(TransformMojo.XERCES_RESOLVER_CONFIG);
System.setProperty(TransformMojo.XERCES_RESOLVER_CONFIG, TransformMojo.DOCBOOK_MOJO_RESOVER);
URI stylesheetLocationURI;
try {
stylesheetLocationURI = new URI(this.stylesheetLocation);
} catch (URISyntaxException exc) {
throw new MojoExecutionException("Unable to parse stylesheet location " + stylesheetLocation, exc);
}
try {
if (this.sourceDirectory.exists()) {
OLinkDBUpdater olinkDBUpdater = new OLinkDBUpdater(log, this.sourceDirectory, this.databaseDirectory, stylesheetLocationURI, this.artifacts);
olinkDBUpdater.update();
DocumentTransformer documentTransformer = new DocumentTransformer(log, this.sourceDirectory, this.resourceDirectory, this.databaseDirectory, this.outputDirectory, stylesheetLocationURI, this.customizations, this.artifacts);
for (int i = 0; i < outputFormats.length; i++) {
documentTransformer.enableOutputFormat(outputFormats[i]);
}
documentTransformer.transform();
if (this.profiles.length != 0) {
for (int i = 0; i < profiles.length; i++) {
documentTransformer.transform(this.profiles[i]);
}
}
}
} finally {
resetProperties(xercesParser, httpProxyHost, httpProxyPort, httpNonProxyHosts, entityResolver);
}
}Example 3
| Project: versions-maven-plugin-master File: WagonUtils.java View source code |
/**
* Convenience method to convert the {@link org.apache.maven.settings.Proxy} object from a
* {@link org.apache.maven.settings.Settings} into a {@link org.apache.maven.wagon.proxy.ProxyInfo}.
*
* @param settings The settings to use.
* @return The proxy details from the settings or <code>null</code> if the settings do not define a proxy.
*/
public static ProxyInfo getProxyInfo(Settings settings) {
ProxyInfo proxyInfo = null;
if (settings != null && settings.getActiveProxy() != null) {
proxyInfo = new ProxyInfo();
final Proxy proxy = settings.getActiveProxy();
proxyInfo.setHost(proxy.getHost());
proxyInfo.setType(proxy.getProtocol());
proxyInfo.setPort(proxy.getPort());
proxyInfo.setNonProxyHosts(proxy.getNonProxyHosts());
proxyInfo.setUserName(proxy.getUsername());
proxyInfo.setPassword(proxy.getPassword());
}
return proxyInfo;
}Example 4
| Project: jmeter-maven-plugin-master File: AbstractJMeterMojo.java View source code |
/**
* Try to load the active maven proxy.
*/
protected void loadMavenProxy() {
if (settings == null)
return;
try {
Proxy mvnProxy = settings.getActiveProxy();
if (mvnProxy != null) {
ProxyConfiguration newProxyConf = new ProxyConfiguration();
newProxyConf.setHost(mvnProxy.getHost());
newProxyConf.setPort(mvnProxy.getPort());
newProxyConf.setUsername(mvnProxy.getUsername());
newProxyConf.setPassword(mvnProxy.getPassword());
newProxyConf.setHostExclusions(mvnProxy.getNonProxyHosts());
proxyConfig = newProxyConf;
getLog().info("Maven proxy loaded successfully");
} else {
getLog().warn("No maven proxy found, but useMavenProxy set to true.");
}
} catch (Exception e) {
getLog().error("Error while loading maven proxy", e);
}
}Example 5
| Project: liferay-portal-master File: InitBundleMojo.java View source code |
@Override
public void execute() throws MojoExecutionException {
if (project.hasParent()) {
return;
}
Proxy proxy = MavenUtil.getProxy(_mavenSession);
String proxyProtocol = url.getProtocol();
String proxyHost = null;
Integer proxyPort = null;
String proxyUser = null;
String proxyPassword = null;
String nonProxyHosts = null;
if (proxy != null) {
proxyHost = BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyHost", proxy.getHost());
proxyPort = BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyPort", proxy.getPort());
proxyUser = BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyUser", proxy.getUsername());
proxyPassword = BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyPassword", proxy.getPassword());
nonProxyHosts = BundleSupportUtil.setSystemProperty(proxyProtocol + ".nonProxyHosts", proxy.getNonProxyHosts());
}
try {
InitBundleCommand initBundleCommand = new InitBundleCommand();
initBundleCommand.setCacheDir(cacheDir);
initBundleCommand.setConfigsDir(new File(project.getBasedir(), configs));
initBundleCommand.setEnvironment(environment);
initBundleCommand.setLiferayHomeDir(getLiferayHomeDir());
initBundleCommand.setPassword(password);
initBundleCommand.setStripComponents(stripComponents);
initBundleCommand.setUrl(url);
initBundleCommand.setUserName(userName);
initBundleCommand.execute();
} catch (Exception e) {
throw new MojoExecutionException("Unable to initialize bundle", e);
} finally {
if (proxy != null) {
BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyHost", proxyHost);
BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyPort", proxyPort);
BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyUser", proxyUser);
BundleSupportUtil.setSystemProperty(proxyProtocol + ".proxyPassword", proxyPassword);
BundleSupportUtil.setSystemProperty(proxyProtocol + ".nonProxyHosts", nonProxyHosts);
}
}
}Example 6
| Project: wisdom-master File: MojoUtils.java View source code |
public static ProxyConfig getProxyConfig(MavenSession mavenSession, SettingsDecrypter decrypter) {
if (mavenSession == null || mavenSession.getSettings() == null || mavenSession.getSettings().getProxies() == null || mavenSession.getSettings().getProxies().isEmpty()) {
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
} else {
final List<Proxy> mavenProxies = mavenSession.getSettings().getProxies();
final List<ProxyConfig.Proxy> proxies = new ArrayList<>(mavenProxies.size());
for (Proxy mavenProxy : mavenProxies) {
if (mavenProxy.isActive()) {
mavenProxy = decryptProxy(mavenProxy, decrypter);
proxies.add(new ProxyConfig.Proxy(mavenProxy.getId(), mavenProxy.getProtocol(), mavenProxy.getHost(), mavenProxy.getPort(), mavenProxy.getUsername(), mavenProxy.getPassword(), mavenProxy.getNonProxyHosts()));
}
}
return new ProxyConfig(proxies);
}
}Example 7
| Project: frontend-maven-plugin-master File: MojoUtils.java View source code |
static ProxyConfig getProxyConfig(MavenSession mavenSession, SettingsDecrypter decrypter) {
if (mavenSession == null || mavenSession.getSettings() == null || mavenSession.getSettings().getProxies() == null || mavenSession.getSettings().getProxies().isEmpty()) {
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
} else {
final List<Proxy> mavenProxies = mavenSession.getSettings().getProxies();
final List<ProxyConfig.Proxy> proxies = new ArrayList<ProxyConfig.Proxy>(mavenProxies.size());
for (Proxy mavenProxy : mavenProxies) {
if (mavenProxy.isActive()) {
mavenProxy = decryptProxy(mavenProxy, decrypter);
proxies.add(new ProxyConfig.Proxy(mavenProxy.getId(), mavenProxy.getProtocol(), mavenProxy.getHost(), mavenProxy.getPort(), mavenProxy.getUsername(), mavenProxy.getPassword(), mavenProxy.getNonProxyHosts()));
}
}
LOGGER.info("Found proxies: {}", proxies);
return new ProxyConfig(proxies);
}
}Example 8
| Project: ipf-labs-master File: AbstractDocMojo.java View source code |
/**
* Enables a proxy server for http access if it is configured within the Maven settings.
*/
protected void enableProxy() {
if (settings == null || settings.getActiveProxy() == null) {
return;
}
Proxy activeProxy = settings.getActiveProxy();
String protocol = activeProxy.getProtocol().isEmpty() ? "" : activeProxy.getProtocol();
if (defined(activeProxy.getHost())) {
System.setProperty(protocol + ".proxyHost", activeProxy.getHost());
}
if (activeProxy.getPort() > 0) {
System.setProperty(protocol + ".proxyPort", Integer.toString(activeProxy.getPort()));
}
if (defined(activeProxy.getNonProxyHosts())) {
System.setProperty(protocol + ".nonProxyHosts", activeProxy.getNonProxyHosts());
}
if (defined(activeProxy.getUsername())) {
System.setProperty(protocol + ".proxyUser", activeProxy.getUsername());
if (defined(activeProxy.getPassword())) {
System.setProperty(protocol + ".proxyPassword", activeProxy.getPassword());
}
}
}Example 9
| Project: Mav-master File: DefaultSettingsValidatorTest.java View source code |
public void testValidateUniqueProxyId() throws Exception {
Settings settings = new Settings();
Proxy proxy = new Proxy();
String id = null;
proxy.setId(id);
proxy.setHost("www.example.com");
settings.addProxy(proxy);
settings.addProxy(proxy);
SimpleProblemCollector problems = new SimpleProblemCollector();
validator.validate(settings, problems);
assertEquals(1, problems.messages.size());
assertContains(problems.messages.get(0), "'proxies.proxy.id' must be unique" + " but found duplicate proxy with id " + id);
}Example 10
| Project: maven-install-plugin-master File: MojoUtils.java View source code |
static ProxyConfig getProxyConfig(MavenSession mavenSession, SettingsDecrypter decrypter) {
if (mavenSession == null || mavenSession.getSettings() == null || mavenSession.getSettings().getProxies() == null || mavenSession.getSettings().getProxies().isEmpty()) {
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
} else {
final List<Proxy> mavenProxies = mavenSession.getSettings().getProxies();
final List<ProxyConfig.Proxy> proxies = new ArrayList<ProxyConfig.Proxy>(mavenProxies.size());
for (Proxy mavenProxy : mavenProxies) {
if (mavenProxy.isActive()) {
mavenProxy = decryptProxy(mavenProxy, decrypter);
proxies.add(new ProxyConfig.Proxy(mavenProxy.getId(), mavenProxy.getProtocol(), mavenProxy.getHost(), mavenProxy.getPort(), mavenProxy.getUsername(), mavenProxy.getPassword(), mavenProxy.getNonProxyHosts()));
}
}
LOGGER.info("Found proxies: {}", proxies);
return new ProxyConfig(proxies);
}
}Example 11
| Project: maven-master File: DefaultSettingsValidatorTest.java View source code |
public void testValidateUniqueProxyId() throws Exception {
Settings settings = new Settings();
Proxy proxy = new Proxy();
String id = null;
proxy.setId(id);
proxy.setHost("www.example.com");
settings.addProxy(proxy);
settings.addProxy(proxy);
SimpleProblemCollector problems = new SimpleProblemCollector();
validator.validate(settings, problems);
assertEquals(1, problems.messages.size());
assertContains(problems.messages.get(0), "'proxies.proxy.id' must be unique" + " but found duplicate proxy with id " + id);
}Example 12
| Project: oceano-master File: DefaultMaven.java View source code |
public RepositorySystemSession newRepositorySession(MavenExecutionRequest request) {
MavenRepositorySystemSession session = new MavenRepositorySystemSession(false);
session.setCache(request.getRepositoryCache());
Map<Object, Object> configProps = new LinkedHashMap<Object, Object>();
configProps.put(ConfigurationProperties.USER_AGENT, getUserAgent());
configProps.put(ConfigurationProperties.INTERACTIVE, Boolean.valueOf(request.isInteractiveMode()));
configProps.putAll(request.getSystemProperties());
configProps.putAll(request.getUserProperties());
session.setOffline(request.isOffline());
session.setChecksumPolicy(request.getGlobalChecksumPolicy());
if (request.isNoSnapshotUpdates()) {
session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_NEVER);
} else if (request.isUpdateSnapshots()) {
session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS);
} else {
session.setUpdatePolicy(null);
}
session.setNotFoundCachingEnabled(request.isCacheNotFound());
session.setTransferErrorCachingEnabled(request.isCacheTransferError());
session.setArtifactTypeRegistry(RepositoryUtils.newArtifactTypeRegistry(artifactHandlerManager));
LocalRepository localRepo = new LocalRepository(request.getLocalRepository().getBasedir());
session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(localRepo));
if (request.getWorkspaceReader() != null) {
session.setWorkspaceReader(request.getWorkspaceReader());
} else {
session.setWorkspaceReader(workspaceRepository);
}
DefaultSettingsDecryptionRequest decrypt = new DefaultSettingsDecryptionRequest();
decrypt.setProxies(request.getProxies());
decrypt.setServers(request.getServers());
SettingsDecryptionResult decrypted = settingsDecrypter.decrypt(decrypt);
if (logger.isDebugEnabled()) {
for (SettingsProblem problem : decrypted.getProblems()) {
logger.debug(problem.getMessage(), problem.getException());
}
}
DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector();
for (Mirror mirror : request.getMirrors()) {
mirrorSelector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts());
}
session.setMirrorSelector(mirrorSelector);
DefaultProxySelector proxySelector = new DefaultProxySelector();
for (Proxy proxy : decrypted.getProxies()) {
Authentication proxyAuth = new Authentication(proxy.getUsername(), proxy.getPassword());
proxySelector.add(new org.sonatype.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), proxyAuth), proxy.getNonProxyHosts());
}
session.setProxySelector(proxySelector);
DefaultAuthenticationSelector authSelector = new DefaultAuthenticationSelector();
for (Server server : decrypted.getServers()) {
Authentication auth = new Authentication(server.getUsername(), server.getPassword(), server.getPrivateKey(), server.getPassphrase());
authSelector.add(server.getId(), auth);
if (server.getConfiguration() != null) {
Xpp3Dom dom = (Xpp3Dom) server.getConfiguration();
for (int i = dom.getChildCount() - 1; i >= 0; i--) {
Xpp3Dom child = dom.getChild(i);
if ("wagonProvider".equals(child.getName())) {
dom.removeChild(i);
}
}
XmlPlexusConfiguration config = new XmlPlexusConfiguration(dom);
configProps.put("aether.connector.wagon.config." + server.getId(), config);
}
configProps.put("aether.connector.perms.fileMode." + server.getId(), server.getFilePermissions());
configProps.put("aether.connector.perms.dirMode." + server.getId(), server.getDirectoryPermissions());
}
session.setAuthenticationSelector(authSelector);
session.setTransferListener(request.getTransferListener());
session.setRepositoryListener(eventSpyDispatcher.chainListener(new LoggingRepositoryListener(logger)));
session.setUserProps(request.getUserProperties());
session.setSystemProps(request.getSystemProperties());
session.setConfigProps(configProps);
return session;
}Example 13
| Project: org.ops4j.pax.url-master File: AetherBasedResolver.java View source code |
private ProxySelector selectProxies() {
DefaultProxySelector proxySelector = new DefaultProxySelector();
for (org.apache.maven.settings.Proxy proxy : m_settings.getProxies()) {
if (!proxy.isActive()) {
continue;
}
String nonProxyHosts = proxy.getNonProxyHosts();
Proxy proxyObj = new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), getAuthentication(proxy));
proxySelector.add(proxyObj, nonProxyHosts);
}
if (m_settings.getProxies().size() == 0) {
javaDefaultProxy(proxySelector);
}
return proxySelector;
}Example 14
| Project: resolver-master File: MavenConverter.java View source code |
/**
* Converts Maven Proxy to Aether Proxy
*
* @param proxy
* the Maven proxy to be converted
* @return Aether proxy equivalent
*/
public static Proxy asProxy(org.apache.maven.settings.Proxy proxy) {
final Authentication authentication;
if (proxy.getUsername() != null || proxy.getPassword() != null) {
authentication = new AuthenticationBuilder().addUsername(proxy.getUsername()).addPassword(proxy.getPassword()).build();
} else {
authentication = null;
}
return new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authentication);
}Example 15
| Project: Clay-master File: AetherUtils.java View source code |
/**
* Create a new {@link org.eclipse.aether.repository.ProxySelector} from given list of
* {@link org.apache.maven.settings.Proxy}
*/
public static ProxySelector newProxySelector(List<Proxy> proxies) {
DefaultProxySelector proxySelector = new DefaultProxySelector();
for (Proxy proxy : proxies) {
Authentication auth = new AuthenticationBuilder().addUsername(proxy.getUsername()).addPassword(proxy.getPassword()).build();
proxySelector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth), proxy.getNonProxyHosts());
}
return proxySelector;
}Example 16
| Project: embedmongo-maven-plugin-master File: StartMojo.java View source code |
public IProxyFactory getProxyFactory(Settings settings) {
URI downloadUri = URI.create(downloadPath);
final String downloadHost = downloadUri.getHost();
final String downloadProto = downloadUri.getScheme();
if (settings.getProxies() != null) {
for (org.apache.maven.settings.Proxy proxy : (List<org.apache.maven.settings.Proxy>) settings.getProxies()) {
if (proxy.isActive() && equalsIgnoreCase(proxy.getProtocol(), downloadProto) && !contains(proxy.getNonProxyHosts(), downloadHost)) {
return new HttpProxyFactory(proxy.getHost(), proxy.getPort());
}
}
}
return new NoProxyFactory();
}Example 17
| Project: sisu-maven-bridge-master File: DefaultMavenSettings.java View source code |
public ProxySelector getProxySelector() {
return new ProxySelector() {
@Override
public org.eclipse.aether.repository.Proxy getProxy(final RemoteRepository repository) {
if (proxySelector != null) {
final org.eclipse.aether.repository.Proxy proxy = proxySelector.getProxy(repository);
if (proxy != null) {
return proxy;
}
}
return session.getProxySelector().getProxy(repository);
}
};
}Example 18
| Project: cuke4duke-master File: AbstractJRubyMojo.java View source code |
/**
* Detect proxy from settings and convert to arg expected by RubyGems.
*/
protected String getProxyArg() {
Proxy activeProxy = this.settings.getActiveProxy();
if (activeProxy == null) {
return "";
}
String proxyArg = " --http-proxy " + activeProxy.getProtocol() + "://" + activeProxy.getHost() + ":" + activeProxy.getPort();
getLog().debug("Adding proxy from settings.xml: " + proxyArg);
return proxyArg;
}Example 19
| Project: drools-master File: Aether.java View source code |
private RepositorySystemSession newRepositorySystemSession(Settings settings, RepositorySystem system) {
LocalRepository localRepo = new LocalRepository(localRepoDir);
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
session.setOffline(offline);
if (!settings.getProxies().isEmpty()) {
DefaultProxySelector proxySelector = new DefaultProxySelector();
for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) {
proxySelector.add(new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort()), proxy.getNonProxyHosts());
}
session.setProxySelector(proxySelector);
}
return session;
}Example 20
| Project: nexus-maven-plugins-master File: RemoteNexus.java View source code |
// ==
protected NexusClient createNexusClient(final Parameters parameters) {
final String nexusUrl = parameters.getNexusUrl();
try {
final BaseUrl baseUrl = BaseUrl.baseUrlFrom(nexusUrl);
final UsernamePasswordAuthenticationInfo authenticationInfo;
final Map<Protocol, ProxyInfo> proxyInfos = new HashMap<Protocol, ProxyInfo>(1);
if (server != null && server.getUsername() != null) {
log.info(" + Using server credentials \"{}\" from Maven settings.", server.getId());
authenticationInfo = new UsernamePasswordAuthenticationInfo(server.getUsername(), server.getPassword());
} else {
authenticationInfo = null;
}
if (proxy != null) {
final UsernamePasswordAuthenticationInfo proxyAuthentication;
if (proxy.getUsername() != null) {
proxyAuthentication = new UsernamePasswordAuthenticationInfo(proxy.getUsername(), proxy.getPassword());
} else {
proxyAuthentication = null;
}
log.info(" + Using \"{}\" {} Proxy from Maven settings.", proxy.getId(), proxy.getProtocol().toUpperCase());
final ProxyInfo zProxy = new ProxyInfo(baseUrl.getProtocol(), proxy.getHost(), proxy.getPort(), proxyAuthentication);
proxyInfos.put(zProxy.getProxyProtocol(), zProxy);
}
final ValidationLevel sslCertificateValidationLevel = parameters.isSslInsecure() ? ValidationLevel.LAX : ValidationLevel.STRICT;
final ValidationLevel sslCertificateHostnameValidationLevel = parameters.isSslAllowAll() ? ValidationLevel.NONE : ValidationLevel.LAX;
final ConnectionInfo connectionInfo = new ConnectionInfo(baseUrl, authenticationInfo, proxyInfos, sslCertificateValidationLevel, sslCertificateHostnameValidationLevel);
final NexusClient nexusClient = new JerseyNexusClientFactory(// support v2 and v3
new JerseyStagingWorkflowV2SubsystemFactory(), new JerseyStagingWorkflowV3SubsystemFactory()).createFor(connectionInfo);
final NexusStatus nexusStatus = nexusClient.getNexusStatus();
log.info(" * Connected to Nexus at {}, is version {} and edition \"{}\"", connectionInfo.getBaseUrl(), nexusStatus.getVersion(), nexusStatus.getEditionLong());
return nexusClient;
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed Nexus base URL [" + nexusUrl + "]", e);
} catch (UniformInterfaceException e) {
throw new IllegalArgumentException("Nexus base URL [" + nexusUrl + "] does not point to a valid Nexus location: " + e.getMessage(), e);
} catch (Exception e) {
throw new IllegalArgumentException("Nexus connection problem to URL [" + nexusUrl + " ]: " + e.getMessage(), e);
}
}Example 21
| Project: capsule-maven-master File: MavenUserSettings.java View source code |
public ProxySelector getProxySelector() {
final DefaultProxySelector selector = new DefaultProxySelector();
for (Proxy proxy : settings.getProxies()) {
final AuthenticationBuilder auth = new AuthenticationBuilder();
auth.addUsername(proxy.getUsername()).addPassword(proxy.getPassword());
selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth.build()), proxy.getNonProxyHosts());
}
return selector;
}Example 22
| Project: felix-master File: RemoteFileManager.java View source code |
/**
* Convenience method to map a Proxy object from the user system settings to a ProxyInfo object.
* @param settings project settings given by maven
* @return a proxyInfo object instancied or null if no active proxy is define in the settings.xml
*/
public static ProxyInfo getProxyInfo(Settings settings) {
ProxyInfo proxyInfo = null;
if (settings != null && settings.getActiveProxy() != null) {
Proxy settingsProxy = settings.getActiveProxy();
proxyInfo = new ProxyInfo();
proxyInfo.setHost(settingsProxy.getHost());
proxyInfo.setType(settingsProxy.getProtocol());
proxyInfo.setPort(settingsProxy.getPort());
proxyInfo.setNonProxyHosts(settingsProxy.getNonProxyHosts());
proxyInfo.setUserName(settingsProxy.getUsername());
proxyInfo.setPassword(settingsProxy.getPassword());
}
return proxyInfo;
}Example 23
| Project: maven-confluence-plugin-master File: AbstractBaseConfluenceMojo.java View source code |
/**
*
* @param task
* @throws MojoExecutionException
*/
protected <T extends Action1<ConfluenceService>> void confluenceExecute(T task) throws MojoExecutionException {
ConfluenceService confluence = null;
try {
ConfluenceProxy proxyInfo = null;
final Proxy activeProxy = mavenSettings.getActiveProxy();
if (activeProxy != null) {
proxyInfo = new ConfluenceProxy(activeProxy.getHost(), activeProxy.getPort(), activeProxy.getUsername(), activeProxy.getPassword(), activeProxy.getNonProxyHosts());
}
final ConfluenceService.Credentials credentials = new ConfluenceService.Credentials(getUsername(), getPassword());
confluence = ConfluenceServiceFactory.createInstance(getEndPoint(), credentials, proxyInfo, sslCertificate);
getLog().info(String.valueOf(confluence));
confluence.call(task);
} catch (RuntimeException re) {
throw re;
} catch (Exception e) {
final String msg = "has been impossible connect to confluence due exception";
throw new MojoExecutionException(msg, e);
}
}Example 24
| Project: maven-plugins-master File: AbstractJavadocMojo.java View source code |
/**
* Method that adds/sets the javadoc proxy parameters in the command line execution.
*
* @param cmd the command line execution object where the argument will be added
*/
private void addProxyArg(Commandline cmd) {
if (settings == null || settings.getActiveProxy() == null) {
return;
}
Proxy activeProxy = settings.getActiveProxy();
String protocol = StringUtils.isNotEmpty(activeProxy.getProtocol()) ? activeProxy.getProtocol() + "." : "";
if (StringUtils.isNotEmpty(activeProxy.getHost())) {
cmd.createArg().setValue("-J-D" + protocol + "proxySet=true");
cmd.createArg().setValue("-J-D" + protocol + "proxyHost=" + activeProxy.getHost());
if (activeProxy.getPort() > 0) {
cmd.createArg().setValue("-J-D" + protocol + "proxyPort=" + activeProxy.getPort());
}
if (StringUtils.isNotEmpty(activeProxy.getNonProxyHosts())) {
cmd.createArg().setValue("-J-D" + protocol + "nonProxyHosts=\"" + activeProxy.getNonProxyHosts() + "\"");
}
if (StringUtils.isNotEmpty(activeProxy.getUsername())) {
cmd.createArg().setValue("-J-Dhttp.proxyUser=\"" + activeProxy.getUsername() + "\"");
if (StringUtils.isNotEmpty(activeProxy.getPassword())) {
cmd.createArg().setValue("-J-Dhttp.proxyPassword=\"" + activeProxy.getPassword() + "\"");
}
}
}
}Example 25
| Project: maven-release-master File: ForkedMavenExecutorTest.java View source code |
public void testEncryptSettings() throws Exception {
// prepare
File workingDirectory = getTestFile("target/working-directory");
Process mockProcess = mock(Process.class);
when(mockProcess.getInputStream()).thenReturn(mock(InputStream.class));
when(mockProcess.getErrorStream()).thenReturn(mock(InputStream.class));
when(mockProcess.getOutputStream()).thenReturn(mock(OutputStream.class));
when(mockProcess.waitFor()).thenReturn(0);
Commandline commandLineMock = mock(Commandline.class);
when(commandLineMock.execute()).thenReturn(mockProcess);
Arg valueArgument = mock(Arg.class);
when(commandLineMock.createArg()).thenReturn(valueArgument);
CommandLineFactory commandLineFactoryMock = mock(CommandLineFactory.class);
when(commandLineFactoryMock.createCommandLine(isA(String.class))).thenReturn(commandLineMock);
executor.setCommandLineFactory(commandLineFactoryMock);
Settings settings = new Settings();
Server server = new Server();
server.setPassphrase("server_passphrase");
server.setPassword("server_password");
settings.addServer(server);
Proxy proxy = new Proxy();
proxy.setPassword("proxy_password");
settings.addProxy(proxy);
ReleaseEnvironment releaseEnvironment = new DefaultReleaseEnvironment();
releaseEnvironment.setSettings(settings);
AbstractMavenExecutor executorSpy = spy(executor);
SettingsXpp3Writer settingsWriter = mock(SettingsXpp3Writer.class);
ArgumentCaptor<Settings> encryptedSettings = ArgumentCaptor.forClass(Settings.class);
when(executorSpy.getSettingsWriter()).thenReturn(settingsWriter);
executorSpy.executeGoals(workingDirectory, "validate", releaseEnvironment, false, null, new ReleaseResult());
verify(settingsWriter).write(isA(Writer.class), encryptedSettings.capture());
assertNotSame(settings, encryptedSettings.getValue());
Server encryptedServer = encryptedSettings.getValue().getServers().get(0);
assertEquals("server_passphrase", secDispatcher.decrypt(encryptedServer.getPassphrase()));
assertEquals("server_password", secDispatcher.decrypt(encryptedServer.getPassword()));
Proxy encryptedProxy = encryptedSettings.getValue().getProxies().get(0);
assertEquals("proxy_password", secDispatcher.decrypt(encryptedProxy.getPassword()));
File settingsSecurity = new File(System.getProperty("user.home"), ".m2/settings-security.xml");
if (settingsSecurity.exists()) {
assertFalse("server_passphrase".equals(encryptedServer.getPassphrase()));
assertFalse("server_password".equals(encryptedServer.getPassword()));
assertFalse("proxy_password".equals(encryptedProxy.getPassword()));
}
}Example 26
| Project: pom-version-manipulator-master File: DefaultSessionConfigurator.java View source code |
private void loadSettings(final VersionManagerSession session) {
MavenExecutionRequest executionRequest = session.getExecutionRequest();
if (executionRequest == null) {
executionRequest = new DefaultMavenExecutionRequest();
}
File settingsXml;
try {
settingsXml = getFile(session.getSettingsXml(), session.getDownloads());
} catch (final VManException e) {
session.addError(e);
return;
}
final DefaultSettingsBuildingRequest req = new DefaultSettingsBuildingRequest();
req.setUserSettingsFile(settingsXml);
req.setSystemProperties(System.getProperties());
try {
final SettingsBuildingResult result = settingsBuilder.build(req);
final Settings settings = result.getEffectiveSettings();
final String proxyHost = System.getProperty("http.proxyHost");
final String proxyPort = System.getProperty("http.proxyPort", "8080");
final String nonProxyHosts = System.getProperty("http.nonProxyHosts", "localhost");
final String proxyUser = System.getProperty("http.proxyUser");
final String proxyPassword = System.getProperty("http.proxyPassword");
if (proxyHost != null) {
final Proxy proxy = new Proxy();
proxy.setActive(true);
proxy.setHost(proxyHost);
proxy.setId("cli");
proxy.setNonProxyHosts(nonProxyHosts);
proxy.setPort(Integer.parseInt(proxyPort));
if (proxyUser != null && proxyPassword != null) {
proxy.setUsername(proxyUser);
proxy.setPassword(proxyPassword);
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
}
});
}
settings.setProxies(Collections.singletonList(proxy));
}
executionRequest = requestPopulator.populateFromSettings(executionRequest, settings);
session.setExecutionRequest(executionRequest);
} catch (final SettingsBuildingException e) {
session.addError(new VManException("Failed to build settings from: %s. Reason: %s", e, settingsXml, e.getMessage()));
} catch (final MavenExecutionRequestPopulationException e) {
session.addError(new VManException("Failed to initialize system using settings from: %s. Reason: %s", e, settingsXml, e.getMessage()));
}
}Example 27
| Project: bundlemaker-master File: MvnSettingsBasedRepositoryAdapter.java View source code |
private ProxySelector selectProxies() {
DefaultProxySelector proxySelector = new DefaultProxySelector();
//
for (Proxy proxy : _settings.getProxies()) {
// The fields are user, pass, host, port, nonProxyHosts, protocol.
String nonProxyHosts = proxy.getNonProxyHosts();
org.sonatype.aether.repository.Proxy proxyObj = new org.sonatype.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), getAuthentication(proxy));
proxySelector.add(proxyObj, nonProxyHosts);
}
//
return proxySelector;
}Example 28
| Project: karaf-master File: MojoSupport.java View source code |
protected Artifact resourceToArtifact(String resourceLocation, boolean skipNonMavenProtocols) throws MojoExecutionException {
resourceLocation = resourceLocation.replace("\r\n", "").replace("\n", "").replace(" ", "").replace("\t", "");
final int index = resourceLocation.indexOf("mvn:");
if (index < 0) {
if (skipNonMavenProtocols) {
return null;
}
throw new MojoExecutionException("Resource URL is not a Maven URL: " + resourceLocation);
} else {
resourceLocation = resourceLocation.substring(index + "mvn:".length());
}
final int index1 = resourceLocation.indexOf('?');
final int index2 = resourceLocation.indexOf('#');
int endIndex = -1;
if (index1 > 0) {
if (index2 > 0) {
endIndex = Math.min(index1, index2);
} else {
endIndex = index1;
}
} else if (index2 > 0) {
endIndex = index2;
}
if (endIndex >= 0) {
resourceLocation = resourceLocation.substring(0, endIndex);
}
final int index3 = resourceLocation.indexOf('$');
if (index3 > 0) {
resourceLocation = resourceLocation.substring(0, index3);
}
ArtifactRepository repo = null;
if (resourceLocation.startsWith("http://")) {
final int repoDelimIntex = resourceLocation.indexOf('!');
String repoUrl = resourceLocation.substring(0, repoDelimIntex);
repo = new DefaultArtifactRepository(repoUrl, repoUrl, new DefaultRepositoryLayout());
org.apache.maven.repository.Proxy mavenProxy = configureProxyToInlineRepo();
if (mavenProxy != null) {
repo.setProxy(mavenProxy);
}
resourceLocation = resourceLocation.substring(repoDelimIntex + 1);
}
String[] parts = resourceLocation.split("/");
String groupId = parts[0];
String artifactId = parts[1];
String version = null;
String classifier = null;
String type = "jar";
if (parts.length > 2) {
version = parts[2];
if (parts.length > 3) {
type = parts[3];
if (parts.length > 4) {
classifier = parts[4];
}
}
} else {
Dependency dep = findDependency(project.getDependencies(), artifactId, groupId);
if (dep == null && project.getDependencyManagement() != null) {
dep = findDependency(project.getDependencyManagement().getDependencies(), artifactId, groupId);
}
if (dep != null) {
version = dep.getVersion();
classifier = dep.getClassifier();
type = dep.getType();
}
}
if (version == null || version.isEmpty()) {
throw new MojoExecutionException("Cannot find version for: " + resourceLocation);
}
Artifact artifact = factory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);
artifact.setRepository(repo);
return artifact;
}Example 29
| Project: Maven-Archetype-master File: RemoteCatalogArchetypeDataSource.java View source code |
private ArchetypeCatalog downloadCatalog(ArtifactRepository repository) throws WagonException, IOException, ArchetypeDataSourceException {
getLogger().debug("Searching for remote catalog: " + repository.getUrl() + "/" + ARCHETYPE_CATALOG_FILENAME);
// We use wagon to take advantage of a Proxy that has already been setup in a Maven environment.
Repository wagonRepository = new Repository(repository.getId(), repository.getUrl());
AuthenticationInfo authInfo = getAuthenticationInfo(wagonRepository.getId());
ProxyInfo proxyInfo = getProxy(wagonRepository.getProtocol());
Wagon wagon = getWagon(wagonRepository);
File catalog = File.createTempFile("archetype-catalog", ".xml");
try {
wagon.connect(wagonRepository, authInfo, proxyInfo);
wagon.get(ARCHETYPE_CATALOG_FILENAME, catalog);
return readCatalog(ReaderFactory.newXmlReader(catalog));
} finally {
disconnectWagon(wagon);
catalog.delete();
}
}Example 30
| Project: org-tools-master File: RepositoryUtils.java View source code |
// ----------------------------------------------------------------------
// Private methods
// ----------------------------------------------------------------------
/**
* Convenience method to map a <code>Proxy</code> object from the user system settings to a <code>ProxyInfo</code>
* object.
*
* @return a proxyInfo object instanced or null if no active proxy is define in the settings.xml
*/
private ProxyInfo getProxyInfo() {
ProxyInfo proxyInfo = null;
if (settings != null && settings.getActiveProxy() != null) {
Proxy settingsProxy = settings.getActiveProxy();
proxyInfo = new ProxyInfo();
proxyInfo.setHost(settingsProxy.getHost());
proxyInfo.setType(settingsProxy.getProtocol());
proxyInfo.setPort(settingsProxy.getPort());
proxyInfo.setNonProxyHosts(settingsProxy.getNonProxyHosts());
proxyInfo.setUserName(settingsProxy.getUsername());
proxyInfo.setPassword(settingsProxy.getPassword());
}
return proxyInfo;
}Example 31
| Project: SmallMind-master File: MavenRepository.java View source code |
private ProxySelector getProxySelector(Settings settings) {
DefaultProxySelector selector = new DefaultProxySelector();
for (Proxy proxy : settings.getProxies()) {
AuthenticationBuilder auth = new AuthenticationBuilder();
auth.addUsername(proxy.getUsername()).addPassword(proxy.getPassword());
selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth.build()), proxy.getNonProxyHosts());
}
return selector;
}Example 32
| Project: spring-boot-master File: MavenSettings.java View source code |
private ProxySelector createProxySelector(SettingsDecryptionResult decryptedSettings) {
DefaultProxySelector selector = new DefaultProxySelector();
for (Proxy proxy : decryptedSettings.getProxies()) {
Authentication authentication = new AuthenticationBuilder().addUsername(proxy.getUsername()).addPassword(proxy.getPassword()).build();
selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authentication), proxy.getNonProxyHosts());
}
return selector;
}Example 33
| Project: beanstalker-master File: AbstractAWSMojo.java View source code |
protected ClientConfiguration getClientConfiguration() {
ClientConfiguration clientConfiguration = new ClientConfiguration().withUserAgent(getUserAgent());
if (null != this.settings && null != settings.getActiveProxy()) {
Proxy proxy = settings.getActiveProxy();
clientConfiguration.setProxyHost(proxy.getHost());
clientConfiguration.setProxyUsername(proxy.getUsername());
clientConfiguration.setProxyPassword(proxy.getPassword());
clientConfiguration.setProxyPort(proxy.getPort());
}
return clientConfiguration;
}Example 34
| Project: isc-maven-plugin-master File: Downloads.java View source code |
/**
* Adapted from the Site plugin's AbstractDeployMojo to allow http operations through proxy.
* <p>
* Refer to
* http://maven.apache.org/guides/mini/guide-proxies.html
* <br>
* http://maven.apache.org/plugins/maven-site-plugin/xref/org/apache/maven/plugins/site/AbstractDeployMojo.html.
*/
private boolean isProxied(Proxy proxyConfig) throws MalformedURLException {
String nonProxyHostsAsString = proxyConfig.getNonProxyHosts();
for (String nonProxyHost : StringUtils.split(nonProxyHostsAsString, ",;|")) {
if (StringUtils.contains(nonProxyHost, "*")) {
// Handle wildcard at the end, beginning or middle of the nonProxyHost
final int pos = nonProxyHost.indexOf('*');
String nonProxyHostPrefix = nonProxyHost.substring(0, pos);
String nonProxyHostSuffix = nonProxyHost.substring(pos + 1);
// prefix*
if (StringUtils.isNotEmpty(nonProxyHostPrefix) && DOMAIN.startsWith(nonProxyHostPrefix) && StringUtils.isEmpty(nonProxyHostSuffix)) {
return false;
}
// *suffix
if (StringUtils.isEmpty(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && DOMAIN.endsWith(nonProxyHostSuffix)) {
return false;
}
// prefix*suffix
if (StringUtils.isNotEmpty(nonProxyHostPrefix) && DOMAIN.startsWith(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && DOMAIN.endsWith(nonProxyHostSuffix)) {
return false;
}
} else if (DOMAIN.equals(nonProxyHost)) {
return false;
}
}
return true;
}Example 35
| Project: maven-gae-plugin-master File: EngineGoalBase.java View source code |
private void addProxyOption(final List<String> args) {
if (isNotEmpty(proxy)) {
addStringOption(args, "--proxy=", proxy);
} else if (hasServerSettings()) {
final Proxy activCfgProxy = settings.getActiveProxy();
if (activCfgProxy != null) {
addStringOption(args, "--proxy=", activCfgProxy.getHost() + ":" + activCfgProxy.getPort());
}
}
}Example 36
| Project: aether-ant-master File: AntRepoSys.java View source code |
private ProxySelector getProxySelector() {
DefaultProxySelector selector = new DefaultProxySelector();
for (Proxy proxy : proxies) {
selector.add(ConverterUtils.toProxy(proxy), proxy.getNonProxyHosts());
}
Settings settings = getSettings();
for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) {
AuthenticationBuilder auth = new AuthenticationBuilder();
auth.addUsername(proxy.getUsername()).addPassword(proxy.getPassword());
selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth.build()), proxy.getNonProxyHosts());
}
return selector;
}Example 37
| Project: lib-jenkins-maven-embedder-master File: MavenEmbedder.java View source code |
/**
* {@link WagonManager} can't configure itself from {@link Settings}, so we need to baby-sit them.
* So much for dependency injection.
*/
private void resolveParameters(WagonManager wagonManager, Settings settings) throws ComponentLookupException, ComponentLifecycleException, SettingsConfigurationException {
// TODO todo or not todo ?
Proxy proxy = settings.getActiveProxy();
if (proxy != null) {
if (proxy.getHost() == null) {
throw new SettingsConfigurationException("Proxy in settings.xml has no host");
}
//wagonManager.addProxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), proxy.getUsername(),
// proxy.getPassword(), proxy.getNonProxyHosts());
}
for (Server server : (List<Server>) settings.getServers()) {
if (server.getConfiguration() != null) {
//wagonManager.addConfiguration(server.getId(), (Xpp3Dom) server.getConfiguration());
}
}
for (Mirror mirror : (List<Mirror>) settings.getMirrors()) {
//wagonManager.addMirror(mirror.getId(), mirror.getMirrorOf(), mirror.getUrl());
}
}Example 38
| Project: maven-jdocbook-plugin-master File: AbstractDocBookMojo.java View source code |
private void doExecuteWithProxy(Proxy proxy) throws JDocBookProcessException {
String originalHost = null;
String originalPort = null;
String originalUser = null;
String originalPswd = null;
// First set up jvm environment with the proxy settings (storing the original values for later)
if (!empty(proxy.getHost())) {
originalHost = System.getProperty("http.proxyHost");
System.setProperty("http.proxyHost", proxy.getHost());
originalPort = System.getProperty("http.proxyPort");
System.setProperty("http.proxyPort", Integer.toString(proxy.getPort()));
}
if (!empty(proxy.getUsername())) {
originalUser = System.getProperty("http.proxyUser");
System.setProperty("http.proxyUser", emptyStringIfNull(proxy.getUsername()));
}
if (!empty(proxy.getPassword())) {
originalPswd = System.getProperty("http.proxyPassword");
System.setProperty("http.proxyPassword", emptyStringIfNull(proxy.getPassword()));
}
try {
// Do the processing
doExecute();
} finally {
// Restore the original settings
if (!empty(proxy.getHost())) {
System.setProperty("http.proxyHost", emptyStringIfNull(originalHost));
System.setProperty("http.proxyPort", emptyStringIfNull(originalPort));
}
if (!empty(proxy.getUsername())) {
System.setProperty("http.proxyUser", emptyStringIfNull(originalUser));
}
if (!empty(proxy.getPassword())) {
System.setProperty("http.proxyPassword", emptyStringIfNull(originalPswd));
}
}
}Example 39
| Project: cxf-master File: AbstractCodegenMoho.java View source code |
private void restoreProxySetting(String originalProxyHost, String originalProxyPort, String originalNonProxyHosts, String originalProxyUser, String originalProxyPassword) {
if (originalProxyHost != null) {
System.setProperty(HTTP_PROXY_HOST, originalProxyHost);
} else {
System.getProperties().remove(HTTP_PROXY_HOST);
}
if (originalProxyPort != null) {
System.setProperty(HTTP_PROXY_PORT, originalProxyPort);
} else {
System.getProperties().remove(HTTP_PROXY_PORT);
}
if (originalNonProxyHosts != null) {
System.setProperty(HTTP_NON_PROXY_HOSTS, originalNonProxyHosts);
} else {
System.getProperties().remove(HTTP_NON_PROXY_HOSTS);
}
if (originalProxyUser != null) {
System.setProperty(HTTP_PROXY_USER, originalProxyUser);
} else {
System.getProperties().remove(HTTP_PROXY_USER);
}
if (originalProxyPassword != null) {
System.setProperty(HTTP_PROXY_PASSWORD, originalProxyPassword);
} else {
System.getProperties().remove(HTTP_PROXY_PASSWORD);
}
Proxy proxy = mavenSession.getSettings().getActiveProxy();
if (proxy != null && !StringUtils.isEmpty(proxy.getUsername()) && !StringUtils.isEmpty(proxy.getPassword())) {
Authenticator.setDefault(null);
}
}Example 40
| Project: grails-maven-master File: AbstractGrailsMojo.java View source code |
private void configureMavenProxy() {
if (settings != null) {
Proxy activeProxy = settings.getActiveProxy();
if (activeProxy != null) {
String host = activeProxy.getHost();
int port = activeProxy.getPort();
String noProxy = activeProxy.getNonProxyHosts();
String username = activeProxy.getUsername();
String password = activeProxy.getPassword();
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", String.valueOf(port));
if (noProxy != null) {
System.setProperty("http.nonProxyHosts", noProxy);
}
if (username != null) {
System.setProperty("http.proxyUser", username);
}
if (password != null) {
System.setProperty("http.proxyPassword", password);
}
}
}
}Example 41
| Project: jaxb2-maven-plugin-master File: AbstractJavaGeneratorMojo.java View source code |
private String getProxyString(final Proxy activeProxy) {
// Check sanity
if (activeProxy == null) {
return null;
}
// The XJC proxy argument should be on the form
// [user[:password]@]proxyHost[:proxyPort]
//
// builder.withNamedArgument("httpproxy", httpproxy);
//
final StringBuilder proxyBuilder = new StringBuilder();
if (activeProxy.getUsername() != null) {
// Start with the username.
proxyBuilder.append(activeProxy.getUsername());
// Append the password if provided.
if (activeProxy.getPassword() != null) {
proxyBuilder.append(":").append(activeProxy.getPassword());
}
proxyBuilder.append("@");
}
// Append hostname and port.
proxyBuilder.append(activeProxy.getHost()).append(":").append(activeProxy.getPort());
// All done.
return proxyBuilder.toString();
}Example 42
| Project: karaf-cave-master File: MavenProxyServletTest.java View source code |
private MavenResolver createResolver(String localRepo, String remoteRepos, String proxyProtocol, String proxyHost, int proxyPort, String proxyUsername, String proxyPassword, String proxyNonProxyHosts) {
Hashtable<String, String> props = new Hashtable<>();
props.put("localRepository", localRepo);
if (remoteRepos != null) {
props.put("repositories", remoteRepos);
}
MavenConfigurationImpl config = new MavenConfigurationImpl(new DictionaryPropertyResolver(props), null);
if (proxyProtocol != null) {
Proxy proxy = new Proxy();
proxy.setProtocol(proxyProtocol);
proxy.setHost(proxyHost);
proxy.setPort(proxyPort);
proxy.setUsername(proxyUsername);
proxy.setPassword(proxyPassword);
proxy.setNonProxyHosts(proxyNonProxyHosts);
config.getSettings().addProxy(proxy);
}
return new AetherBasedResolver(config);
}Example 43
| Project: mvn-fluid-cd-master File: JenkinsDefaultMaven.java View source code |
public RepositorySystemSession newRepositorySession(MavenExecutionRequest request) {
DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
session.setCache(request.getRepositoryCache());
Map<Object, Object> configProps = new LinkedHashMap<Object, Object>();
configProps.put(ConfigurationProperties.USER_AGENT, getUserAgent());
configProps.put(ConfigurationProperties.INTERACTIVE, request.isInteractiveMode());
configProps.putAll(request.getSystemProperties());
configProps.putAll(request.getUserProperties());
session.setOffline(request.isOffline());
session.setChecksumPolicy(request.getGlobalChecksumPolicy());
if (request.isNoSnapshotUpdates()) {
session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_NEVER);
} else if (request.isUpdateSnapshots()) {
session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS);
} else {
session.setUpdatePolicy(null);
}
int errorPolicy = 0;
errorPolicy |= request.isCacheNotFound() ? ResolutionErrorPolicy.CACHE_NOT_FOUND : 0;
errorPolicy |= request.isCacheTransferError() ? ResolutionErrorPolicy.CACHE_TRANSFER_ERROR : 0;
session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(errorPolicy, errorPolicy | ResolutionErrorPolicy.CACHE_NOT_FOUND));
session.setArtifactTypeRegistry(RepositoryUtils.newArtifactTypeRegistry(artifactHandlerManager));
LocalRepository localRepo = new LocalRepository(request.getLocalRepository().getBasedir());
if (request.isUseLegacyLocalRepository()) {
logger.warn("Disabling enhanced local repository: using legacy is strongly discouraged to ensure build reproducibility.");
try {
session.setLocalRepositoryManager(simpleLocalRepositoryManagerFactory.newInstance(session, localRepo));
} catch (NoLocalRepositoryManagerException e) {
logger.warn("Failed to configure legacy local repository: back to default");
session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(session, localRepo));
}
} else {
session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(session, localRepo));
}
if (request.getWorkspaceReader() != null) {
session.setWorkspaceReader(request.getWorkspaceReader());
} else {
session.setWorkspaceReader(workspaceRepository);
}
DefaultSettingsDecryptionRequest decrypt = new DefaultSettingsDecryptionRequest();
decrypt.setProxies(request.getProxies());
decrypt.setServers(request.getServers());
SettingsDecryptionResult decrypted = settingsDecrypter.decrypt(decrypt);
if (logger.isDebugEnabled()) {
for (SettingsProblem problem : decrypted.getProblems()) {
logger.debug(problem.getMessage(), problem.getException());
}
}
DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector();
for (Mirror mirror : request.getMirrors()) {
mirrorSelector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts());
}
session.setMirrorSelector(mirrorSelector);
DefaultProxySelector proxySelector = new DefaultProxySelector();
for (Proxy proxy : decrypted.getProxies()) {
AuthenticationBuilder authBuilder = new AuthenticationBuilder();
authBuilder.addUsername(proxy.getUsername()).addPassword(proxy.getPassword());
proxySelector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), authBuilder.build()), proxy.getNonProxyHosts());
}
session.setProxySelector(proxySelector);
DefaultAuthenticationSelector authSelector = new DefaultAuthenticationSelector();
for (Server server : decrypted.getServers()) {
AuthenticationBuilder authBuilder = new AuthenticationBuilder();
authBuilder.addUsername(server.getUsername()).addPassword(server.getPassword());
authBuilder.addPrivateKey(server.getPrivateKey(), server.getPassphrase());
authSelector.add(server.getId(), authBuilder.build());
if (server.getConfiguration() != null) {
Xpp3Dom dom = (Xpp3Dom) server.getConfiguration();
for (int i = dom.getChildCount() - 1; i >= 0; i--) {
Xpp3Dom child = dom.getChild(i);
if ("wagonProvider".equals(child.getName())) {
dom.removeChild(i);
}
}
XmlPlexusConfiguration config = new XmlPlexusConfiguration(dom);
configProps.put("aether.connector.wagon.config." + server.getId(), config);
}
configProps.put("aether.connector.perms.fileMode." + server.getId(), server.getFilePermissions());
configProps.put("aether.connector.perms.dirMode." + server.getId(), server.getDirectoryPermissions());
}
session.setAuthenticationSelector(authSelector);
session.setTransferListener(request.getTransferListener());
session.setRepositoryListener(eventSpyDispatcher.chainListener(new LoggingRepositoryListener(logger)));
session.setUserProperties(request.getUserProperties());
session.setSystemProperties(request.getSystemProperties());
session.setConfigProperties(configProps);
return session;
}Example 44
| Project: mvnplugins-master File: LinkcheckReport.java View source code |
// ----------------------------------------------------------------------
// Private methods
// ----------------------------------------------------------------------
/**
* Execute the <code>Linkcheck</code> tool.
*
* @param basedir not null
* @throws LinkCheckException if any
*/
private LinkcheckModel executeLinkCheck(File basedir) throws LinkCheckException {
// Wrap linkcheck
linkCheck.setOnline(!offline);
linkCheck.setBasedir(basedir);
linkCheck.setBaseURL(baseURL);
linkCheck.setReportOutput(linkcheckOutput);
linkCheck.setLinkCheckCache(linkcheckCache);
linkCheck.setExcludedLinks(excludedLinks);
linkCheck.setExcludedPages(getExcludedPages());
linkCheck.setExcludedHttpStatusErrors(excludedHttpStatusErrors);
linkCheck.setExcludedHttpStatusWarnings(excludedHttpStatusWarnings);
linkCheck.setEncoding((StringUtils.isNotEmpty(encoding) ? encoding : WriterFactory.UTF_8));
HttpBean bean = new HttpBean();
bean.setMethod(httpMethod);
bean.setFollowRedirects(httpFollowRedirect);
bean.setTimeout(timeout);
if (httpClientParameters != null) {
bean.setHttpClientParameters(httpClientParameters);
}
Proxy proxy = settings.getActiveProxy();
if (proxy != null) {
bean.setProxyHost(proxy.getHost());
bean.setProxyPort(proxy.getPort());
bean.setProxyUser(proxy.getUsername());
bean.setProxyPassword(proxy.getPassword());
}
linkCheck.setHttp(bean);
return linkCheck.execute();
}Example 45
| Project: DependencyCheck-master File: BaseDependencyCheckMojo.java View source code |
/**
* Takes the properties supplied and updates the dependency-check settings.
* Additionally, this sets the system properties required to change the
* proxy url, port, and connection timeout.
*/
protected void populateSettings() {
Settings.initialize();
InputStream mojoProperties = null;
try {
mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
Settings.mergeProperties(mojoProperties);
} catch (IOException ex) {
getLog().warn("Unable to load the dependency-check ant task.properties file.");
if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} finally {
if (mojoProperties != null) {
try {
mojoProperties.close();
} catch (IOException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
}
}
}
Settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental);
if (externalReport != null) {
getLog().warn("The 'externalReport' option was set; this configuration option has been removed. " + "Please update the dependency-check-maven plugin's configuration");
}
if (proxyUrl != null && !proxyUrl.isEmpty()) {
getLog().warn("Deprecated configuration detected, proxyUrl will be ignored; use the maven settings to configure the proxy instead");
}
final Proxy proxy = getMavenProxy();
if (proxy != null) {
Settings.setString(Settings.KEYS.PROXY_SERVER, proxy.getHost());
Settings.setString(Settings.KEYS.PROXY_PORT, Integer.toString(proxy.getPort()));
final String userName = proxy.getUsername();
final String password = proxy.getPassword();
Settings.setStringIfNotNull(Settings.KEYS.PROXY_USERNAME, userName);
Settings.setStringIfNotNull(Settings.KEYS.PROXY_PASSWORD, password);
Settings.setStringIfNotNull(Settings.KEYS.PROXY_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
}
Settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
Settings.setStringIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFile);
Settings.setStringIfNotEmpty(Settings.KEYS.HINTS_FILE, hintsFile);
//File Type Analyzer Settings
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, centralAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled);
Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled);
Settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions);
Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, rubygemsAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, opensslAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_CMAKE_ENABLED, cmakeAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, autoconfAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, composerAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, nodeAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, bundleAuditAnalyzerEnabled);
Settings.setStringIfNotNull(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, bundleAuditPath);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_COCOAPODS_ENABLED, cocoapodsAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_SWIFT_PACKAGE_MANAGER_ENABLED, swiftPackageManagerAnalyzerEnabled);
//Database configuration
Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
Settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
if (databaseUser == null && databasePassword == null && serverId != null) {
final Server server = settingsXml.getServer(serverId);
if (server != null) {
databaseUser = server.getUsername();
try {
//
if (securityDispatcher instanceof DefaultSecDispatcher) {
((DefaultSecDispatcher) securityDispatcher).setConfigurationFile("~/.m2/settings-security.xml");
}
databasePassword = securityDispatcher.decrypt(server.getPassword());
} catch (SecDispatcherException ex) {
if (ex.getCause() instanceof FileNotFoundException || (ex.getCause() != null && ex.getCause().getCause() instanceof FileNotFoundException)) {
final String tmp = server.getPassword();
if (tmp.startsWith("{") && tmp.endsWith("}")) {
getLog().error(String.format("Unable to decrypt the server password for server id '%s' in settings.xml%n\tCause: %s", serverId, ex.getMessage()));
} else {
databasePassword = tmp;
}
} else {
getLog().error(String.format("Unable to decrypt the server password for server id '%s' in settings.xml%n\tCause: %s", serverId, ex.getMessage()));
}
}
} else {
getLog().error(String.format("Server '%s' not found in the settings.xml file", serverId));
}
}
Settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser);
Settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword);
Settings.setStringIfNotEmpty(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified);
Settings.setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified);
Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base);
Settings.setStringIfNotEmpty(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base);
Settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours);
}Example 46
| Project: m2e-core-master File: MavenImpl.java View source code |
public ProxyInfo getProxyInfo(String protocol) throws CoreException {
Settings settings = getSettings();
for (Proxy proxy : settings.getProxies()) {
if (proxy.isActive() && protocol.equalsIgnoreCase(proxy.getProtocol())) {
ProxyInfo proxyInfo = new ProxyInfo();
proxyInfo.setType(proxy.getProtocol());
proxyInfo.setHost(proxy.getHost());
proxyInfo.setPort(proxy.getPort());
proxyInfo.setNonProxyHosts(proxy.getNonProxyHosts());
proxyInfo.setUserName(proxy.getUsername());
proxyInfo.setPassword(proxy.getPassword());
return proxyInfo;
}
}
return null;
}Example 47
| Project: sarl-master File: GenerateTestsMojo.java View source code |
@SuppressWarnings({ "checkstyle:methodlength", "checkstyle:npathcomplexity" })
private void generateAbstractTest(File outputFolder) throws IOException {
//$NON-NLS-1$
getLog().debug("Generating abstract test");
final ImportManager importManager = new ImportManager();
final ITreeAppendable it = new FakeTreeAppendable(importManager);
//$NON-NLS-1$ //$NON-NLS-2$
it.append("@").append(SuppressWarnings.class).append("(\"all\")");
it.newLine();
//$NON-NLS-1$
it.append("public class AbstractBaseTest {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("protected static String STR_SUCCESS = \"success\";");
it.newLine();
//$NON-NLS-1$
it.append("protected static String STR_FAILURE = \"failure\";");
it.newLine();
//$NON-NLS-1$
it.append("protected static String STR_FACT = \"fact\";");
it.newLine().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("private static ").append(Injector.class).append(" injector = ");
//$NON-NLS-1$
it.append(DocumentationSetup.class).append(".doSetup();");
it.newLine().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("private ").append(ScriptExecutor.class).append(" scriptExecutor;");
it.newLine().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("protected ").append(ScriptExecutor.class).append(" getScriptExecutor() {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("if (this.scriptExecutor == null) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("this.scriptExecutor = this.injector.getInstance(").append(ScriptExecutor.class).append(".class);");
it.newLine();
final StringBuilder cp = new StringBuilder();
for (final File cpElement : getClassPath()) {
if (cp.length() > 0) {
//$NON-NLS-1$
cp.append(//$NON-NLS-1$
":");
}
cp.append(cpElement.getAbsolutePath());
}
//$NON-NLS-1$
it.append("scriptExecutor.setClassPath(\"");
it.append(Strings.convertToJavaString(cp.toString()));
//$NON-NLS-1$
it.append("\");");
it.newLine();
final String bootPath = getBootClassPath();
if (!Strings.isEmpty(bootPath)) {
//$NON-NLS-1$
it.append("scriptExecutor.setBootClassPath(\"");
it.append(Strings.convertToJavaString(bootPath));
//$NON-NLS-1$
it.append("\");");
it.newLine();
}
JavaVersion version = null;
if (!Strings.isEmpty(this.source)) {
version = JavaVersion.fromQualifier(this.source);
}
if (version == null) {
version = JavaVersion.JAVA8;
}
//$NON-NLS-1$
it.append("scriptExecutor.setJavaSourceVersion(\"");
it.append(Strings.convertToJavaString(version.getQualifier()));
//$NON-NLS-1$
it.append("\");");
it.newLine();
//$NON-NLS-1$
it.append("scriptExecutor.setTempFolder(").append(FileSystem.class);
//$NON-NLS-1$
it.append(".convertStringToFile(\"");
it.append(Strings.convertToJavaString(this.tempDirectory.getAbsolutePath()));
//$NON-NLS-1$
it.append("\"));");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("return this.scriptExecutor;");
it.newLine();
//$NON-NLS-1$
it.append("}");
it.newLine().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("public void assertNoIssue(int lineno, ").append(List.class).append("<String> issues) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("if (issues != null && !issues.isEmpty()) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append(StringBuilder.class).append(" msg = new ").append(StringBuilder.class).append("();");
it.newLine();
//$NON-NLS-1$
it.append("for (String message : issues) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("msg.append(message).append(\"\\n\");");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine();
//$NON-NLS-1$
it.append("throw new ").append(ComparisonFailure.class).append(//$NON-NLS-1$
"(\"Expecting no issue but find one [line:\" + lineno + \"]\", \"\", msg.toString());");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("public void assertIssues(int lineno, ").append(List.class).append("<String> issues) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("if (issues == null || issues.isEmpty()) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append(Assert.class).append(".fail(\"Expecting issues but did not find one [line:\" + lineno + \"]\");");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine().newLine();
//$NON-NLS-1$
it.append("public static String getHttpCodeExplanation(int code) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("switch (code) {");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_BAD_METHOD: return \"Method Not Allowed\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_CREATED: return \"Created\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_ACCEPTED: return \"Accepted\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_NOT_AUTHORITATIVE: return ");
//$NON-NLS-1$
it.append("\"Non-Authoritative Information\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_NO_CONTENT: return \"No Content\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_RESET: return \"Reset Content\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_PARTIAL: return \"Partial Content\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_MULT_CHOICE: return \"Multiple Choices\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_MOVED_PERM: return \"Moved Permanently\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_MOVED_TEMP: return \"Temporary Redirect\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_SEE_OTHER: return \"See Other\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_NOT_MODIFIED: return \"Not Modified\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_USE_PROXY: return \"Use Proxy\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_BAD_REQUEST: return \"Bad Request\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_UNAUTHORIZED: return \"Unauthorized\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_PAYMENT_REQUIRED: return \"Payment Required\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_FORBIDDEN: return \"Forbidden\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_NOT_FOUND: return \"Not Found\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_NOT_ACCEPTABLE: return \"Not Acceptable\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_PROXY_AUTH: return ");
//$NON-NLS-1$
it.append("\"Proxy Authentication Required\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_CLIENT_TIMEOUT: return \"Request Time-Out\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_CONFLICT: return \"Conflict\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_GONE: return \"Gone\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_LENGTH_REQUIRED: return \"Length Required\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_PRECON_FAILED: return \"Precondition Failed\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_ENTITY_TOO_LARGE: return ");
//$NON-NLS-1$
it.append("\"Request Entity Too Large\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_REQ_TOO_LONG: return ");
//$NON-NLS-1$
it.append("\"Request-URI Too Large\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_UNSUPPORTED_TYPE: return ");
//$NON-NLS-1$
it.append("\"Unsupported Media Type\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_INTERNAL_ERROR: return ");
//$NON-NLS-1$
it.append("\"Internal Server Error\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_NOT_IMPLEMENTED: return \"Not Implemented\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_BAD_GATEWAY: return \"Bad Gateway\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_UNAVAILABLE: return \"Service Unavailable\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_GATEWAY_TIMEOUT: return \"Gateway Timeout\";");
it.newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("case ").append(HttpURLConnection.class).append(".HTTP_VERSION: return ");
//$NON-NLS-1$
it.append("\"HTTP Version Not Supported\";");
it.newLine();
//$NON-NLS-1$
it.append("default: return null;");
it.newLine();
//$NON-NLS-1$
it.append("}");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine().newLine();
//$NON-NLS-1$
it.append("public static boolean isAcceptableHttpCode(int code) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("return code == ").append(HttpURLConnection.class).append(".HTTP_OK");
it.increaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("|| code == ").append(HttpURLConnection.class).append(".HTTP_MOVED_TEMP");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append(";");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine().newLine();
//$NON-NLS-1$
it.append("public static void assertURLAccessibility(int lineno, ").append(URL.class);
//$NON-NLS-1$//$NON-NLS-2$
it.append(" url) throws ").append(Exception.class).append(" {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("int code;");
it.newLine();
//$NON-NLS-1$
it.append(HttpURLConnection.class).append(".setFollowRedirects(false);");
it.newLine();
//$NON-NLS-1$
it.append(URLConnection.class).append(" connection = url.openConnection();");
it.newLine();
//$NON-NLS-1$
it.append(Assume.class).append(".assumeTrue(\"Not an UTL with http[s] protocol\", connection instanceof ");
//$NON-NLS-1$
it.append(HttpURLConnection.class).append(");");
it.newLine();
//$NON-NLS-1$
it.append(HttpURLConnection.class).append(" httpConnection = (");
//$NON-NLS-1$
it.append(HttpURLConnection.class).append(") connection;");
it.newLine();
//$NON-NLS-1$
it.append("try {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("httpConnection.setInstanceFollowRedirects(false);");
it.newLine();
//$NON-NLS-1$
it.append("httpConnection.setConnectTimeout(").append(Integer.toString(this.remoteLinkTimeOut));
//$NON-NLS-1$
it.append(");");
it.newLine();
//$NON-NLS-1$
it.append("httpConnection.setReadTimeout(").append(Integer.toString(this.remoteLinkTimeOut));
//$NON-NLS-1$
it.append(");");
it.newLine();
//$NON-NLS-1$
it.append("httpConnection.setAllowUserInteraction(false);");
it.newLine();
//$NON-NLS-1$
it.append("httpConnection.setRequestMethod(\"HEAD\");");
it.newLine();
//$NON-NLS-1$
it.append("httpConnection.connect();");
it.newLine();
//$NON-NLS-1$
it.append("code = httpConnection.getResponseCode();");
it.decreaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("} catch (").append(IOException.class).append(" exception) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("Throwable rootCause = ").append(Throwables.class).append(".getRootCause(exception);");
it.newLine();
if (this.ignoreRemoteLinkTimeOut) {
//$NON-NLS-1$ //$NON-NLS-2$
it.append("if (rootCause instanceof ").append(SocketTimeoutException.class).append(") {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append(Assume.class).append(".assumeNoException(\"");
//$NON-NLS-1$
it.append("Connection time-out at line \" + lineno + \" when connecting to: \" + url.toExternalForm()");
//$NON-NLS-1$
it.append(", rootCause);");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine();
}
//$NON-NLS-1$
it.append("throw new ").append(RuntimeException.class);
//$NON-NLS-1$
it.append("(\"Error at line \" + lineno + \" when connecting to: \" + url.toExternalForm(), rootCause);");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("} finally {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("httpConnection.disconnect();");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine();
//$NON-NLS-1$
it.append("if (isAcceptableHttpCode(code)) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("return;");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine();
//$NON-NLS-1$
it.append("String explanation = getHttpCodeExplanation(code);");
it.newLine();
//$NON-NLS-1$
it.append("String codeMsg = !").append(Strings.class);
//$NON-NLS-1$
it.append(".isEmpty(explanation) ? code + \"/\\\"\" + explanation + \"\\\"\" : Integer.toString(code);");
it.newLine();
//$NON-NLS-1$
it.append(Assert.class).append(".fail(\"Invalid response code \" + codeMsg + \" at line \" + lineno ");
//$NON-NLS-1$
it.append("+ \" when connecting to: \" + url.toExternalForm());");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
if (!this.session.isOffline() && !this.session.getRequest().getProxies().isEmpty()) {
it.newLine().newLine();
//$NON-NLS-1$
it.append("private static boolean proxyNameMatches(String pattern, String name) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append(Pattern.class).append(" pat = ");
//$NON-NLS-1$
it.append(Pattern.class).append(".compile(pattern, ");
//$NON-NLS-1$
it.append(Pattern.class).append(".CASE_INSENSITIVE);");
it.newLine();
//$NON-NLS-1$
it.append(Matcher.class).append(" mat = pat.matcher(name);");
it.newLine();
//$NON-NLS-1$
it.append("return mat.matches();");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine().newLine();
//$NON-NLS-1$
it.append("static {");
it.increaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append("final ").append(ProxySelector.class).append(" defaultSelector = ");
//$NON-NLS-1$
it.append(ProxySelector.class).append(".getDefault();");
it.newLine();
//$NON-NLS-1$
it.append(ProxySelector.class).append(" newSelector = new ").append(ProxySelector.class);
//$NON-NLS-1$
it.append("() {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("public ").append(List.class);
//$NON-NLS-1$ //$NON-NLS-2$
it.append("<").append(java.net.Proxy.class).append("> select(final ");
//$NON-NLS-1$
it.append(URI.class).append(" uri) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$ //$NON-NLS-2$
it.append(List.class).append("<").append(java.net.Proxy.class).append("> proxies = new ");
//$NON-NLS-1$
it.append(ArrayList.class).append("(defaultSelector.select(uri));");
it.newLine();
for (final Proxy proxy : this.session.getRequest().getProxies()) {
//$NON-NLS-1$
it.append("if (\"").append(//$NON-NLS-1$
Strings.convertToJavaString(proxy.getProtocol()));
//$NON-NLS-1$
it.append(//$NON-NLS-1$
"\".equals(uri.getScheme())) {");
it.increaseIndentation().newLine();
final String nonProxyHosts = proxy.getNonProxyHosts();
boolean hasProxy = false;
if (!Strings.isEmpty(nonProxyHosts)) {
if (nonProxyHosts != null) {
hasProxy = true;
//$NON-NLS-1$
it.append("if (");
//$NON-NLS-1$
final StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|");
boolean first = true;
while (tokenizer.hasMoreTokens()) {
String pattern = tokenizer.nextToken();
//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
pattern = pattern.replace(".", "\\.").replace("*", ".*");
if (first) {
first = false;
} else {
//$NON-NLS-1$
it.newLine().append(" && ");
}
//$NON-NLS-1$
it.append("!proxyNameMatches(\"^").append(Strings.convertToJavaString(pattern));
//$NON-NLS-1$
it.append("$\", uri.getHost())");
}
//$NON-NLS-1$
it.append(") {");
it.increaseIndentation().newLine();
}
}
//$NON-NLS-1$
it.append("proxies.add(new ").append(//$NON-NLS-1$
java.net.Proxy.class);
//$NON-NLS-1$ //$NON-NLS-2$
it.append("(").append(Type.class).append(".HTTP, new ");
//$NON-NLS-1$
it.append(InetSocketAddress.class).append(//$NON-NLS-1$
"(\"");
it.append(Strings.convertToJavaString(proxy.getHost()));
//$NON-NLS-1$
it.append("\", ").append(//$NON-NLS-1$
Integer.toString(proxy.getPort()));
//$NON-NLS-1$
it.append(//$NON-NLS-1$
")));");
if (hasProxy) {
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
}
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append(//$NON-NLS-1$
"}");
it.newLine();
}
//$NON-NLS-1$ //$NON-NLS-2$
it.append("return ").append(Collections.class).append(".unmodifiableList(proxies);");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine();
//$NON-NLS-1$
it.append("public void connectFailed(").append(URI.class);
//$NON-NLS-1$
it.append(" uri, ").append(SocketAddress.class);
//$NON-NLS-1$
it.append(" sa, ").append(IOException.class);
//$NON-NLS-1$
it.append(" ioe) {");
it.increaseIndentation().newLine();
//$NON-NLS-1$
it.append("throw new ").append(RuntimeException.class);
//$NON-NLS-1$
it.append("(ioe);");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("};");
it.newLine();
//$NON-NLS-1$
it.append(ProxySelector.class).append(".setDefault(newSelector);");
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
}
it.decreaseIndentation().newLine();
//$NON-NLS-1$
it.append("}");
it.newLine();
write(outputFolder, BASE_PACKAGE, "AbstractBaseTest", importManager, it);
}Example 48
| Project: citrus-tool-master File: EclipsePlugin.java View source code |
private void writeAdditionalConfig() throws MojoExecutionException {
if (additionalConfig != null) {
for (int j = 0; j < additionalConfig.length; j++) {
EclipseConfigFile file = additionalConfig[j];
File projectRelativeFile = new File(eclipseProjectDir, file.getName());
if (projectRelativeFile.isDirectory()) {
// just ignore?
getLog().warn(//$NON-NLS-1$
Messages.getString(//$NON-NLS-1$
"EclipsePlugin.foundadir", projectRelativeFile.getAbsolutePath()));
}
try {
projectRelativeFile.getParentFile().mkdirs();
if (file.getContent() == null) {
if (file.getLocation() != null) {
InputStream inStream = locator.getResourceAsInputStream(file.getLocation());
OutputStream outStream = new FileOutputStream(projectRelativeFile);
try {
IOUtil.copy(inStream, outStream);
} finally {
IOUtil.close(inStream);
IOUtil.close(outStream);
}
} else {
URL url = file.getURL();
String endPointUrl = url.getProtocol() + "://" + url.getAuthority();
// Repository Id should be ignored by Wagon ...
Repository repository = new Repository("additonal-configs", endPointUrl);
Wagon wagon = wagonManager.getWagon(repository);
;
if (logger.isDebugEnabled()) {
Debug debug = new Debug();
wagon.addSessionListener(debug);
wagon.addTransferListener(debug);
}
wagon.setTimeout(1000);
Settings settings = mavenSettingsBuilder.buildSettings();
ProxyInfo proxyInfo = null;
if (settings != null && settings.getActiveProxy() != null) {
Proxy settingsProxy = settings.getActiveProxy();
proxyInfo = new ProxyInfo();
proxyInfo.setHost(settingsProxy.getHost());
proxyInfo.setType(settingsProxy.getProtocol());
proxyInfo.setPort(settingsProxy.getPort());
proxyInfo.setNonProxyHosts(settingsProxy.getNonProxyHosts());
proxyInfo.setUserName(settingsProxy.getUsername());
proxyInfo.setPassword(settingsProxy.getPassword());
}
if (proxyInfo != null) {
wagon.connect(repository, wagonManager.getAuthenticationInfo(repository.getId()), proxyInfo);
} else {
wagon.connect(repository, wagonManager.getAuthenticationInfo(repository.getId()));
}
wagon.get(url.getPath(), projectRelativeFile);
}
} else {
FileUtils.fileWrite(projectRelativeFile.getAbsolutePath(), file.getContent());
}
} catch (WagonException e) {
throw new MojoExecutionException(Messages.getString("EclipsePlugin.remoteexception", new Object[] { file.getURL(), e.getMessage() }));
} catch (IOException e) {
throw new MojoExecutionException(Messages.getString("EclipsePlugin.cantwritetofile", projectRelativeFile.getAbsolutePath()));
} catch (ResourceNotFoundException e) {
throw new MojoExecutionException(Messages.getString("EclipsePlugin.cantfindresource", file.getLocation()));
} catch (XmlPullParserException e) {
throw new MojoExecutionException(Messages.getString("EclipsePlugin.settingsxmlfailure", e.getMessage()));
}
}
}
}Example 49
| Project: haxemojos-master File: RepositorySystemStub.java View source code |
@Override
public void injectProxy(List<ArtifactRepository> repositories, List<Proxy> proxies) {
//To change body of implemented methods use File | Settings | File Templates.
}