List of usage examples for java.net Proxy Proxy
public Proxy(Type type, SocketAddress sa)
From source file:org.jboss.tools.ws.ui.utils.JAXRSTester.java
/** * Call a JAX-RS service//from w w w . ja v a 2 s .c o m * @param address * @param parameters * @param headers * @param methodType * @param requestBody * @param proxy * @param port * @throws Exception */ public void doTest(String address, Map<String, String> parameters, Map<String, String> headers, String methodType, String requestBody, String proxy, int port, String uid, String pwd) throws Exception { // handle the proxy Proxy proxyObject = null; if (proxy != null && proxy.length() > 0 && port > 0) { InetSocketAddress proxyAddress = new InetSocketAddress(proxy, port); proxyObject = new Proxy(Proxy.Type.HTTP, proxyAddress); } // clear the returned results resultBody = EMPTY_STRING; // get the parms string String query = buildWebQuery(parameters); // Clear the address of any leading/trailing spaces address = address.trim(); // build the complete URL URL url = null; if (query != null && query.trim().length() > 0) { // add the ? if there are parameters if (!address.endsWith("?") && !address.contains("?")) {//$NON-NLS-1$ //$NON-NLS-2$ // if we're a "GET" - add the ? by default if (methodType.equalsIgnoreCase("GET")) { //$NON-NLS-1$ address = address + "?"; //$NON-NLS-1$ // if we're a PUT or POST, check if we have parms // and add the ? if we do } else if (methodType.equalsIgnoreCase("POST")//$NON-NLS-1$ || methodType.equalsIgnoreCase("PUT") //$NON-NLS-1$ || methodType.equalsIgnoreCase("DELETE")) { //$NON-NLS-1$ if (query.trim().length() > 0) { address = address + "?"; //$NON-NLS-1$ } } } else if (address.contains("?")) { //$NON-NLS-1$ address = address + "&"; //$NON-NLS-1$ } // add parms to the url if we have some url = new URL(address + query); } else { url = new URL(address); } // make connection HttpURLConnection httpurlc = null; if (proxyObject == null) { httpurlc = (HttpURLConnection) url.openConnection(); } else { // if have proxy, pass it along httpurlc = (HttpURLConnection) url.openConnection(proxyObject); } // since we are expecting output back, set to true httpurlc.setDoOutput(true); // not sure what this does - may be used for authentication? httpurlc.setAllowUserInteraction(false); // set whether this is a GET or POST httpurlc.setRequestMethod(methodType); // if we have headers to add if (headers != null && !headers.isEmpty()) { Iterator<?> iter = headers.entrySet().iterator(); while (iter.hasNext()) { Entry<?, ?> entry = (Entry<?, ?>) iter.next(); if (entry.getKey() != null && entry.getKey() instanceof String) httpurlc.addRequestProperty((String) entry.getKey(), (String) entry.getValue()); } } // if we have basic authentication to add, add it! if (uid != null && pwd != null) { String authStr = uid + ':' + pwd; byte[] authEncByte = Base64.encodeBase64(authStr.getBytes()); String authStringEnc = new String(authEncByte); httpurlc.addRequestProperty("Authorization", "Basic " + authStringEnc); //$NON-NLS-1$//$NON-NLS-2$ } requestHeaders = httpurlc.getRequestProperties(); // Check if task has been interrupted if (Thread.interrupted()) { throw new InterruptedException(); } // CONNECT! httpurlc.connect(); // Check if task has been interrupted if (Thread.interrupted()) { throw new InterruptedException(); } // If we are doing a POST and we have some request body to pass along, do it if (requestBody != null && (methodType.equalsIgnoreCase("POST") //$NON-NLS-1$ || methodType.equalsIgnoreCase("PUT"))) { //$NON-NLS-1$ requestBody = WSTestUtils.stripNLsFromXML(requestBody); OutputStreamWriter out = new OutputStreamWriter(httpurlc.getOutputStream()); String stripped = stripCRLF(requestBody); out.write(stripped); out.close(); } // Check if task has been interrupted if (Thread.interrupted()) { throw new InterruptedException(); } // if we have headers to pass to user, copy them if (httpurlc.getHeaderFields() != null) { resultHeaders = httpurlc.getHeaderFields(); } // retrieve result and put string results into the response InputStream is = null; try { is = httpurlc.getInputStream(); // Check if task has been interrupted if (Thread.interrupted()) { throw new InterruptedException(); } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$ StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n");//$NON-NLS-1$ } br.close(); resultBody = sb.toString(); // Check if task has been interrupted if (Thread.interrupted()) { throw new InterruptedException(); } } catch (IOException ie) { try { is = httpurlc.getErrorStream(); // is possible that we're getting nothing back in the error stream if (is != null) { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//$NON-NLS-1$ StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n");//$NON-NLS-1$ } br.close(); resultBody = sb.toString(); } } catch (IOException ie2) { resultBody = ie2.getLocalizedMessage(); } } // as a last resort, if we still have nothing to report, // show an error message to the user if (resultBody == null || resultBody.trim().isEmpty()) { resultBody = JBossWSUIMessages.JAXRSRSTestView_Message_Unsuccessful_Test; } // disconnect explicitly (may not be necessary) httpurlc.disconnect(); }
From source file:org.wso2.carbon.identity.provisioning.duo.DuoHttp.java
public void setProxy(String host, int port) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); }
From source file:com.cisco.gerrit.plugins.slack.client.WebhookClient.java
/** * Opens a connection to the provided Webhook URL. * * @param webhookUrl The Webhook URL to open a connection to. * @return The open connection to the provided Webhook URL. *//* w ww. j a v a2 s .c om*/ private HttpURLConnection openConnection(String webhookUrl) { try { HttpURLConnection connection; if (StringUtils.isNotBlank(config.getProxyHost())) { LOGGER.info("Connecting via proxy"); if (StringUtils.isNotBlank(config.getProxyUsername())) { Authenticator authenticator; authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(config.getProxyUsername(), config.getProxyPassword().toCharArray())); } }; Authenticator.setDefault(authenticator); } Proxy proxy; proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort())); connection = (HttpURLConnection) new URL(webhookUrl).openConnection(proxy); } else { LOGGER.info("Connecting directly"); connection = (HttpURLConnection) new URL(webhookUrl).openConnection(); } return connection; } catch (MalformedURLException e) { throw new RuntimeException("Unable to create webhook URL: " + webhookUrl, e); } catch (IOException e) { throw new RuntimeException("Error opening connection to Slack URL: [" + e.getMessage() + "].", e); } }
From source file:in.goahead.apps.util.URLUtils.java
public static Proxy getProxy() { Proxy proxy = null;/*from ww w . ja v a 2s. c o m*/ String proxyType = System.getProperty("YAYTD.PROXY_TYPE"); String proxyServer = System.getProperty("YAYTD.PROXY_SERVER"); String proxyPort = System.getProperty("YAYTD.PROXY_PORT"); try { if (proxyType != null && proxyServer != null && proxyPort != null) { proxy = new Proxy(Proxy.Type.valueOf(proxyType), new InetSocketAddress(proxyServer, Integer.parseInt(proxyPort))); } } catch (IllegalArgumentException ile) { ile.printStackTrace(); } return proxy; }
From source file:cc.arduino.net.CustomProxySelector.java
private Proxy makeProxyFrom(String proxyConfigs) { String proxyConfig = proxyConfigs.split(";")[0]; if (proxyConfig.startsWith("DIRECT")) { return Proxy.NO_PROXY; }/*from ww w.j a va 2 s . co m*/ Proxy.Type type; if (proxyConfig.startsWith("PROXY")) { type = Proxy.Type.HTTP; proxyConfig = proxyConfig.replace("PROXY ", ""); } else { type = Proxy.Type.SOCKS; proxyConfig = proxyConfig.replace("SOCKS ", ""); } String[] hostPort = proxyConfig.split(":"); return new Proxy(type, new InetSocketAddress(hostPort[0], Integer.valueOf(hostPort[1]))); }
From source file:com.blackducksoftware.integration.hub.cli.CLIDownloadService.java
public void customInstall(HubProxyInfo hubProxyInfo, CLILocation cliLocation, CIEnvironmentVariables ciEnvironmentVariables, final URL archive, String hubVersion, final String localHostName) throws IOException, InterruptedException, HubIntegrationException, IllegalArgumentException, EncryptionException { boolean cliMismatch = true; try {// www .j a v a 2s . com final File hubVersionFile = cliLocation.createHubVersionFile(); if (hubVersionFile.exists()) { final String storedHubVersion = IOUtils.toString(new FileReader(hubVersionFile)); if (hubVersion.equals(storedHubVersion)) { cliMismatch = false; } else { hubVersionFile.delete(); hubVersionFile.createNewFile(); } } final File cliInstallDirectory = cliLocation.getCLIInstallDir(); if (!cliInstallDirectory.exists()) { cliMismatch = true; } if (cliMismatch) { logger.debug("Attempting to download the Hub CLI."); final FileWriter writer = new FileWriter(hubVersionFile); writer.write(hubVersion); writer.close(); hubVersionFile.setLastModified(0L); } final long cliTimestamp = hubVersionFile.lastModified(); URLConnection connection = null; try { Proxy proxy = null; if (hubProxyInfo != null) { String proxyHost = hubProxyInfo.getHost(); int proxyPort = hubProxyInfo.getPort(); String proxyUsername = hubProxyInfo.getUsername(); String proxyPassword = hubProxyInfo.getDecryptedPassword(); if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } if (proxy != null) { if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) { AuthenticatorUtil.setAuthenticator(proxyUsername, proxyPassword); } else { AuthenticatorUtil.resetAuthenticator(); } } } if (proxy != null) { connection = archive.openConnection(proxy); } else { connection = archive.openConnection(); } connection.setIfModifiedSince(cliTimestamp); connection.connect(); } catch (final IOException ioe) { logger.error("Skipping installation of " + archive + " to " + cliLocation.getCanonicalPath() + ": " + ioe.toString()); return; } if (connection instanceof HttpURLConnection && ((HttpURLConnection) connection).getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { // CLI has not been modified return; } final long sourceTimestamp = connection.getLastModified(); if (cliInstallDirectory.exists() && cliInstallDirectory.listFiles().length > 0) { if (!cliMismatch && sourceTimestamp == cliTimestamp) { logger.debug("The current Hub CLI is up to date."); return; } for (final File file : cliInstallDirectory.listFiles()) { FileUtils.deleteDirectory(file); } } else { cliInstallDirectory.mkdir(); } logger.debug("Updating the Hub CLI."); hubVersionFile.setLastModified(sourceTimestamp); logger.info("Unpacking " + archive.toString() + " to " + cliInstallDirectory.getCanonicalPath() + " on " + localHostName); final CountingInputStream cis = new CountingInputStream(connection.getInputStream()); try { unzip(cliInstallDirectory, cis, logger); updateJreSecurity(logger, cliLocation, ciEnvironmentVariables); } catch (final IOException e) { throw new IOException(String.format("Failed to unpack %s (%d bytes read of total %d)", archive, cis.getByteCount(), connection.getContentLength()), e); } } catch (final IOException e) { throw new IOException("Failed to install " + archive + " to " + cliLocation.getCanonicalPath(), e); } }
From source file:hudson.ProxyConfiguration.java
public static Proxy createProxy(String host, String name, int port, String noProxyHost) { if (host != null && noProxyHost != null) { for (Pattern p : getNoProxyHostPatterns(noProxyHost)) { if (p.matcher(host).matches()) return Proxy.NO_PROXY; }/* www.j a v a 2 s. co m*/ } return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(name, port)); }
From source file:fr.xebia.confluence.gist.GistMacro.java
private String fetchGistUrl(String gistUrl, String proxyHost, String proxyPort) throws MacroException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); InputStream in = null;/*from w ww . j a v a2 s .com*/ try { URL url = new URL(gistUrl); URLConnection c; if (proxyHost != null) { int port; if (proxyPort == null) { port = 80; } else { port = Integer.parseInt(proxyPort); } Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, port)); c = url.openConnection(proxy); } else { c = url.openConnection(); } in = c.getInputStream(); IOUtils.copy(in, pw, settingsManager.getGlobalSettings().getDefaultEncoding()); pw.flush(); sw.flush(); return sw.toString(); } catch (IOException e) { String message = ConfluenceActionSupport.getTextStatic(COULD_NOT_FETCH_URL_CONTENTS_ERROR_KEY, new String[] { gistUrl, e.getMessage() }); throw new MacroException(message, e); } finally { Closeables.closeQuietly(pw); Closeables.closeQuietly(sw); Closeables.closeQuietly(in); } }
From source file:org.sonarqube.ws.client.HttpConnectorTest.java
@Test public void use_proxy_authentication() throws Exception { MockWebServer proxy = new MockWebServer(); proxy.start();/*from w w w .j av a2 s. c o m*/ underTest = HttpConnector.newBuilder().url(serverUrl) .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHostName(), proxy.getPort()))) .proxyCredentials("theProxyLogin", "theProxyPassword").build(); GetRequest request = new GetRequest("api/issues/search"); proxy.enqueue(new MockResponse().setResponseCode(407)); proxy.enqueue(new MockResponse().setBody("OK!")); underTest.call(request); RecordedRequest recordedRequest = proxy.takeRequest(); assertThat(recordedRequest.getHeader("Proxy-Authorization")).isNull(); recordedRequest = proxy.takeRequest(); assertThat(recordedRequest.getHeader("Proxy-Authorization")) .isEqualTo(basic("theProxyLogin", "theProxyPassword")); }