List of usage examples for java.net Proxy Proxy
public Proxy(Type type, SocketAddress sa)
From source file:org.apache.nifi.processors.standard.util.FTPTransfer.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 ww w. jav a2 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).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.clickha.nifi.processors.util.FTPTransferV2.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();//ww w . j a v a 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(); } // additional FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX); final String ftpClientConfig = ctx.getProperty(FTP_CLIENT_CONFIG_SYST).getValue(); if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_UNIX)) { this.ftpConfig = ftpConfig; client.configure(ftpConfig); } else if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_NT)) { this.ftpConfig = ftpConfig; client.configure(ftpConfig); } final String transferMode = ctx.getProperty(TRANSFER_MODE).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:org.broad.igv.util.HttpUtils.java
/** * The "real" connection method//from w w w.j a v a 2 s.c o m * * @param url * @param requestProperties * @param method * @return * @throws java.io.IOException */ private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { //Encode query string portions url = StringUtils.encodeURLQueryString(url); if (log.isTraceEnabled()) { log.trace(url); } //Encode base portions. Right now just spaces, most common case //TODO This is a hack and doesn't work for all characters which need it if (StringUtils.countChar(url.toExternalForm(), ' ') > 0) { String newPath = url.toExternalForm().replaceAll(" ", "%20"); url = new URL(newPath); } Proxy sysProxy = null; boolean igvProxySettingsExist = proxySettings != null && proxySettings.useProxy; //Only check for system proxy if igv proxy settings not found if (!igvProxySettingsExist) { sysProxy = getSystemProxy(url.toExternalForm()); } boolean useProxy = sysProxy != null || igvProxySettingsExist; HttpURLConnection conn; if (useProxy) { Proxy proxy = sysProxy; if (igvProxySettingsExist) { if (proxySettings.type == Proxy.Type.DIRECT) { proxy = Proxy.NO_PROXY; } else { proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); } } conn = (HttpURLConnection) url.openConnection(proxy); if (igvProxySettingsExist && proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes)); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { conn.setRequestProperty("Accept", "application/json,text/plain"); } else { conn.setRequestProperty("Accept", "text/plain"); } //------// //There seems to be a bug with JWS caches //So we avoid caching //This default is persistent, really should be available statically but isn't conn.setDefaultUseCaches(false); conn.setUseCaches(false); //------// conn.setConnectTimeout(Globals.CONNECT_TIMEOUT); conn.setReadTimeout(Globals.READ_TIMEOUT); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "Keep-Alive"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } conn.setRequestProperty("User-Agent", Globals.applicationString()); if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); if (log.isDebugEnabled()) { //logHeaders(conn); } // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code >= 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); log.debug("Redirecting to " + newLocation); return openConnection(new URL(newLocation), requestProperties, method, redirectCount++); } // TODO -- handle other response codes. else if (code >= 400) { String message; if (code == 404) { message = "File not found: " + url.toString(); throw new FileNotFoundException(message); } else if (code == 401) { // Looks like this only happens when user hits "Cancel". // message = "Not authorized to view this file"; // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE); redirectCount = MAX_REDIRECTS + 1; return null; } else { message = conn.getResponseMessage(); } String details = readErrorStream(conn); log.error("URL: " + url.toExternalForm() + ". error stream: " + details); log.error("Code: " + code + ". " + message); HttpResponseException exc = new HttpResponseException(code); throw exc; } } return conn; }
From source file:org.apache.nifi.processors.standard.InvokeHTTP.java
@OnScheduled public void setUpClient(final ProcessContext context) throws IOException { okHttpClientAtomicReference.set(null); OkHttpClient okHttpClient = new OkHttpClient(); // Add a proxy if set final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue(); final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger(); if (proxyHost != null && proxyPort != null) { final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); okHttpClient.setProxy(proxy);//www .j a v a 2s.c om } // Set timeouts okHttpClient.setConnectTimeout( (context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()), TimeUnit.MILLISECONDS); okHttpClient.setReadTimeout( context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(), TimeUnit.MILLISECONDS); // Set whether to follow redirects okHttpClient.setFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean()); final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE); // check if the ssl context is set and add the factory if so if (sslContext != null) { okHttpClient.setSslSocketFactory(sslContext.getSocketFactory()); } // check the trusted hostname property and override the HostnameVerifier String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue()); if (!trustedHostname.isEmpty()) { okHttpClient.setHostnameVerifier( new OverrideHostnameVerifier(trustedHostname, okHttpClient.getHostnameVerifier())); } setAuthenticator(okHttpClient, context); useChunked = context.getProperty(PROP_USE_CHUNKED_ENCODING).asBoolean(); okHttpClientAtomicReference.set(okHttpClient); }
From source file:ca.mymenuapp.ui.debug.DebugAppContainer.java
private void showNewNetworkProxyDialog(final ProxyAdapter proxyAdapter) { final int originalSelection = networkProxy.isSet() ? ProxyAdapter.PROXY : ProxyAdapter.NONE; View view = LayoutInflater.from(app).inflate(R.layout.debug_drawer_network_proxy, null); final EditText host = findById(view, R.id.debug_drawer_network_proxy_host); new AlertDialog.Builder(activity) // .setTitle("Set Network Proxy").setView(view) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override/*from www . j a v a2 s .c o m*/ public void onClick(DialogInterface dialog, int i) { networkProxyView.setSelection(originalSelection); dialog.cancel(); } }).setPositiveButton("Use", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { String theHost = host.getText().toString(); if (!Strings.isBlank(theHost)) { String[] parts = theHost.split(":", 2); SocketAddress address = InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])); networkProxy.set(theHost); // Persist across restarts. proxyAdapter.notifyDataSetChanged(); // Tell the spinner to update. networkProxyView.setSelection(ProxyAdapter.PROXY); // And show the proxy. client.setProxy(new Proxy(HTTP, address)); } else { networkProxyView.setSelection(originalSelection); } } }).setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { networkProxyView.setSelection(originalSelection); } }).show(); }
From source file:org.eclipse.mylyn.commons.net.WebUtil.java
/** * @since 3.1/*from w ww . ja v a 2 s. com*/ */ public static Proxy createProxy(String proxyHost, int proxyPort, AuthenticationCredentials credentials) { String proxyUsername = ""; //$NON-NLS-1$ String proxyPassword = ""; //$NON-NLS-1$ if (credentials != null) { proxyUsername = credentials.getUserName(); proxyPassword = credentials.getPassword(); } if (proxyHost != null && proxyHost.length() > 0) { InetSocketAddress sockAddr = new InetSocketAddress(proxyHost, proxyPort); boolean authenticated = (proxyUsername != null && proxyPassword != null && proxyUsername.length() > 0 && proxyPassword.length() > 0); if (authenticated) { return new AuthenticatedProxy(Type.HTTP, sockAddr, proxyUsername, proxyPassword); } else { return new Proxy(Type.HTTP, sockAddr); } } return Proxy.NO_PROXY; }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * CRL- ? , ? ? , ? ?/* ww w . java 2 s . c o m*/ * ? * * @param crlName */ private void loadCrlObject(String crlName) { TypeOfCrlLoaded oldState = MAP_OF_LOAD_CRL_LABEL.get(crlName); if (TypeOfCrlLoaded.LOADING.equals(oldState)) { return; } MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADING); String location = MAP_OF_CRL_PATH.get(crlName); try { URL url = new URL(location); HttpURLConnection conn = null; if (useProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setUseCaches(false); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() == 200) { CertificateFactory cf = CertificateFactory.getInstance("X.509", "KALKAN"); X509CRL crlObject = (X509CRL) cf.generateCRL(conn.getInputStream()); MAP_OF_XCRL.put(crlName, crlObject); } else { String msg = "(1) ? CRL- : '" + location + "' : " + conn.getResponseCode() + " , " + conn.getResponseMessage(); log.warning(msg); } } catch (Exception e) { String msg = "(1) ? CRL- : '" + location + "' : " + e.getMessage(); log.warning(msg); } //MAP_OF_LOAD_CRL_LABEL.put(crlName, oldState ) ; MAP_OF_LOAD_CRL_TIME.put(crlName, new Date()); MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADED); }
From source file:net.sf.jsignpdf.BasicSignerOptions.java
/** * Creates and returns Proxy object, which should be used for URL * connections in JSignPdf.//from w w w .ja v a 2 s . c o m * * @return initialized Proxy object. */ public Proxy createProxy() { Proxy tmpResult = Proxy.NO_PROXY; if (isAdvanced() && getProxyType() != Proxy.Type.DIRECT) { tmpResult = new Proxy(getProxyType(), new InetSocketAddress(getProxyHost(), getProxyPort())); } return tmpResult; }
From source file:com.opentok.test.OpenTokTest.java
@Test public void testCreateSessionWithProxy() throws OpenTokException, UnknownHostException { WireMockConfiguration proxyConfig = WireMockConfiguration.wireMockConfig(); proxyConfig.dynamicPort();//w w w .ja va2 s . co m WireMockServer proxyingService = new WireMockServer(proxyConfig); proxyingService.start(); WireMock proxyingServiceAdmin = new WireMock(proxyingService.port()); String targetServiceBaseUrl = "http://localhost:" + wireMockRule.port(); proxyingServiceAdmin.register( any(urlMatching(".*")).atPriority(10).willReturn(aResponse().proxiedFrom(targetServiceBaseUrl))); String sessionId = "SESSIONID"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getLocalHost(), proxyingService.port())); sdk = new OpenTok(apiKey, apiSecret, apiUrl, proxy); stubFor(post(urlEqualTo("/session/create")).willReturn(aResponse().withStatus(200) .withHeader("Content-Type", "text/xml") .withBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><sessions><Session><" + "session_id>" + sessionId + "</session_id><partner_id>123456</partner_id><create_dt>" + "Mon Mar 17 00:41:31 PDT 2014</create_dt></Session></sessions>"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(this.apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); verify(postRequestedFor(urlMatching("/session/create"))); Helpers.verifyPartnerAuth(this.apiKey, this.apiSecret); Helpers.verifyUserAgent(); }
From source file:fur.shadowdrake.minecraft.InstallPanel.java
public boolean downloadMojangLauncher() { URL u;/* w ww. j a va 2s .c o m*/ HttpURLConnection connection; Proxy p; InputStream is; FileOutputStream fos; if (new File(config.getInstallDir(), "Minecraft.jar").isFile()) { return true; } log.println("Connecting to Mojang server..."); if (config.getHttpProxy().isEmpty()) { p = Proxy.NO_PROXY; } else { Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == Authenticator.RequestorType.PROXY) { return config.getHttpProxyCredentials(); } else { return super.getPasswordAuthentication(); } } }); p = new Proxy(Proxy.Type.HTTP, new ProxyAddress(config.getHttpProxy(), 3128).getSockaddr()); } try { u = new URL("https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar"); connection = (HttpURLConnection) u.openConnection(p); connection.addRequestProperty("User-agent", "Minecraft Bootloader"); connection.setUseCaches(false); connection.setDefaultUseCaches(false); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.connect(); log.println("Mojang server returned " + connection.getResponseMessage()); if (connection.getResponseCode() != 200) { connection.disconnect(); return false; } } catch (MalformedURLException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex); log.println("Connection to Mojang server failed."); return false; } try { is = connection.getInputStream(); fos = new FileOutputStream(new File(config.getInstallDir(), "Minecraft.jar")); log.println("Downloading Minecraft.jar"); byte[] buffer = new byte[4096]; for (int n = is.read(buffer); n > 0; n = is.read(buffer)) { fos.write(buffer, 0, n); } fos.close(); is.close(); connection.disconnect(); log.println("Done."); } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "downloadMojangLauncher", ex); log.println("Faild to save file."); return false; } return true; }