Java Code Examples for java.net.Proxy#Type

The following examples show how to use java.net.Proxy#Type . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProxyFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void normal() {
	Proxy.Type type = Proxy.Type.HTTP;
	factoryBean.setType(type);
	String hostname = "example.com";
	factoryBean.setHostname(hostname);
	int port = 8080;
	factoryBean.setPort(port);
	factoryBean.afterPropertiesSet();

	Proxy result = factoryBean.getObject();

	assertEquals(type, result.type());
	InetSocketAddress address = (InetSocketAddress) result.address();
	assertEquals(hostname, address.getHostName());
	assertEquals(port, address.getPort());
}
 
Example 2
Source File: SettingsReader.java    From jeveassets with GNU General Public License v2.0 6 votes vote down vote up
private void parseProxy(final Element proxyElement, final Settings settings) throws XmlException {
	Proxy.Type type;
	try {
		type = Proxy.Type.valueOf(getString(proxyElement, "type"));
	} catch (IllegalArgumentException  ex) {
		type = null;
	}
	String address = getString(proxyElement, "address");
	int port = getInt(proxyElement, "port");
	String username = null;
	if (haveAttribute(proxyElement, "username")) {
		username = getString(proxyElement, "username");
	}
	String password = null;
	if (haveAttribute(proxyElement, "password")) {
		password = getString(proxyElement, "password");
	}
	if (type != null && type != Proxy.Type.DIRECT && !address.isEmpty() && port != 0) { // check the proxy attributes are all there.
		settings.setProxyData(new ProxyData(address, type, port, username, password));
	}
}
 
Example 3
Source File: StandardProxyConfigurationService.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final Proxy.Type proxyType = Proxy.Type.valueOf(validationContext.getProperty(PROXY_TYPE).getValue());
    if (Proxy.Type.DIRECT.equals(proxyType)) {
        return Collections.emptyList();
    }

    final List<ValidationResult> results = new ArrayList<>();
    if (!validationContext.getProperty(PROXY_SERVER_HOST).isSet()) {
        results.add(new ValidationResult.Builder().subject(PROXY_SERVER_HOST.getDisplayName())
                .explanation("required").valid(false).build());
    }
    if (!validationContext.getProperty(PROXY_SERVER_PORT).isSet()) {
        results.add(new ValidationResult.Builder().subject(PROXY_SERVER_PORT.getDisplayName())
                .explanation("required").valid(false).build());
    }
    return results;
}
 
Example 4
Source File: ProxySettingsPanel.java    From jeveassets with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean save() {
	//Save proxy data
	if (jProxyType.getSelectedItem() != Proxy.Type.DIRECT) {
		String address = jProxyAddress.getText();
		int port = (int) jProxyPort.getValue();
		Proxy.Type type = (Proxy.Type) jProxyType.getSelectedItem();
		String username;
		String password;
		if (jEnableAuth.isSelected()) {
			username = jProxyUsername.getText();
			char[] passwordChars = jProxyPassword.getPassword();
			password = String.valueOf(passwordChars);
		} else {
			username = null;
			password = null;
		}
		Settings.get().setProxyData(new ProxyData(address, type, port, username, password));
	} else {
		Settings.get().setProxyData(new ProxyData());
	}
	return false;
}
 
Example 5
Source File: Client.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
public Client(final String serviceUrl, final Proxy.Type protocol, final String proxy, final int port)
    throws IOException, ODataException,
    HttpException {
  this.serviceUrl = serviceUrl;
  this.protocol = protocol;
  this.proxy = proxy;
  this.port = port;
  useProxy = true;
  useAuthentication = false;

  edm = getEdmInternal();
}
 
Example 6
Source File: ProxyWrapper.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the proxy's type.
 *
 * @return The proxy's type.
 */
public
Proxy.Type
getType()
{
  return itsProxyType;
}
 
Example 7
Source File: ProxyData.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
public ProxyData(String address, Proxy.Type type, int port, String username, String password) {
	this.address = address;
	this.type = type;
	this.port = port;
	this.username = username;
	this.password = password;
	updateProxy();
}
 
Example 8
Source File: RequestLine.java    From AndroidProjects with MIT License 5 votes vote down vote up
/**
 * Returns the request status line, like "GET / HTTP/1.1". This is exposed to the application by
 * {@link HttpURLConnection#getHeaderFields}, so it needs to be set even if the transport is
 * HTTP/2.
 */
public static String get(Request request, Proxy.Type proxyType) {
  StringBuilder result = new StringBuilder();
  result.append(request.method());
  result.append(' ');

  if (includeAuthorityInRequestLine(request, proxyType)) {
    result.append(request.url());
  } else {
    result.append(requestPath(request.url()));
  }

  result.append(" HTTP/1.1");
  return result.toString();
}
 
Example 9
Source File: GoogleProxy.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/** Creates an {@link GoogleProxy} instance based on proxy configuration. */
public static GoogleProxy fromConfiguration() {
  checkState(Configuration.isInitialized(), "configuration must be initialized");

  String userName = Configuration.getString(TRANSPORT_PROXY_USERNAME_KEY, "").get();
  String password = Configuration.getString(TRANSPORT_PROXY_PASSWORD_KEY, "").get();
  GoogleProxy.Builder builder = new GoogleProxy.Builder();
  if (!userName.isEmpty() && !password.isEmpty()) {
    builder.setUserNamePassword(userName, password);
  }

  Proxy.Type proxyType =
      Configuration.getValue(
          TRANSPORT_PROXY_TYPE_KEY,
          Proxy.Type.HTTP,
          value -> {
            try {
              return Proxy.Type.valueOf(value);
            } catch (IllegalArgumentException e) {
              throw new InvalidConfigurationException(e);
            }
          })
          .get();
  String hostname = Configuration.getString(TRANSPORT_PROXY_HOSTNAME_KEY, "").get();
  int port = Configuration.getInteger(TRANSPORT_PROXY_PORT_KEY, -1).get();

  if (!hostname.isEmpty()) {
    Configuration.checkConfiguration(port > 0, String.format("port %d is invalid", port));
  }

  Proxy proxy =
      hostname.isEmpty()
          ? Proxy.NO_PROXY
          : new Proxy(proxyType, new InetSocketAddress(hostname, port));

  return builder.setProxy(proxy).build();
}
 
Example 10
Source File: ProxyConfiguration.java    From bugsnag-java with MIT License 4 votes vote down vote up
public void setType(Proxy.Type type) {
    this.type = type;
}
 
Example 11
Source File: ProxyTypeResolver.java    From Hauk with Apache License 2.0 4 votes vote down vote up
private ProxyTypeResolver(int index, Proxy.Type mapping) {
    super(index, mapping);
}
 
Example 12
Source File: PacProxySelector.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private Proxy parsePacProxy(String pacProxy) {
	/*
	 * PAC formats:
	 *
	 * DIRECT Connections should be made directly, without any proxies.
	 *
	 * PROXY host:port The specified proxy should be used.
	 *
	 * SOCKS host:port The specified SOCKS server should be used.
	 *
	 * Where port is not supplied use port 80
	 */

	if (pacProxy.equals("DIRECT")) {
		return Proxy.NO_PROXY;
	}

	String[] split = pacProxy.split(" ", 0);

	if (split.length != 2) {
		return null;
	}

	String proxyTypeStr = split[0];
	String address = split[1];

	Proxy.Type proxyType = null;

	if (proxyTypeStr.equals("PROXY")) {
		proxyType = Proxy.Type.HTTP;
	} else if (proxyTypeStr.equals("SOCKS")) {
		proxyType = Proxy.Type.SOCKS;
	}

	if (proxyType == null) {
		return null;
	}

	split = address.split(":", 0);
	String host = null;
	int port = 80;

	if (split.length == 1) {
		host = split[0];
	} else if (split.length == 2) {
		host = split[0];

		try {
			port = Integer.parseInt(split[1]);
		} catch (NumberFormatException ex) {
			return null;
		}
	} else {
		return null;
	}

	return new Proxy(proxyType, new InetSocketAddress(host, port));
}
 
Example 13
Source File: WrapProxy.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public Proxy.Type type() {
    return getWrappedObject().type();
}
 
Example 14
Source File: RestServiceAdapter.java    From mdw with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an HttpConnection based on the configured endpoint, which
 * includes the resource path. Override for HTTPS or other connection type.
 */
public Object openConnection(String proxyHost, int proxyPort, Proxy.Type proxyType) throws ConnectionException {
    try {
        String endpointUri = getEndpointUri();
        if (endpointUri == null)
            throw new ConnectionException("Missing endpoint URI");
        Map<String,String> params = getRequestParameters();
        if (params != null && !params.isEmpty()) {
            StringBuffer query = new StringBuffer();
            query.append(endpointUri.indexOf('?') < 0 ? '?' : '&');
            int count = 0;
            for (String name : params.keySet()) {
                if (count > 0)
                    query.append('&');
                String encoding = getUrlEncoding();
                query.append(encoding == null ? name : URLEncoder.encode(name, encoding)).append("=");
                query.append(encoding == null ? params.get(name) : URLEncoder.encode(params.get(name), encoding));
                count++;
            }
            endpointUri += query;
        }
        logDebug("REST adapter endpoint: " + endpointUri);
        URL url = new URL(endpointUri);
        HttpConnection httpConnection;
        if ("PATCH".equals(getHttpMethod()))
            httpConnection = new HttpAltConnection(url);
        else
            httpConnection = new HttpConnection(url);

        if (proxyHost != null)
            httpConnection.setProxyHost(proxyHost);
        if (proxyPort > 0)
            httpConnection.setProxyPort(proxyPort);
        if (proxyType != null)
            httpConnection.setProxyType(proxyType);

        httpConnection.open();
        return httpConnection;
    }
    catch (Exception ex) {
        throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
    }
}
 
Example 15
Source File: WrapProxy.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public void __construct(Proxy.Type type, String host, int port) {
    __wrappedObject = new Proxy(type, new InetSocketAddress(host, port));
}
 
Example 16
Source File: ProxyConfiguration.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * This method can be used from customValidate method of components using this Controller Service
 * to validate the service is configured with the supported proxy types.
 * @param context the validation context
 * @param results if validation fails, an invalid validation result will be added to this collection
 * @param _specs specify supported proxy specs
 */
public static void validateProxySpec(ValidationContext context, Collection<ValidationResult> results, final ProxySpec ... _specs) {

    final Set<ProxySpec> specs = getUniqueProxySpecs(_specs);
    final Set<Proxy.Type> supportedProxyTypes = specs.stream().map(ProxySpec::getProxyType).collect(Collectors.toSet());

    if (!context.getProperty(PROXY_CONFIGURATION_SERVICE).isSet()) {
        return;
    }

    final ProxyConfigurationService proxyService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
    final ProxyConfiguration proxyConfiguration = proxyService.getConfiguration();
    final Proxy.Type proxyType = proxyConfiguration.getProxyType();

    if (proxyType.equals(Proxy.Type.DIRECT)) {
        return;
    }

    if (!supportedProxyTypes.contains(proxyType)) {
        results.add(new ValidationResult.Builder()
                .explanation(String.format("Proxy type %s is not supported.", proxyType))
                .valid(false)
                .subject(PROXY_CONFIGURATION_SERVICE.getDisplayName())
                .build());

        // If the proxy type is not supported, no need to do further validation.
        return;
    }

    if (proxyConfiguration.hasCredential()) {
        // If credential is set, check whether the component is capable to use it.
        if (!specs.contains(Proxy.Type.HTTP.equals(proxyType) ? HTTP_AUTH : SOCKS_AUTH)) {
            results.add(new ValidationResult.Builder()
                    .explanation(String.format("Proxy type %s with Authentication is not supported.", proxyType))
                    .valid(false)
                    .subject(PROXY_CONFIGURATION_SERVICE.getDisplayName())
                    .build());
        }
    }


}
 
Example 17
Source File: ProxySocketFactory.java    From bisq with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * A convenience constructor for creating a proxy with the specified host
 * and port.
 *
 * @param proxyType The type of proxy were connecting to
 * @param hostname  The hostname of the proxy server
 * @param port      The port of the proxy server
 */
public ProxySocketFactory(Proxy.Type proxyType, String hostname, int port) {
    this.proxy = new Proxy(proxyType, new InetSocketAddress(hostname, port));
}
 
Example 18
Source File: ProxySocketFactory.java    From bisq-core with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * A convenience constructor for creating a proxy with the specified host
 * and port.
 *
 * @param proxyType The type of proxy were connecting to
 * @param hostname  The hostname of the proxy server
 * @param port      The port of the proxy server
 */
public ProxySocketFactory(Proxy.Type proxyType, String hostname, int port) {
    this.proxy = new Proxy(proxyType, new InetSocketAddress(hostname, port));
}
 
Example 19
Source File: RequestLine.java    From AndroidProjects with MIT License 2 votes vote down vote up
/**
 * Returns true if the request line should contain the full URL with host and port (like "GET
 * http://android.com/foo HTTP/1.1") or only the path (like "GET /foo HTTP/1.1").
 */
private static boolean includeAuthorityInRequestLine(Request request, Proxy.Type proxyType) {
  return !request.isHttps() && proxyType == Proxy.Type.HTTP;
}
 
Example 20
Source File: ProxyFactoryBean.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Set the proxy type.
 * <p>Defaults to {@link java.net.Proxy.Type#HTTP}.
 */
public void setType(Proxy.Type type) {
	this.type = type;
}