List of usage examples for java.net Proxy Proxy
public Proxy(Type type, SocketAddress sa)
From source file:com.msopentech.thali.utilities.test.NetworkPerfTests.java
@Override public void setUp() throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException, InterruptedException { if (perfListenerHttpKeyTypes == null) { perfThaliListener = getStartedListener("automaticPerfListener"); perfListenerHttpKeyTypes = perfThaliListener.getHttpKeys(); }/*from ww w . j av a 2s.co m*/ noTorHttpListenerKey = new HttpKeyURL(perfListenerHttpKeyTypes.getLocalMachineIPHttpKeyURL()); torHttpListenerKey = new HttpKeyURL(perfListenerHttpKeyTypes.getOnionHttpKeyURL()); proxyPort = Integer.parseInt(perfListenerHttpKeyTypes.getSocksOnionProxyPort()); torSocksProxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort)); configureRequestObjects = new ConfigureRequestObjects(noTorHttpListenerKey.getHost(), noTorHttpListenerKey.getPort(), torHttpListenerKey.getHost(), torHttpListenerKey.getPort(), ThaliCryptoUtilities.DefaultPassPhrase, getCreateClientBuilder(), getNewRandomCouchBaseContext(), null, torSocksProxy); HttpKeyTypes httpKeyTypes = new HttpKeyTypes(noTorHttpListenerKey, torHttpListenerKey, proxyPort); relayWebServer = new RelayWebServer(getCreateClientBuilder(), getNewRandomCouchBaseContext().getFilesDir(), httpKeyTypes, relayHost, relayPort); relayWebServer.start(); CouchDbConnector replicationDbConnector = configureRequestObjects.thaliCouchDbInstance .createConnector(ReplicationManager.replicationDatabaseName, false); for (String docId : replicationDbConnector.getAllDocIds()) { String currentRevision = replicationDbConnector.getCurrentRevision(docId); replicationDbConnector.delete(docId, currentRevision); } localName = configureRequestObjects.testDatabaseConnector.getDatabaseName(); remoteName = configureRequestObjects.replicationDatabaseConnector.getDatabaseName(); targetNoTorReplicationUrl = noTorHttpListenerKey + remoteName; targetTorReplicationUrl = torHttpListenerKey + remoteName; configureRequestObjects.thaliCouchDbInstance.deleteDatabase(localName); configureRequestObjects.thaliCouchDbInstance.deleteDatabase(remoteName); configureRequestObjects.testDatabaseConnector.createDatabaseIfNotExists(); configureRequestObjects.replicationDatabaseConnector.createDatabaseIfNotExists(); }
From source file:com.francetelecom.clara.cloud.paas.it.services.helper.PaasServicesEnvApplicationAccessHelper.java
/** * Check if a string appear in the html page * * @param url//from www . j a v a 2 s . c om * URL to test * @param token * String that must be in html page * @return Cookie that identifies the was or null if the test failed. An * empty string means that no cookie was found in the request, but * the check succeeded. */ private static String checkStringAndReturnCookie(URL url, String token, String httpProxyHost, int httpProxyPort) { InputStream is = null; String cookie = null; try { HttpURLConnection connection; if (httpProxyHost != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod("GET"); is = connection.getInputStream(); // check http status code if (connection.getResponseCode() == 200) { DataInputStream dis = new DataInputStream(new BufferedInputStream(is)); StringWriter writer = new StringWriter(); IOUtils.copy(dis, writer, "UTF-8"); if (writer.toString().contains(token)) { cookie = connection.getHeaderField("Set-Cookie"); if (cookie == null) cookie = ""; } else { logger.info("URL " + url.getFile() + " returned code 200 but does not contain keyword '" + token + "'"); logger.debug("1000 first chars of response body: " + writer.toString().substring(0, 1000)); } } else { logger.error("URL " + url.getFile() + " returned code " + connection.getResponseCode() + " : " + connection.getResponseMessage()); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } } catch (IOException e) { logger.error("URL test failed: " + url.getFile() + " => " + e.getMessage() + " (" + e.getClass().getName() + ")"); if (System.getProperty("http.proxyHost") != null) { logger.info("Using proxy=" + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); } } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { // just going to ignore this one } } return cookie; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java
/** * Returns an <code>HttpURLConnection</code> fully ready to attempt * connection. This means it sets the request method (GET or POST), headers, * cookies, and authorization for the URL request. * <p>/*from w w w . j av a2 s . com*/ * The request infos are saved into the sample result if one is provided. * * @param u * <code>URL</code> of the URL request * @param method * GET, POST etc * @param res * sample result to save request infos to * @return <code>HttpURLConnection</code> ready for .connect * @exception IOException * if an I/O Exception occurs */ protected HttpURLConnection setupConnection(URL u, String method, HTTPSampleResult res) throws IOException { SSLManager sslmgr = null; if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { sslmgr = SSLManager.getInstance(); // N.B. this needs to be done before opening the connection } catch (Exception e) { log.warn("Problem creating the SSLManager: ", e); } } final HttpURLConnection conn; final String proxyHost = getProxyHost(); final int proxyPort = getProxyPortInt(); if (proxyHost.length() > 0 && proxyPort > 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); //TODO - how to define proxy authentication for a single connection? // It's not clear if this is possible // String user = getProxyUser(); // if (user.length() > 0){ // Authenticator auth = new ProxyAuthenticator(user, getProxyPass()); // } conn = (HttpURLConnection) u.openConnection(proxy); } else { conn = (HttpURLConnection) u.openConnection(); } // Update follow redirects setting just for this connection conn.setInstanceFollowRedirects(getAutoRedirects()); int cto = getConnectTimeout(); if (cto > 0) { conn.setConnectTimeout(cto); } int rto = getResponseTimeout(); if (rto > 0) { conn.setReadTimeout(rto); } if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { if (null != sslmgr) { sslmgr.setContext(conn); // N.B. must be done after opening connection } } catch (Exception e) { log.warn("Problem setting the SSLManager for the connection: ", e); } } // a well-behaved browser is supposed to send 'Connection: close' // with the last request to an HTTP server. Instead, most browsers // leave it to the server to close the connection after their // timeout period. Leave it to the JMeter user to decide. if (getUseKeepAlive()) { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE); } else { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE); } conn.setRequestMethod(method); setConnectionHeaders(conn, u, getHeaderManager(), getCacheManager()); String cookies = setConnectionCookie(conn, u, getCookieManager()); setConnectionAuthorization(conn, u, getAuthManager()); if (method.equals(HTTPConstants.POST)) { setPostHeaders(conn); } else if (method.equals(HTTPConstants.PUT)) { setPutHeaders(conn); } if (res != null) { res.setRequestHeaders(getConnectionHeaders(conn)); res.setCookies(cookies); } return conn; }
From source file:info.guardianproject.net.http.ModSSLSocketFactory.java
/** * Gets an singleton instance of the SSLProtocolSocketFactory. * @return a SSLProtocolSocketFactory//from w w w .java 2 s.c om */ public static ModSSLSocketFactory getSocketFactory(Proxy.Type proxyType, String proxyHost, int proxyPort) { if (DEFAULT_FACTORY == null) { DEFAULT_FACTORY = new ModSSLSocketFactory(); } proxyAddr = new InetSocketAddress(proxyHost, proxyPort); proxy = new Proxy(proxyType, proxyAddr); return DEFAULT_FACTORY; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImplClassifier.java
/** * Returns an <code>HttpURLConnection</code> fully ready to attempt * connection. This means it sets the request method (GET or POST), headers, * cookies, and authorization for the URL request. * <p>/*from w w w. ja v a2 s .c om*/ * The request infos are saved into the sample result if one is provided. * * @param u * <code>URL</code> of the URL request * @param method * GET, POST etc * @param res * sample result to save request infos to * @return <code>HttpURLConnection</code> ready for .connect * @exception IOException * if an I/O Exception occurs */ protected HttpURLConnection setupConnection(URL u, String method, HTTPSampleResult res) throws IOException { SSLManager sslmgr = null; if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { sslmgr = SSLManager.getInstance(); // N.B. this needs to be done // before opening the // connection } catch (Exception e) { log.warn("Problem creating the SSLManager: ", e); } } final HttpURLConnection conn; final String proxyHost = getProxyHost(); final int proxyPort = getProxyPortInt(); if (proxyHost.length() > 0 && proxyPort > 0) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); // TODO - how to define proxy authentication for a single // connection? // It's not clear if this is possible // String user = getProxyUser(); // if (user.length() > 0){ // Authenticator auth = new ProxyAuthenticator(user, // getProxyPass()); // } conn = (HttpURLConnection) u.openConnection(proxy); } else { conn = (HttpURLConnection) u.openConnection(); } // Update follow redirects setting just for this connection conn.setInstanceFollowRedirects(getAutoRedirects()); int cto = getConnectTimeout(); if (cto > 0) { conn.setConnectTimeout(cto); } int rto = getResponseTimeout(); if (rto > 0) { conn.setReadTimeout(rto); } if (HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) { try { if (null != sslmgr) { sslmgr.setContext(conn); // N.B. must be done after opening // connection } } catch (Exception e) { log.warn("Problem setting the SSLManager for the connection: ", e); } } // a well-bahaved browser is supposed to send 'Connection: close' // with the last request to an HTTP server. Instead, most browsers // leave it to the server to close the connection after their // timeout period. Leave it to the JMeter user to decide. if (getUseKeepAlive()) { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE); } else { conn.setRequestProperty(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE); } conn.setRequestMethod(method); setConnectionHeaders(conn, u, getHeaderManager(), getCacheManager()); String cookies = setConnectionCookie(conn, u, getCookieManager()); setConnectionAuthorization(conn, u, getAuthManager()); if (method.equals(HTTPConstants.POST)) { setPostHeaders(conn); } else if (method.equals(HTTPConstants.PUT)) { setPutHeaders(conn); } if (res != null) { res.setRequestHeaders(getConnectionHeaders(conn)); res.setCookies(cookies); } return conn; }
From source file:com.googlecode.jmxtrans.model.output.LibratoWriter.java
@JsonCreator public LibratoWriter(@JsonProperty("typeNames") ImmutableList<String> typeNames, @JsonProperty("booleanAsNumber") boolean booleanAsNumber, @JsonProperty("debug") Boolean debugEnabled, @JsonProperty("url") URL url, @JsonProperty("libratoApiTimeoutInMillis") Integer libratoApiTimeoutInMillis, @JsonProperty("username") String username, @JsonProperty("token") String token, @JsonProperty("proxyHost") String proxyHost, @JsonProperty("proxyPort") Integer proxyPort, @JsonProperty("settings") Map<String, Object> settings) throws MalformedURLException { super(typeNames, booleanAsNumber, debugEnabled, settings); logger.warn("LibratoWriter is deprecated. Please use LibratoWriterFactory instead."); this.url = MoreObjects.firstNonNull(url, new URL( MoreObjects.firstNonNull((String) this.getSettings().get(SETTING_URL), DEFAULT_LIBRATO_API_URL))); this.libratoApiTimeoutInMillis = MoreObjects.firstNonNull(libratoApiTimeoutInMillis, Settings.getIntSetting(getSettings(), SETTING_LIBRATO_API_TIMEOUT_IN_MILLIS, 1000)); this.username = MoreObjects.firstNonNull(username, (String) getSettings().get(SETTING_USERNAME)); this.token = MoreObjects.firstNonNull(token, (String) getSettings().get(SETTING_TOKEN)); this.basicAuthentication = Base64Variants.getDefaultVariant() .encode((this.username + ":" + this.token).getBytes(Charsets.US_ASCII)); this.proxyHost = proxyHost != null ? proxyHost : (String) getSettings().get(SETTING_PROXY_HOST); this.proxyPort = proxyPort != null ? proxyPort : Settings.getIntegerSetting(getSettings(), SETTING_PROXY_PORT, null); if (this.proxyHost != null && this.proxyPort != null) { this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort)); } else {//from w w w. j a va 2 s .c om this.proxy = null; } this.httpUserAgent = "jmxtrans-standalone/1 " + "(" + System.getProperty("java.vm.name") + "/" + System.getProperty("java.version") + "; " + System.getProperty("os.name") + "-" + System.getProperty("os.arch") + "/" + System.getProperty("os.version") + ")"; }
From source file:net.fenyo.gnetwatch.actions.ActionHTTP.java
/** * Loads the server./* ww w . ja v a 2 s . c o m*/ * @param none. * @return void. * @throws IOException IO exception. * @throws InterruptedException exception. * @see http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html */ // Queue thread // supports any thread public void invoke() throws IOException, InterruptedException { if (isDisposed() == true) return; try { super.invoke(); IPQuerier querier; synchronized (getGUI().getSynchro()) { if (TargetIPv4.class.isInstance(getTarget())) { querier = (IPQuerier) ((TargetIPv4) getTarget()).getIPQuerier().clone(); } else if (TargetIPv6.class.isInstance(getTarget())) { querier = (IPQuerier) ((TargetIPv6) getTarget()).getIPQuerier().clone(); } else return; } final URL url = new URL(querier.getURL()); final Proxy proxy = querier.getUseProxy() ? new Proxy(Proxy.Type.HTTP, new InetSocketAddress(querier.getProxyHost(), querier.getProxyPort())) : null; URLConnection[] connections = new URLConnection[querier.getNParallel()]; InputStream[] streams = new InputStream[querier.getNParallel()]; int[] sizes = new int[querier.getNParallel()]; for (int idx = 0; idx < querier.getNParallel(); idx++) connect(idx, querier, connections, streams, sizes, url, proxy); final byte[] buf = new byte[65536]; long last_time = System.currentTimeMillis(); int bytes_received = 0; int pages_received = 0; while (true) { int available_for_every_connections = 0; for (int idx = 0; idx < querier.getNParallel(); idx++) { final int available = (streams[idx] != null) ? streams[idx].available() : 0; available_for_every_connections += available; if (available == 0) { if (sizes[idx] == 0) { if (streams[idx] != null) streams[idx].close(); bytes_received += connect(idx, querier, connections, streams, sizes, url, proxy); pages_received++; } } else { final int nread = streams[idx].read(buf); switch (nread) { case -1: streams[idx].close(); connect(idx, querier, connections, streams, sizes, url, proxy); pages_received++; break; case 0: log.error("0 byte read"); for (InputStream foo : streams) if (foo != null) foo.close(); return; default: // log.debug("read: " + new String(buf).substring(0, nread - 1)); bytes_received += nread; sizes[idx] -= nread; } } if (System.currentTimeMillis() - last_time > 1000) { synchronized (getGUI().getSynchro()) { synchronized (getGUI().sync_tree) { final Session session = getGUI().getSynchro().getSessionFactory() .getCurrentSession(); session.beginTransaction(); try { session.update(this); getTarget() .addEvent(new EventHTTP(new Double(((double) 8 * 1000 * bytes_received) / (System.currentTimeMillis() - last_time)).intValue())); getTarget() .addEvent(new EventHTTPPages(new Double(((double) 1000 * pages_received) / (System.currentTimeMillis() - last_time)).intValue())); setDescription(GenericTools.formatNumericString(getGUI().getConfig(), "" + new Double(((double) 8 * 1000 * bytes_received) / (System.currentTimeMillis() - last_time)).intValue()) + " bit/s (" + GenericTools.formatNumericString(getGUI().getConfig(), "" + new Double(((double) 1000 * pages_received) / (System.currentTimeMillis() - last_time)).intValue()) + " pages/sec)"); getGUI().setStatus(getGUI().getConfig().getPattern("bytes_http", bytes_received, querier.getAddress().toString().substring(1)) + " " + error_string); last_time = System.currentTimeMillis(); bytes_received = 0; pages_received = 0; session.getTransaction().commit(); } catch (final Exception ex) { log.error("Exception", ex); session.getTransaction().rollback(); } } } } if (interrupted == true) { for (InputStream foo : streams) if (foo != null) foo.close(); return; } } if (available_for_every_connections == 0) Thread.sleep(10); } } catch (final InterruptedException ex) { log.error("Exception", ex); } }
From source file:com.varaneckas.hawkscope.Version.java
/** * Asynchroniously checks if a newer version of Hawkscope is available * /* w ww .j ava2 s .com*/ * @return */ public static void checkForUpdate() { if (!cfg.checkForUpdates()) { return; } try { log.debug("Checking for updates..."); URLConnection conn = null; final URL versionCheckUrl = new URL(VERSION_CHECK_URL); Proxy proxy = null; if (cfg.isHttpProxyInUse()) { proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort())); conn = versionCheckUrl.openConnection(proxy); } else { conn = versionCheckUrl.openConnection(); } conn.setConnectTimeout(Constants.CONNECTION_TIMOUT); conn.setReadTimeout(Constants.CONNECTION_TIMOUT); final InputStream io = conn.getInputStream(); int c = 0; final StringBuilder version = new StringBuilder(); while ((c = io.read()) != -1) { version.append((char) c); } if (log.isDebugEnabled()) { log.debug("Check complete. Latest " + OSUtils.CURRENT_OS + " version: " + version.toString()); } if (VERSION_NUMBER.compareTo(version.toString()) < 0) { log.info("Newer " + OSUtils.CURRENT_OS + " version available (" + version.toString() + "). You should update Hawkscope!"); isUpdateAvailable = true; updateVersion = version.toString(); } else { log.info("You have the latest available version of Hawkscope: " + VERSION_NUMBER); isUpdateAvailable = false; } PluginManager.getInstance().checkPluginUpdates(PLUGIN_VERSION_CHECK_URL, proxy); } catch (final Exception e) { log.info("Failed checking for update: " + e.getMessage()); } }
From source file:com.varaneckas.hawkscope.plugins.twitter.TwitterClient.java
/** * Gets an 24x24 image for User//from ww w. j a va 2s . c o m * * @param user * @return */ public Image getUserImage(final User user) { if (user == null) { return getTwitterIcon(); } if (!userImages.containsKey(user.getName())) { final Configuration cfg = ConfigurationFactory.getConfigurationFactory().getConfiguration(); Image i = null; try { if (!cfg.isHttpProxyInUse()) { i = new Image(Display.getCurrent(), user.getProfileImageURL().openStream()); } else { Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort())); URLConnection con = user.getProfileImageURL().openConnection(p); con.setReadTimeout(3000); i = new Image(Display.getCurrent(), con.getInputStream()); } i = new Image(Display.getCurrent(), i.getImageData().scaledTo(24, 24)); userImages.put(user.getName(), i); } catch (final IOException e) { log.warn("Failed getting user icon: " + user.getName(), e); return getTwitterIcon(); } } return userImages.get(user.getName()); }
From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java
private HttpURLConnection createConnection(final String location) throws IOException { URL url = new URL(location); HttpURLConnection conn;// w w w. j ava2 s . c o m if (proxyHost != null && proxyPort != null) { if (proxyUser != null && proxyPassword != null) { Authenticator authenticator = new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }; Authenticator.setDefault(authenticator); } Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } return conn; }