List of usage examples for java.net Proxy Proxy
public Proxy(Type type, SocketAddress sa)
From source file:manchester.synbiochem.datacapture.SeekConnector.java
@Value("${outgoing.proxy}") public void setProxy(String proxy) { if ("IGNORE".equals(proxy)) { this.proxy = null; return;//from w ww. j a v a 2 s .c om } String[] split = proxy.split(":"); int port = Integer.parseInt(split[1]); this.proxy = new Proxy(HTTP, new InetSocketAddress(split[0], port)); }
From source file:com.googlecode.jmxtrans.model.output.StackdriverWriter.java
@JsonCreator public StackdriverWriter(@JsonProperty("typeNames") ImmutableList<String> typeNames, @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("debug") Boolean debugEnabled, @JsonProperty("gatewayUrl") String gatewayUrl, @JsonProperty("apiKey") String apiKey, @JsonProperty("proxyHost") String proxyHost, @JsonProperty("proxyPort") Integer proxyPort, @JsonProperty("prefix") String prefix, @JsonProperty("timeoutInMillis") Integer timeoutInMillis, @JsonProperty("source") String source, @JsonProperty("detectInstance") String detectInstance, @JsonProperty("settings") Map<String, Object> settings) throws MalformedURLException { super(typeNames, booleanAsNumber, debugEnabled, settings); this.gatewayUrl = new URL(firstNonNull(gatewayUrl, (String) getSettings().get(SETTING_STACKDRIVER_API_URL), DEFAULT_STACKDRIVER_API_URL)); this.apiKey = MoreObjects.firstNonNull(apiKey, (String) getSettings().get(SETTING_STACKDRIVER_API_KEY)); // Proxy configuration if (proxyHost == null) { proxyHost = (String) getSettings().get(SETTING_PROXY_HOST); }//from ww w . j av a 2 s. c o m if (proxyPort == null) { proxyPort = (Integer) getSettings().get(SETTING_PROXY_PORT); } this.proxyHost = proxyHost; this.proxyPort = proxyPort; if (!isNullOrEmpty(this.proxyHost)) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort)); } else { proxy = null; } // Prefix this.prefix = firstNonNull(prefix, (String) getSettings().get(SETTING_PREFIX), ""); if (!isNullOrEmpty(this.prefix)) { if (!isAlphanumeric(this.prefix)) { throw new IllegalArgumentException("Prefix setting must be alphanumeric only [A-Za-z0-9]"); } } logger.info("Setting prefix to " + this.prefix); this.timeoutInMillis = firstNonNull(timeoutInMillis, Settings.getIntegerSetting(getSettings(), SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS, null), DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS); // try to get and instance ID if (source == null) { source = (String) getSettings().get(SETTING_SOURCE_INSTANCE); } this.source = source; if (detectInstance == null) { detectInstance = (String) getSettings().get(SETTING_DETECT_INSTANCE); } this.detectInstance = detectInstance; this.instanceId = computeInstanceId(this.source, this.detectInstance); }
From source file:org.jmxtrans.embedded.output.CopperEggWriter.java
/** * Load settings//from w w w .j av a2 s .co m */ @Override public void start() { config_location = DEFAULT_COPPEREGG_CONFIGURATION_PATH; String path = config_location.substring("classpath:".length()); long thisPID = getPID(); if (myPID == thisPID) { logger.info("Started from two threads with the same PID, {}", thisPID); return; } myPID = thisPID; try { String str = String.valueOf(myPID); url_str = getStringSetting(SETTING_URL, DEFAULT_COPPEREGG_API_URL); url = new URL(url_str); user = getStringSetting(SETTING_USERNAME); token = getStringSetting(SETTING_TOKEN); user = token; basicAuthentication = Base64Variants.getDefaultVariant() .encode((user + ":" + "U").getBytes(Charset.forName("US-ASCII"))); if (getStringSetting(SETTING_PROXY_HOST, null) != null && !getStringSetting(SETTING_PROXY_HOST).isEmpty()) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getStringSetting(SETTING_PROXY_HOST), getIntSetting(SETTING_PROXY_PORT))); } coppereggApiTimeoutInMillis = getIntSetting(SETTING_COPPEREGG_API_TIMEOUT_IN_MILLIS, DEFAULT_COPPEREGG_API_TIMEOUT_IN_MILLIS); source = getStringSetting(SETTING_SOURCE, DEFAULT_SOURCE); source = getStrategy().resolveExpression(source); myhost = source; myPID_host = myhost + '.' + str; try { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); if (in == null) { logger.warn("No file found for classpath:" + config_location); } else { read_config(in); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in start " + e); } ensure_metric_groups(); ensure_dashboards(); logger.info("jvm_os_groupID : {}", jvm_os_groupID); logger.info("jvm_gc_groupID : {}", jvm_gc_groupID); logger.info("jvm_runtime_groupID : {}", jvm_runtime_groupID); logger.info("jvm_class_groupID : {}", jvm_class_groupID); logger.info("jvm_thread_groupID : {}", jvm_thread_groupID); logger.info("heap_metric_groupID : {}", heap_metric_groupID); logger.info("nonheap_metric_groupID : {}", nonheap_metric_groupID); logger.info("tomcat_thread_pool_groupID : {}", tomcat_thread_pool_groupID); logger.info("tomcat_grp_groupID : {}", tomcat_grp_groupID); logger.info("tomcat_servlet_groupID : {}", tomcat_servlet_groupID); logger.info("tomcat_manager_groupID : {}", tomcat_manager_groupID); logger.info("tomcat_db_groupID : {}", tomcat_db_groupID); logger.info("jmxtrans_metric_groupID : {}", jmxtrans_metric_groupID); logger.info("app_groupID : {}", app_groupID); logger.info("app_sales_groupID : {}", app_sales_groupID); logger.info("Started CopperEggWriter Successfully on jvm '{}', connected to '{}', proxy {}", myPID_host, url, proxy); } catch (MalformedURLException e) { exceptionCounter.incrementAndGet(); throw new EmbeddedJmxTransException(e); } }
From source file:org.apache.pig.shock.SSHSocketImplFactory.java
public Socket createSocket(String host, int port) throws IOException, UnknownHostException { String socksHost = System.getProperty("socksProxyHost"); Socket s;//from w w w . j a v a2s .com InetSocketAddress addr = new InetSocketAddress(host, port); if (socksHost != null) { Proxy proxy = new Proxy(Type.SOCKS, new InetSocketAddress(socksHost, 1080)); s = new Socket(proxy); s.connect(addr); } else { log.error(addr); SocketChannel sc = SocketChannel.open(addr); s = sc.socket(); } s.setTcpNoDelay(true); return s; }
From source file:info.joseluismartin.gtc.mvc.CacheController.java
public void init() throws ServletException { List<ProxyConfig> list = proxyService.getAll(); if (!list.isEmpty()) { ProxyConfig config = list.get(0); if (!config.isDirectConnection()) { proxyHost = config.getHost(); proxyPort = config.getPort(); proxyUser = config.getUserName(); proxyPassword = config.getPassword(); SocketAddress address = new InetSocketAddress(proxyHost, proxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); Authenticator.setDefault(new SimpleAuthenticator(proxyUser, proxyPassword)); log.info("Using proxy: " + proxyHost + ":" + proxyPort); }// ww w.jav a 2s . c o m } }
From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java
protected HttpsURLConnection openUrlConnection(String url, SSLContext sslContext) throws IOException { DockerPort dockerPort = docker.containers().container("squid").port(3128); HttpsURLConnection httpURLConnection = (HttpsURLConnection) new URL(url).openConnection(new Proxy( Proxy.Type.HTTP, new InetSocketAddress(dockerPort.getIp(), dockerPort.getExternalPort()))); httpURLConnection.setSSLSocketFactory(sslContext.getSocketFactory()); return httpURLConnection; }
From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java
@Test public void httpProxy_fromSystemProperty() throws Exception { ProxySelector defaultProxySelector = ProxySelector.getDefault(); try {// w w w . j a v a2 s . com ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(URI uri) { InetSocketAddress address = new InetSocketAddress(HTTP_PROXY.getHost(), HTTP_PROXY.getPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); return Collections.singletonList(proxy); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { } }); String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) .properties(new String[] { "spring.cloud.config.server.git.uri=" + repoUrl }).run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class), hasProperty("message", containsString(HTTP_PROXY.getHost())))); makeRequest(httpClient, "http://somehost"); } finally { ProxySelector.setDefault(defaultProxySelector); } }
From source file:org.kawanfw.sql.api.client.RemoteDriver.java
/** * Attempts to make a database connection to the given URL. * /*w ww . java 2 s .co m*/ * The driver will return "null" if it realizes it is the wrong kind of * driver to connect to the given URL. {@link #acceptsURL} will return null. * * <P> * The driver will throw<code>SQLException</code> if it is the right driver * to connect to the given URL but has trouble connecting to the database. * * <P> * The <code>java.util.Properties</code> argument can be used to pass * arbitrary string tag/value pairs as connection arguments. At least "user" * and "password" properties should be included in the * <code>Properties</code> object. * * @param url * the URL of the database to which to connect * @param info * a list of arbitrary string tag/value pairs as connection * arguments. At least a "user" and "password" property should be * included. * @return a <code>Connection</code> object that represents a connection to * the URL * @exception SQLException * if a database access error occurs */ @Override public Connection connect(String url, Properties info) throws SQLException { if (url == null) { throw new SQLException("url not set. Please provide an url."); } if (!acceptsURL(url)) { return null; } Properties info2 = new Properties(); RemoteDriverUtil.copyProperties(info, info2); // Properties may be passed in url if (url.contains("?")) { String query = StringUtils.substringAfter(url, "?"); Map<String, String> mapProps = RemoteDriverUtil.getQueryMap(query); Set<String> set = mapProps.keySet(); for (String propName : set) { info2.setProperty(propName, mapProps.get(propName)); } url = StringUtils.substringBefore(url, "?"); } String username = info2.getProperty("user"); String password = info2.getProperty("password"); if (username == null) { throw new SQLException("user not set. Please provide a user."); } if (password == null) { throw new SQLException("password not set. Please provide a password."); } // Add proxy lookup String proxyType = info2.getProperty("proxyType"); String proxyHostname = info2.getProperty("proxyHostname"); String proxyPort = info2.getProperty("proxyPort"); String proxyUsername = info2.getProperty("proxyUsername"); String proxyPassword = info2.getProperty("proxyPassword"); String statelessMode = info2.getProperty("statelessMode"); String joinResultSetMetaData = info2.getProperty("joinResultSetMetaData"); String zipResultSet = info2.getProperty("zipResultSet"); int port = -1; Proxy proxy = null; if (proxyHostname != null) { try { port = Integer.parseInt(proxyPort); } catch (NumberFormatException e) { throw new SQLException("Invalid proxy port. Port is not numeric: " + proxyPort); } if (proxyType == null) { proxyType = "HTTP"; } proxy = new Proxy(Type.valueOf(proxyType), new InetSocketAddress(proxyHostname, port)); } boolean statelessModeBoolean = Boolean.parseBoolean(statelessMode); SessionParameters sessionParameters = getSessionParameters(info2); debug(sessionParameters.toString()); // if (url.startsWith("jdbc:kawanfw://")) { // url = url.replace("jdbc:kawanfw", "http"); // } // If we have passed the "proxy" property, build back the // instance from the property value // 1) Treat the case the user did a property.put(proxy) instead of // property.setProperty(proxy.toString()) if (proxy == null) { Object objProxy = info2.get("proxy"); if (objProxy != null && objProxy instanceof Proxy) { proxy = (Proxy) proxy; } // 2) Treat the case the user as correctly used // property.setProperty(httpProxy.toString()) else { String proxyStr = info2.getProperty("proxy"); debug("proxyStr:" + proxyStr); if (proxyStr != null) { proxy = RemoteDriverUtil.buildProxy(proxyStr); } } } // If we have passed the "sessionParameters" property, build back // the // instance from the property value // 1) Treat the case the user did a property.put(sessionParameters) // instead of property.setProperty(sessionParameters.toString()) Object objSessionParameters = info2.get("sessionParameters"); if (objSessionParameters != null && objSessionParameters instanceof SessionParameters) { String jsonString = SessionParametersGson.toJson((SessionParameters) (objSessionParameters)); if (jsonString != null) { sessionParameters = SessionParametersGson.fromJson(jsonString); } } // 2) Treat the case the user as correctly used // property.setProperty(sessionParameters.toString()) else { String jsonString = info2.getProperty("sessionParameters"); if (jsonString != null) { sessionParameters = SessionParametersGson.fromJson(jsonString); } } debug("url : " + url); debug("Proxy : " + proxy); debug("sessionParameters: " + sessionParameters); boolean doJoinResultSetMetaData = false; if (joinResultSetMetaData != null) { doJoinResultSetMetaData = Boolean.parseBoolean(joinResultSetMetaData); debug("joinResultSetMetaData: " + doJoinResultSetMetaData); } PasswordAuthentication passwordAuthentication = null; if (proxy != null && proxyUsername != null) { passwordAuthentication = new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()); } boolean doZipResultSet = true; if (zipResultSet != null) { doZipResultSet = Boolean.parseBoolean(zipResultSet); debug("zipResultSet: " + doZipResultSet); } Connection connection = new RemoteConnection(url, username, password.toCharArray(), proxy, passwordAuthentication, sessionParameters, statelessModeBoolean, doJoinResultSetMetaData, doZipResultSet); return connection; }
From source file:org.eclipsetrader.archipelago.Level2Feed.java
@Override public void run() { String HOST = "datasvr.tradearca.com"; Set<String> sTit = new HashSet<String>(); for (int i = 0; i < 5 && !stopping; i++) { try {//www . ja v a 2s. c o m Proxy socksProxy = Proxy.NO_PROXY; if (ArchipelagoPlugin.getDefault() != null) { BundleContext context = ArchipelagoPlugin.getDefault().getBundle().getBundleContext(); ServiceReference reference = context.getServiceReference(IProxyService.class.getName()); if (reference != null) { IProxyService proxy = (IProxyService) context.getService(reference); IProxyData data = proxy.getProxyDataForHost(HOST, IProxyData.SOCKS_PROXY_TYPE); if (data != null) { if (data.getHost() != null) { socksProxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(data.getHost(), data.getPort())); } } context.ungetService(reference); } } socket = new Socket(socksProxy); socket.connect(new InetSocketAddress(HOST, 80)); os = new BufferedOutputStream(socket.getOutputStream()); is = new BufferedReader(new InputStreamReader(socket.getInputStream())); os.write("GET http://datasvr.tradearca.com/zrepeaterz/ HTTP/1.1\r\n\r\n".getBytes()); os.write("LogonRequest=DISABLED\r\n".getBytes()); os.flush(); break; } catch (Exception e) { Status status = new Status(IStatus.ERROR, ArchipelagoPlugin.PLUGIN_ID, 0, "Error connecting to server", e); ArchipelagoPlugin.log(status); try { if (socket != null) { socket.close(); } } catch (Exception e1) { } socket = null; is = null; os = null; } } if (socket == null || os == null || is == null) { thread = null; return; } while (!stopping) { try { if (subscriptionsChanged) { Set<String> toAdd = new HashSet<String>(); Set<String> toRemove = new HashSet<String>(); synchronized (symbolSubscriptions) { for (String s : symbolSubscriptions.keySet()) { if (!sTit.contains(s)) { toAdd.add(s); } } for (String s : sTit) { if (!symbolSubscriptions.containsKey(s)) { toRemove.add(s); } } subscriptionsChanged = false; } if (toRemove.size() != 0) { for (String s : toRemove) { os.write("MsgType=UnregisterBook&Symbol=".getBytes()); os.write(s.getBytes()); os.write("\r\n".getBytes()); } logger.info("Removing " + toRemove); os.flush(); } if (toAdd.size() != 0) { for (String s : toAdd) { os.write("MsgType=RegisterBook&Symbol=".getBytes()); os.write(s.getBytes()); os.write("\r\n".getBytes()); } logger.info("Adding " + toAdd); os.flush(); } sTit.removeAll(toRemove); sTit.addAll(toAdd); } if (!is.ready()) { try { Thread.sleep(100); } catch (Exception e) { } continue; } String inputLine = is.readLine(); if (inputLine.startsWith("BK&")) { String[] sections = inputLine.split("&"); if (sections.length < 4) { continue; } String symbol = sections[1]; int index = 0, item = 0; String[] elements = sections[2].split("#"); List<BookEntry> bid = new ArrayList<BookEntry>(); while (index < elements.length) { Double price = new Double(elements[index++]); Long quantity = new Long(elements[index++]); index++; // Time String id = elements[index++]; bid.add(new BookEntry(null, price, quantity, 1L, id)); item++; } index = 0; item = 0; elements = sections[3].split("#"); List<BookEntry> ask = new ArrayList<BookEntry>(); while (index < elements.length) { Double price = new Double(elements[index++]); Long quantity = new Long(elements[index++]); index++; // Time String id = elements[index++]; ask.add(new BookEntry(null, price, quantity, 1L, id)); item++; } FeedSubscription subscription = symbolSubscriptions.get(symbol); if (subscription != null) { IBook oldValue = subscription.getBook(); IBook newValue = new org.eclipsetrader.core.feed.Book( bid.toArray(new IBookEntry[bid.size()]), ask.toArray(new IBookEntry[ask.size()])); subscription.setBook(newValue); subscription.addDelta(new QuoteDelta(subscription.getIdentifier(), oldValue, newValue)); subscription.fireNotification(); } } } catch (SocketException e) { for (int i = 0; i < 5 && !stopping; i++) { try { socket = new Socket("datasvr.tradearca.com", 80); is = new BufferedReader(new InputStreamReader(socket.getInputStream())); os = new BufferedOutputStream(socket.getOutputStream()); os.write("GET http://datasvr.tradearca.com/zrepeaterz/ HTTP/1.1\r\n\r\n".getBytes()); os.write("LogonRequest=DISABLED\r\n".getBytes()); os.flush(); for (String s : sTit) { os.write("MsgType=RegisterBook&Symbol=".getBytes()); os.write(s.getBytes()); os.write("\r\n".getBytes()); } os.flush(); break; } catch (Exception e1) { Status status = new Status(IStatus.ERROR, ArchipelagoPlugin.PLUGIN_ID, 0, "Error connecting to server", e); ArchipelagoPlugin.log(status); } } if (socket == null || os == null || is == null) { thread = null; return; } } catch (Exception e) { Status status = new Status(IStatus.ERROR, ArchipelagoPlugin.PLUGIN_ID, 0, "Error receiving stream", e); ArchipelagoPlugin.log(status); break; } } try { if (socket != null) { socket.close(); } socket = null; os = null; is = null; } catch (Exception e) { // Do nothing } thread = null; }
From source file:com.yahoo.druid.hadoop.HiveDatasourceInputFormat.java
private String getSegmentsToLoad(String dataSource, List<Interval> intervals, String overlordUrl) throws MalformedURLException { logger.info("CheckPost7"); String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action"; logger.info("Sending request to overlord at " + urlStr); Interval interval = intervals.get(0); String requestJson = getSegmentListUsedActionJson(interval.toString()); logger.info("request json is " + requestJson); int numTries = 3; for (int trial = 0; trial < numTries; trial++) { try {//from w ww. j a v a2 s .co m logger.info("attempt number {} to get list of segments from overlord", trial); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("httpproxy-prod.blue.ygrid.yahoo.com", 4080)); URL url = new URL(String.format("%s/druid/coordinator/v1/metadata/datasources/%s/segments?full", overlordUrl, dataSource)); //new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); conn.setRequestMethod("POST"); conn.setRequestProperty("content-type", "application/json"); conn.setRequestProperty("Accept", "*/*"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setConnectTimeout(60000); conn.usingProxy(); OutputStream out = conn.getOutputStream(); out.write(requestJson.getBytes()); out.close(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { return IOUtils.toString(conn.getInputStream()); } else { logger.warn( "Attempt Failed to get list of segments from overlord. response code [%s] , response [%s]", responseCode, IOUtils.toString(conn.getInputStream())); } } catch (Exception ex) { logger.warn("Exception in getting list of segments from overlord", ex); } try { Thread.sleep(5000); //wait before next trial } catch (InterruptedException ex) { Throwables.propagate(ex); } } throw new RuntimeException( String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]", dataSource, interval, overlordUrl)); }