Example usage for java.net Proxy Proxy

List of usage examples for java.net Proxy Proxy

Introduction

In this page you can find the example usage for java.net Proxy Proxy.

Prototype

public Proxy(Type type, SocketAddress sa) 

Source Link

Document

Creates an entry representing a PROXY connection.

Usage

From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java

private void setupHttpClient() {
    // TODO: make configurable ?
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);

    if (proxyUrl != null) {
        Proxy p = new Proxy(Proxy.Type.HTTP,
                InetSocketAddress.createUnresolved(proxyUrl.getHost(), proxyUrl.getPort()));
        client.setProxy(p);/*  w  w w  . ja  v  a 2  s .c  o  m*/
    }
}

From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinAccountConnection.java

public void init() {

    log.info("init()");

    proxyHost = serverConfigurationService.getString("turnitin.proxyHost");

    proxyPort = serverConfigurationService.getString("turnitin.proxyPort");

    if (!"".equals(proxyHost) && !"".equals(proxyPort)) {
        try {//from w  w  w. j a  va  2  s . c  o m
            SocketAddress addr = new InetSocketAddress(proxyHost, new Integer(proxyPort).intValue());
            proxy = new Proxy(Proxy.Type.HTTP, addr);
            log.debug("Using proxy: " + proxyHost + " " + proxyPort);
        } catch (NumberFormatException e) {
            log.debug("Invalid proxy port specified: " + proxyPort);
        }
    } else if (System.getProperty("http.proxyHost") != null
            && !System.getProperty("http.proxyHost").equals("")) {
        try {
            SocketAddress addr = new InetSocketAddress(System.getProperty("http.proxyHost"),
                    new Integer(System.getProperty("http.proxyPort")).intValue());
            proxy = new Proxy(Proxy.Type.HTTP, addr);
            log.debug("Using proxy: " + System.getProperty("http.proxyHost") + " "
                    + System.getProperty("http.proxyPort"));
        } catch (NumberFormatException e) {
            log.debug("Invalid proxy port specified: " + System.getProperty("http.proxyPort"));
        }
    }

    aid = serverConfigurationService.getString("turnitin.aid");

    said = serverConfigurationService.getString("turnitin.said");

    secretKey = serverConfigurationService.getString("turnitin.secretKey");

    apiURL = serverConfigurationService.getString("turnitin.apiURL", "https://api.turnitin.com/api.asp?");

    defaultInstructorEmail = serverConfigurationService.getString("turnitin.defaultInstructorEmail");

    defaultInstructorFName = serverConfigurationService.getString("turnitin.defaultInstructorFName");

    defaultInstructorLName = serverConfigurationService.getString("turnitin.defaultInstructorLName");

    defaultInstructorPassword = serverConfigurationService.getString("turnitin.defaultInstructorPassword");

    useSourceParameter = serverConfigurationService.getBoolean("turnitin.useSourceParameter", false);

    migrate = serverConfigurationService.getBoolean("turnitin.migrate", false);

    useGrademark = serverConfigurationService.getBoolean("turnitin.useGrademark", true);

    // Account notification options (default value is false)
    boolean sendAccountNotifications = (serverConfigurationService.getBoolean("turnitin.sendnotifications",
            false) || serverConfigurationService.getBoolean("turnitin.sendAccountNotifications", false));

    instructorAccountNotified = serverConfigurationService
            .getBoolean("turnitin.sendAccountNotifications.instructors", sendAccountNotifications);
    studentAccountNotified = serverConfigurationService.getBoolean("turnitin.sendAccountNotifications.student",
            sendAccountNotifications);

    // Submission notification options (default value is false)
    sendSubmissionNotification = serverConfigurationService.getBoolean("turnitin.sendSubmissionNotifications",
            false) ? 1 : 0;

    log.debug("Notification options:" + " instructorAccountNotified=" + instructorAccountNotified
            + " studentAccountNotified=" + studentAccountNotified + " sendSubmissionNotification="
            + sendSubmissionNotification);

    //note that the assignment id actually has to be unique globally so use this as a prefix
    // assignid = defaultAssignId + siteId
    defaultAssignId = serverConfigurationService.getString("turnitin.defaultAssignId");
    ;

    defaultClassPassword = serverConfigurationService.getString("turnitin.defaultClassPassword", "changeit");
    ;

    defaultInstructorId = serverConfigurationService.getString("turnitin.defaultInstructorId", "admin");

    maxRetry = Long.valueOf(serverConfigurationService.getInt("turnitin.maxRetry", 100));

    // Timeout period in ms for network connections (default 180s). Set to 0 to disable timeout.
    turnitinConnTimeout = serverConfigurationService.getInt("turnitin.networkTimeout", 180000);

}

From source file:org.eclipse.mylyn.trac.tests.client.TracClientTest.java

public void testProxy() throws Exception {
    client = fixture.connect(fixture.getRepositoryUrl(), "", "",
            new Proxy(Type.HTTP, new InetSocketAddress("invalidhostname", 8080)));
    try {//from   ww  w  .j  a  v a2  s .c  o m
        client.validate(new NullProgressMonitor());
        fail("Expected IOException");
    } catch (TracException e) {
    }
}

From source file:fr.free.movierenamer.utils.URIRequest.java

private static URLConnection openConnection(URI uri, RequestProperty... properties) throws IOException {
    boolean isHttpRequest = Proxy.Type.HTTP.name().equalsIgnoreCase(uri.getScheme());
    URLConnection connection;//from w ww  .j a  va  2  s  .c  om
    if (isHttpRequest && Settings.getInstance().isProxyIsOn()) {
        Settings settings = Settings.getInstance();
        Proxy proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(settings.getProxyUrl(), settings.getProxyPort()));
        connection = uri.toURL().openConnection(proxy);
    } else {
        connection = uri.toURL().openConnection();
    }

    if (isHttpRequest) {
        Settings settings = Settings.getInstance();
        connection.setReadTimeout(settings.getHttpRequestTimeOut() * 1000); // in ms
        //fake user agent ;)
        connection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
        connection.addRequestProperty("From", "googlebot(at)googlebot.com");
        connection.addRequestProperty("Accept", "*/*");
        String customUserAgent = settings.getHttpCustomUserAgent();
        if (customUserAgent != null && customUserAgent.length() > 0) {
            connection.addRequestProperty("User-Agent", customUserAgent);
        }
    }

    connection.addRequestProperty("Accept-Encoding", "gzip,deflate");
    connection.addRequestProperty("Accept-Charset", UTF + "," + ISO); // important for accents !

    if (properties != null) {
        for (RequestProperty property : properties) {
            connection.addRequestProperty(property.getKey(), property.getValue());
        }
    }

    return connection;
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.ForwardHttpServletMapping.java

@Override
public void init(HttpServletTransactionManager transactionManager, FormatterManager formatterMgr,
        Node configurationNode) throws AdapterHttpInitializationException {

    try {/*from w  w  w.j  av  a  2  s  .  co m*/
        action = XMLConfig.get(configurationNode, "@Action");
        dump = XMLConfig.getBoolean(configurationNode, "@dump-in-out", false);

        Node endpointNode = XMLConfig.getNode(configurationNode, "endpoint");
        host = XMLConfig.get(endpointNode, "@host");
        port = XMLConfig.get(endpointNode, "@port", "80");
        contextPath = XMLConfig.get(endpointNode, "@context-path", "");
        secure = XMLConfig.getBoolean(endpointNode, "@secure", false);
        connTimeout = XMLConfig.getInteger(endpointNode, "@conn-timeout", DEFAULT_CONN_TIMEOUT);
        soTimeout = XMLConfig.getInteger(endpointNode, "@so-timeout", DEFAULT_SO_TIMEOUT);

        URL url = new URL(secure ? "https" : "http", host, Integer.valueOf(port), contextPath);

        Node proxyConfigNode = XMLConfig.getNode(endpointNode, "Proxy");
        if (proxyConfigNode != null) {
            String proxyHost = XMLConfig.get(proxyConfigNode, "@host");
            int proxyPort = XMLConfig.getInteger(proxyConfigNode, "@port", 80);

            Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = url.openConnection(proxy);

            String proxyUser = XMLConfig.get(proxyConfigNode, "@user", "");
            String proxyPassword = XMLConfig.getDecrypted(proxyConfigNode, "@password", "");

            if (proxyUser.trim().length() > 0) {
                String proxyAuthorization = proxyUser + ":" + proxyPassword;
                connection.setRequestProperty("Proxy-Authorization",
                        Base64.getEncoder().encodeToString(proxyAuthorization.getBytes()));
            }

        } else {
            connection = url.openConnection();
        }

        connection.setConnectTimeout(connTimeout);

    } catch (Exception exc) {
        throw new AdapterHttpInitializationException("GVHTTP_CONFIGURATION_ERROR",
                new String[][] { { "message", exc.getMessage() } }, exc);
    }

}

From source file:com.collabnet.ccf.pi.cee.pt.v50.CollabNetConnectionFactory.java

public TrackerWebServicesClient createConnection(String systemId, String systemKind, String repositoryId,
        String repositoryKind, String connectionInfo, String credentialInfo,
        ConnectionManager<TrackerWebServicesClient> connectionManager) throws ConnectionException {
    if (StringUtils.isEmpty(repositoryId)) {
        throw new IllegalArgumentException("Repository Id cannot be null");
    }/*from w  w w .j a v a  2  s  .  com*/

    String username = null;
    String password = null;
    if (credentialInfo != null) {
        String[] splitCredentials = credentialInfo.split(PARAM_DELIMITER);
        if (splitCredentials != null) {
            if (splitCredentials.length == 1) {
                username = splitCredentials[0];
                password = "";
            } else if (splitCredentials.length == 2) {
                username = splitCredentials[0];
                password = splitCredentials[1];
            } else {
                String message = "Credentials info is not valid " + credentialInfo;
                log.error(message);
                throw new IllegalArgumentException(message);
            }
        }
    }
    String projectName = null;
    if (repositoryId != null) {
        String[] splitProjectName = repositoryId.split(":");
        if (splitProjectName != null) {
            if (splitProjectName.length >= 1) {
                projectName = splitProjectName[0];
            } else {
                throw new IllegalArgumentException("Repository id " + repositoryId + " is not valid."
                        + " Could not extract project name from repository id");
            }
        }
    }
    String url = connectionInfo.substring(0, connectionInfo.indexOf("://") + 3) + projectName + "."
            + connectionInfo.substring(connectionInfo.indexOf("://") + 3);
    TrackerWebServicesClient twsclient = null;
    try {
        Proxy proxy = null;
        if (proxyUsed) {
            if (StringUtils.isEmpty(this.proxyHost)) {
                throw new IllegalArgumentException("Proxy host is not valid." + this.proxyHost);
            } else if (this.proxyPort == -1) {
                throw new IllegalArgumentException("Proxy port is not valid " + this.proxyPort);
            }
            Proxy.Type type = null;
            try {
                type = Proxy.Type.valueOf(this.proxyType);
            } catch (Exception e) {
                throw new IllegalArgumentException("Proxy type is not valid " + this.proxyType
                        + ". Proxy type should either be HTTP or SOCKS");
            }
            InetSocketAddress socketAddress = new InetSocketAddress(this.proxyHost, this.proxyPort);

            proxy = new Proxy(type, socketAddress);
        } else {
            proxy = Proxy.NO_PROXY;
        }
        twsclient = TrackerClientManager.getInstance().createClient(url, username, password, null, null, proxy);
    } catch (MalformedURLException e) {
        String message = "Exception when trying to get the Web Services client";
        log.error(message, e);
        throw new ConnectionException(message, e);
    }
    return twsclient;
}

From source file:com.hp.mqm.atrf.core.rest.RestConnector.java

/**
 * @param type         of the http operation: get post put delete
 * @param url          to work on//from   w w w .j av  a2 s  . co m
 * @param queryParams
 * @param data         to write, if a writable operation
 * @param headers      to use in the request
 * @param afterRelogin if equal to false and received 401 and supportRelogin is exist - trial to relogin will be done
 * @return http response
 */
private Response doHttp(String type, String url, List<String> queryParams, String data,
        Map<String, String> headers, boolean afterRelogin) {

    //add query params
    if ((queryParams != null) && !queryParams.isEmpty()) {

        if (url.contains("?")) {
            url += "&";
        } else {
            url += "?";
        }
        url += StringUtils.join(queryParams, "&");
    }

    long start = System.currentTimeMillis();
    String fullUrl = baseUrl + url;
    try {

        HttpURLConnection con;
        if (StringUtils.isEmpty(proxyHost)) {
            con = (HttpURLConnection) new URL(fullUrl).openConnection();
        } else {
            try {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                con = (HttpURLConnection) new URL(fullUrl).openConnection(proxy);
            } catch (Exception e) {
                throw new RuntimeException("Failed to define connection with proxy parameters");
            }
        }

        con.setRequestMethod(type);
        String cookieString = getCookieString();

        prepareHttpRequest(con, headers, data, cookieString);

        con.connect();
        Response ret = retrieveHtmlResponse(con);
        long end = System.currentTimeMillis();
        String msg = String.format("%s %s:%s , total time %s ms", ret.getStatusCode(), type, fullUrl,
                end - start);
        logger.info(msg);

        updateCookies(ret);

        if (ret.getStatusCode() != HttpStatus.SC_OK && ret.getStatusCode() != HttpStatus.SC_CREATED
                && ret.getStatusCode() != HttpStatus.SC_ACCEPTED) {
            throw new RestStatusException(ret);
        }

        return ret;
    } catch (RestStatusException e) {
        if ((e.getResponse().getStatusCode() == HttpStatus.SC_UNAUTHORIZED)
                || (e.getResponse().getStatusCode() == 0
                        && e.getResponse().getResponseData().equals("Error writing to server"))) {
            if (!afterRelogin && supportRelogin != null) {
                boolean reloginResult = false;
                try {
                    reloginResult = supportRelogin.relogin();
                    String msg = String.format("Received status %s. Relogin succeeded.",
                            e.getResponse().getStatusCode());
                    logger.warn(msg);
                } catch (Exception ex) {
                    String msg = String.format("Received status %s. Relogin failed %s",
                            e.getResponse().getStatusCode(), ex.getMessage());
                    logger.warn(msg);
                }

                if (reloginResult) {
                    return doHttp(type, url, queryParams, data, headers, true);
                }
            }
        }
        throw e;//rethrow
    } catch (Exception e) {
        long end = System.currentTimeMillis();
        String msg = String.format("%s %s:%s , total time %s ms, %s", "ERR", type, fullUrl, end - start,
                e.getMessage());
        logger.error(msg);
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.nuxeo.rss.reader.FeedHelper.java

public static SyndFeed parseFeed(String feedUrl) throws Exception {
    URL url = new URL(feedUrl);
    SyndFeedInput input = new SyndFeedInput();
    URLConnection urlConnection;/*from w  w  w .  j  a va  2s . c o m*/
    if (FeedUrlConfig.useProxy()) {
        SocketAddress addr = new InetSocketAddress(FeedUrlConfig.getProxyHost(), FeedUrlConfig.getProxyPort());
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
        urlConnection = url.openConnection(proxy);
        if (FeedUrlConfig.isProxyAuthenticated()) {
            String encoded = Base64.encodeBytes(
                    new String(FeedUrlConfig.getProxyLogin() + ":" + FeedUrlConfig.getProxyPassword())
                            .getBytes());
            urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
            urlConnection.connect();
        }
    } else {
        urlConnection = url.openConnection();
    }
    SyndFeed feed = input.build(new XmlReader(urlConnection));
    return feed;
}

From source file:com.googlecode.gmail4j.http.HttpProxyAwareSslSocketFactory.java

public void setProxy(final String proxyHost, final int proxyPort) {
    this.proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(proxyHost, proxyPort));
}

From source file:org.jmxtrans.embedded.output.StackdriverWriter.java

/**
 * Initial setup for the writer class. Loads in settings and initializes one-time setup variables like instanceId.
 *//*from   w w w . ja v  a  2s  .  c o  m*/
@Override
public void start() {
    try {
        url = new URL(getStringSetting(SETTING_URL, DEFAULT_STACKDRIVER_API_URL));
    } catch (MalformedURLException e) {
        throw new EmbeddedJmxTransException(e);
    }

    apiKey = getStringSetting(SETTING_TOKEN);

    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)));
    }

    logger.info("Starting Stackdriver writer connected to '{}', proxy {} ...", url, proxy);

    stackdriverApiTimeoutInMillis = getIntSetting(SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS,
            DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS);

    // try to get and instance ID
    if (getStringSetting(SETTING_SOURCE_INSTANCE, null) != null
            && !getStringSetting(SETTING_SOURCE_INSTANCE).isEmpty()) {
        // if one is set directly use that
        instanceId = getStringSetting(SETTING_SOURCE_INSTANCE);
        logger.info("Using instance ID {} from setting {}", instanceId, SETTING_SOURCE_INSTANCE);
    } else if (getStringSetting(SETTING_DETECT_INSTANCE, null) != null
            && "AWS".equalsIgnoreCase(getStringSetting(SETTING_DETECT_INSTANCE))) {
        // if setting is to detect, look on the local machine URL
        logger.info("Detect instance set to AWS, trying to determine AWS instance ID");
        instanceId = getLocalAwsInstanceId();
        if (instanceId != null) {
            logger.info("Detected instance ID as {}", instanceId);
        } else {
            logger.info(
                    "Unable to detect AWS instance ID for this machine, sending metrics without an instance ID");
        }
    } else {
        // no instance ID, the metrics will be sent as "bare" custom metrics and not associated with an instance
        instanceId = null;
        logger.info(
                "No source instance ID passed, and not set to detect, sending metrics without and instance ID");
    }

}