List of usage examples for java.net Proxy Proxy
public Proxy(Type type, SocketAddress sa)
From source file:fr.ibp.nifi.processors.IBPFTPTransfer.java
private FTPClient getClient(final FlowFile flowFile) throws IOException { if (client != null) { String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue(); if (remoteHostName.equals(desthost)) { // destination matches so we can keep our current session resetWorkingDirectory();/*from w w w . j a va 2 s . c o m*/ return client; } else { // this flowFile is going to a different destination, reset // session close(); } } final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue()); final String proxyHost = ctx.getProperty(PROXY_HOST).getValue(); final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger(); FTPClient client; if (proxyType == Proxy.Type.HTTP) { client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(), ctx.getProperty(HTTP_PROXY_PASSWORD).getValue()); } else { client = new FTPClient(); if (proxyType == Proxy.Type.SOCKS) { client.setSocketFactory(new SocksProxySocketFactory( new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort)))); } } this.client = client; client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); client.setDefaultTimeout( ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); client.setRemoteVerificationEnabled(false); final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue(); this.remoteHostName = remoteHostname; InetAddress inetAddress = null; try { inetAddress = InetAddress.getByAddress(remoteHostname, null); } catch (final UnknownHostException uhe) { } if (inetAddress == null) { inetAddress = InetAddress.getByName(remoteHostname); } client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger()); this.closed = false; client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()); final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue(); final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue(); final boolean loggedIn = client.login(username, password); if (!loggedIn) { throw new IOException("Could not login for user '" + username + "'"); } final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue(); if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) { client.enterLocalActiveMode(); } else { client.enterLocalPassiveMode(); } final String transferMode = ctx.getProperty(TRANSFER_MODE).evaluateAttributeExpressions(flowFile) .getValue(); final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE : FTPClient.BINARY_FILE_TYPE; if (!client.setFileType(fileType)) { throw new IOException("Unable to set transfer mode to type " + transferMode); } this.homeDirectory = client.printWorkingDirectory(); return client; }
From source file:com.minoritycode.Application.java
private static boolean setProxy() { System.out.println("Setting proxy..."); String host = null;// ww w. j av a 2s. c o m host = config.getProperty("proxyHost").trim(); if (host == null || host.isEmpty() || host.equals("")) { logger.logLine("error proxy host not set in config file"); if (manualOperation) { String message = "Please enter your proxy Host address"; host = Credentials.getInput(message).trim(); Credentials.saveProperty("proxyHost", host); if (host.equals(null)) { System.exit(0); } } else { return false; } } String port = config.getProperty("proxyPort").trim(); if (port == null || port.isEmpty()) { logger.logLine("error proxy port not set in config file"); if (manualOperation) { String message = "Please enter your proxy port"; port = Credentials.getInput(message).trim(); Credentials.saveProperty("proxyPort", port); if (port.equals(null)) { System.exit(0); } } else { return false; } } String user = config.getProperty("proxyUser").trim(); if (user == null || user.isEmpty()) { logger.logLine("error proxy username not set in config file"); if (manualOperation) { String message = "Please enter your proxy username"; user = Credentials.getInput(message).trim(); if (user.equals(null)) { System.exit(0); } Credentials.saveProperty("proxyUser", user); } else { return false; } } String password = config.getProperty("proxyPassword").trim(); if (password == null || password.isEmpty()) { logger.logLine("error proxy password not set in config file"); if (manualOperation) { String message = "Please enter your proxy password"; password = Credentials.getInput(message).trim(); Credentials.saveProperty("proxyPassword", password); if (password.equals(null)) { System.exit(0); } } else { return false; } } Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { String prot = getRequestingProtocol().toLowerCase(); String host = System.getProperty(prot + ".proxyHost", config.getProperty("proxyHost")); String port = System.getProperty(prot + ".proxyPort", config.getProperty("proxyPort")); String user = System.getProperty(prot + ".proxyUser", config.getProperty("proxyUser")); String password = System.getProperty(prot + ".proxyPassword", config.getProperty("proxyPassword")); if (getRequestingHost().equalsIgnoreCase(host)) { if (Integer.parseInt(port) == getRequestingPort()) { // Seems to be OK. return new PasswordAuthentication(user, password.toCharArray()); } } } return null; } }); System.setProperty("http.proxyPort", port); System.setProperty("http.proxyHost", host); System.setProperty("http.proxyUser", user); System.setProperty("http.proxyPassword", password); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, Integer.parseInt(port))); // System.out.println(host+":"+port +" "+ user+":"+password); System.out.println("Proxy set"); return true; }
From source file:com.example.android.hawifi.MainActivity.java
/** * Given a string representation of a URL, sets up a connection and gets * an input stream./*www .j a va 2s . co m*/ * @param urlString A string representation of a URL. * @return An InputStream retrieved from a successful HttpURLConnection. * @throws java.io.IOException */ private InputStream downloadUrl(String urlString) throws IOException { // BEGIN_INCLUDE(get_inputstream) URL url = new URL(urlString); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.144.1.10", 8080)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); //HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); //conn.usingProxy(); //conn.setAllowUserInteraction(false); // Start the query conn.connect(); InputStream stream = conn.getInputStream(); return stream; // END_INCLUDE(get_inputstream) }
From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java
private void addProxySelector() { // Add authenticator with proxyUser and proxyPassword if (proxyUser != null && proxyPassword != null) { Authenticator.setDefault(new Authenticator() { @Override//from w ww . j a v a 2 s . co m public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); } final ProxySelector defaultProxySelector = ProxySelector.getDefault(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(final URI uri) { if (uri.getHost().equals("fastdl.mongodb.org")) { return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort))); } else { return defaultProxySelector.select(uri); } } @Override public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) { } }); }
From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java
public void testLocationSslConnectProxy() throws Exception { String url = "https://foo/bar"; final Proxy proxy = new Proxy(Type.HTTP, proxyAddress); AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() { public Proxy getProxyForHost(String host, String proxyType) { return proxy; }/* w w w.j a va 2 s . c o m*/ }); HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null); ; testProxy.addResponse(TestProxy.SERVICE_UNVAILABLE); GetMethod method = new GetMethod("/"); int statusCode = client.executeMethod(hostConfiguration, method); assertEquals(503, statusCode); Message request = testProxy.getRequest(); assertEquals("CONNECT foo:443 HTTP/1.1", request.request); }
From source file:org.eclipsetrader.directa.internal.core.connector.StreamingConnector.java
@Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void run() { int n = 0;//from w w w . j a v a 2 s.c o m byte bHeader[] = new byte[4]; sTit = new HashSet<String>(); sTit2 = new HashSet<String>(); // Apertura del socket verso il server try { Proxy socksProxy = Proxy.NO_PROXY; if (Activator.getDefault() != null) { BundleContext context = Activator.getDefault().getBundle().getBundleContext(); ServiceReference reference = context.getServiceReference(IProxyService.class.getName()); if (reference != null) { IProxyService proxyService = (IProxyService) context.getService(reference); IProxyData[] proxyData = proxyService.select(new URI(null, streamingServer, null, null)); for (int i = 0; i < proxyData.length; i++) { if (IProxyData.SOCKS_PROXY_TYPE.equals(proxyData[i].getType()) && proxyData[i].getHost() != null) { socksProxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyData[i].getHost(), proxyData[i].getPort())); break; } } context.ungetService(reference); } } socket = new Socket(socksProxy); socket.connect(new InetSocketAddress(streamingServer, streamingPort)); os = socket.getOutputStream(); is = new DataInputStream(socket.getInputStream()); } catch (Exception e) { Activator.log( new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to streaming server", e)); //$NON-NLS-1$ try { if (socket != null) { socket.close(); socket = null; } } catch (Exception e1) { // Do nothing } return; } // Login try { os.write(CreaMsg.creaLoginMsg(WebConnector.getInstance().getUrt(), WebConnector.getInstance().getPrt(), "flashBook", streamingVersion)); //$NON-NLS-1$ os.flush(); byte bHeaderLogin[] = new byte[4]; n = is.read(bHeaderLogin); int lenMsg = Util.getMessageLength(bHeaderLogin, 2); if ((char) bHeaderLogin[0] != '#' && n != -1) { return; } byte msgResp[] = new byte[lenMsg]; is.read(msgResp); if (Util.byteToInt(bHeaderLogin[1]) == CreaMsg.ERROR_MSG) { ErrorMessage eMsg = new ErrorMessage(msgResp); Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to streaming server: " + eMsg.sMessageError, null)); //$NON-NLS-1$ return; } try { os.write(CreaMsg.creaStartDataMsg()); os.flush(); } catch (Exception e) { thread = null; Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error starting data stream", e)); //$NON-NLS-1$ return; } } catch (Exception e) { Activator.log( new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to streaming server", e)); //$NON-NLS-1$ return; } // Forces the subscriptions update on startup subscriptionsChanged = true; while (!isStopping()) { if (subscriptionsChanged) { try { updateStreamSubscriptions(); } catch (Exception e) { thread = null; Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error updating stream subscriptions", e)); //$NON-NLS-1$ break; } } // Legge l'header di un messaggio (se c'e') try { if ((n = is.read(bHeader)) == -1) { continue; } while (n < 4) { int r = is.read(bHeader, n, 4 - n); n += r; } } catch (Exception e) { Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error reading data", e)); //$NON-NLS-1$ break; } // Verifica la correttezza dell'header e legge il resto del messaggio Header h = new Header(); h.start = (char) Util.byteToInt(bHeader[0]); if (h.start == '#') { h.tipo = Util.getByte(bHeader[1]); h.len = Util.getMessageLength(bHeader, 2); byte mes[] = new byte[h.len]; try { n = is.read(mes); while (n < h.len) { int r = is.read(mes, n, h.len - n); n += r; } } catch (Exception e) { } if (h.tipo == CreaMsg.ERROR_MSG) { ErrorMessage eMsg = new ErrorMessage(mes); Activator.log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0, "Message from server: " + eMsg.sMessageError, null)); //$NON-NLS-1$ } else if (h.tipo == Message.TIP_ECHO) { try { os.write(new byte[] { bHeader[0], bHeader[1], bHeader[2], bHeader[3], mes[0], mes[1] }); os.flush(); } catch (Exception e) { // Do nothing } } else if (h.len > 0) { DataMessage obj; try { obj = Message.decodeMessage(mes); if (obj == null) { continue; } } catch (Exception e) { Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error decoding incoming message", e)); //$NON-NLS-1$ continue; } processMessage(obj); } } } try { os.write(CreaMsg.creaStopDataMsg()); os.flush(); } catch (Exception e) { Activator.log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0, "Error stopping data stream", e)); //$NON-NLS-1$ } try { os.write(CreaMsg.creaLogoutMsg()); os.flush(); } catch (Exception e) { Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error closing connection to streaming server", e)); //$NON-NLS-1$ } try { os.close(); is.close(); socket.close(); } catch (Exception e) { Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error closing connection to streaming server", e)); //$NON-NLS-1$ } os = null; is = null; socket = null; if (!isStopping()) { thread = new Thread(this, name + " - Data Reader"); //$NON-NLS-1$ try { Thread.sleep(2 * 1000); } catch (Exception e) { // Do nothing } thread.start(); } }
From source file:org.apache.synapse.config.SynapseConfigUtils.java
/** * Returns a URLCOnnection for given URL. If the URL is https one , then URLConnectin is a * HttpsURLCOnnection and it is configured with KeyStores given in the synapse.properties file * * @param url URL/* ww w . j a v a2 s . c o m*/ * @return URLConnection for given URL */ public static URLConnection getURLConnection(URL url) { try { if (url == null) { if (log.isDebugEnabled()) { log.debug("Provided URL is null"); } return null; } URLConnection connection; if (url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")) { Properties synapseProperties = SynapsePropertiesLoader.loadSynapseProperties(); String proxyHost = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_HOST); String proxyPort = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PORT); // get the list of excluded hosts for proxy List<String> excludedHosts = getExcludedHostsForProxy(synapseProperties); if (proxyHost != null && proxyPort != null && !excludedHosts.contains(proxyHost)) { SocketAddress sockaddr = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)); Proxy proxy = new Proxy(Proxy.Type.HTTP, sockaddr); if (url.getProtocol().equalsIgnoreCase("https")) { connection = getHttpsURLConnection(url, synapseProperties, proxy); } else { connection = url.openConnection(proxy); } } else { if (url.getProtocol().equalsIgnoreCase("https")) { connection = getHttpsURLConnection(url, synapseProperties, null); } else { connection = url.openConnection(); } } // try to see weather authentication is required String userName = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_USER); String password = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PASSWORD); if (userName != null && password != null) { String header = userName + ":" + password; byte[] encodedHeaderBytes = new Base64().encode(header.getBytes()); String encodedHeader = new String(encodedHeaderBytes); connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedHeader); } } else { connection = url.openConnection(); } connection.setReadTimeout(getReadTimeout()); connection.setConnectTimeout(getConnectTimeout()); connection.setRequestProperty("Connection", "close"); // if http is being used return connection; } catch (IOException e) { handleException("Error reading at URI ' " + url + " ' ", e); } return null; }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * * Sets the proxy host and port. This will be implicitly called if * "proxy.host" and "proxy.port" properties are given in properties file * * @param host/* www. jav a 2 s . co m*/ * proxy host * @param port * proxy port */ public static void setProxyConfig(final String host, final int port) { if (host != null) { int proxyPort = port; if (proxyPort < 0) { proxyPort = 0; } LOG.debug("Setting proxy - Host : " + host + " port : " + port); proxyObj = new Proxy(Type.HTTP, new InetSocketAddress(host, port)); } }
From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java
public void testLocationSslConnectProxyNoProxyCredentials() throws Exception { String url = "https://foo/bar"; final Proxy proxy = new Proxy(Type.HTTP, proxyAddress); AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() { public Proxy getProxyForHost(String host, String proxyType) { return proxy; }/*from w w w. ja v a2s .c om*/ }); HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null); ; Message response = new Message("HTTP/1.1 407 Proxy authentication required"); response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\""); testProxy.addResponse(response); testProxy.addResponse(TestProxy.SERVICE_UNVAILABLE); GetMethod method = new GetMethod("/"); int statusCode = client.executeMethod(hostConfiguration, method); assertEquals(407, statusCode); Message request = testProxy.getRequest(); assertEquals("CONNECT foo:443 HTTP/1.1", request.request); assertFalse("Expected HttpClient to close connection", testProxy.hasRequest()); }
From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java
public void testLocationSslConnectProxyTimeout() throws Exception { String url = "https://foo/bar"; final Proxy proxy = new Proxy(Type.HTTP, proxyAddress); AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() { public Proxy getProxyForHost(String host, String proxyType) { return proxy; }/*from ww w .j a v a2 s . c om*/ }); HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null); testProxy.addResponse(TestProxy.OK); GetMethod method = new GetMethod("/"); // avoid second attempt to connect to proxy to get exception right away method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() { public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { return false; } }); try { int statusCode = client.executeMethod(hostConfiguration, method); fail("Expected SSLHandshakeException, got status: " + statusCode); } catch (SSLHandshakeException e) { } catch (SocketException e) { // connection reset, happens in some environments instead of SSLHandshakeExecption depending on how much data has been written before the socket is closed } Message request = testProxy.getRequest(); assertEquals("CONNECT foo:443 HTTP/1.1", request.request); }