Example usage for java.net ProxySelector getDefault

List of usage examples for java.net ProxySelector getDefault

Introduction

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

Prototype

public static ProxySelector getDefault() 

Source Link

Document

Gets the system-wide proxy selector.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    System.setProperty("java.net.useSystemProxies", "true");
    List l = ProxySelector.getDefault().select(new URI("http://www.yahoo.com/"));

    for (Iterator iter = l.iterator(); iter.hasNext();) {
        Proxy proxy = (Proxy) iter.next();
        System.out.println("proxy hostname : " + proxy.type());
        InetSocketAddress addr = (InetSocketAddress) proxy.address();
        if (addr == null) {
            System.out.println("No Proxy");
        } else {/*ww  w.j a v a2  s .c  o  m*/
            System.out.println("proxy hostname : " + addr.getHostName());
            System.out.println("proxy port : " + addr.getPort());
        }
    }
}

From source file:com.google.api.ads.adwords.awreporting.server.AwReportingServer.java

/**
 * Main method./*from  w  ww .  j av a 2  s  .  c  o m*/
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = DAFAULT_PROPERTIES_LOCATION;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            System.exit(0);
        }

        setLogLevel(cmdLine);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        }
        System.out.println("Using properties from: " + propertiesPath);

        RestServer restServer = new RestServer();
        restServer.initApplicationContextAndProperties(propertiesPath);

        String mccAccountId = RestServer.getProperties().getProperty("mccAccountId").replaceAll("-", "");

        System.out.println("Updating DB indexes... (may take long the first time)");
        RestServer.getStorageHelper().createReportIndexes();
        System.out.println("DB indexes Updated.");

        if (cmdLine.hasOption("startServer")) {

            // Start the Rest Server
            System.out.println("Starting Rest Server at Port: " + DEFAULT_SERVER_PORT);
            restServer.startServer();

        } else {

            if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {

                if (cmdLine.hasOption("processKratus")) {
                    // Process Kratus, this process runs for the whole MCC in the properties file
                    // within the given dates and creates a daily Kratu per account.
                    System.out.println("Starting Process Kratus...");

                    // Process only the accounts at accountIdsFile
                    Set<Long> accountIdsSet = Sets.newHashSet();
                    if (cmdLine.hasOption("accountIdsFile")) {
                        String accountsFileName = cmdLine.getOptionValue("accountIdsFile");
                        System.out.println("Using accounts file: " + accountsFileName);
                        addAccountsFromFile(accountIdsSet, accountsFileName);
                    }

                    KratuProcessor kratuProcessor = RestServer.getApplicationContext()
                            .getBean(KratuProcessor.class);
                    kratuProcessor.processKratus(Long.valueOf(mccAccountId), accountIdsSet,
                            cmdLine.getOptionValue("startDate"), cmdLine.getOptionValue("endDate"));
                    System.exit(0);

                } else {
                    // Download Reports,
                    // this porcess downloads 7 report types for each account under the MCC
                    System.out.println("Starting Download Reports porcess...");
                    AwReporting.main(args);
                    System.exit(0);

                }
            } else {
                errors = true;
                System.out.println("Configuration incomplete. Missing options for command line.");
            }
        }

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
            System.out.println("Using properties from: " + propertiesPath);

        } else {
            errors = true;
            System.out.println("Configuration incomplete. Missing options for command line.");
        }

    } catch (ParseException e) {
        errors = true;
        System.out.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        System.out.println("Unexpected error: " + e.getMessage());
    }

    if (errors) {
        printHelpMessage(options);
        System.exit(1);
    }
}

From source file:com.google.api.ads.adwords.awalerting.AwAlerting.java

/**
 * Main method.//from   w  ww. j a v  a  2s. c  o m
 *
 * @param args the command line arguments
 */
public static void main(String args[]) {
    // Set up proxy.
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();
    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            printSamplePropertiesFile();
            System.exit(0);
        }

        if (!cmdLine.hasOption("file")) {
            LOGGER.error("Missing required option: 'file'");
            System.exit(1);
        }

        processAlerts(cmdLine);
    } catch (ParseException e) {
        LOGGER.error("Error parsing the values for the command line options.", e);
        System.exit(1);
    } catch (AlertConfigLoadException e) {
        LOGGER.error("Error laoding alerts configuration.", e);
        System.exit(1);
    } catch (AlertProcessingException e) {
        LOGGER.error("Error processing alerts.", e);
        System.exit(1);
    }
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.KratuMain.java

/**
 * Main method./*from w w w.j  a v  a 2 s .c om*/
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = CLASSPATH_AW_REPORT_MODEL_PROPERTIES_LOCATION;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        }
        System.out.println("Using properties from: " + propertiesPath);

        if (cmdLine.hasOption("startServer")) {
            // Start the Rest Server
            System.out.println("Starting Rest Server...");
            initApplicationContextAndProperties(propertiesPath);
            updateAccounts();

            RestServer.createRestServer(appCtx, propertiesPath);

        } else {
            if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {
                if (cmdLine.hasOption("processKratus")) {
                    // Process Kratus, this process runs for the whole MCC
                    // within the given dates and creates a daily Kratu per account.
                    System.out.println("Starting Process Kratus...");
                    initApplicationContextAndProperties(propertiesPath);
                    updateAccounts();

                    KratuProcessor kratuProcessor = appCtx.getBean(KratuProcessor.class);
                    kratuProcessor.processKratus(cmdLine.getOptionValue("startDate"),
                            cmdLine.getOptionValue("endDate"));
                    System.exit(0);

                } else {
                    // Download Reports,
                    // this porcess downloads 7 report types for each account under the MCC
                    System.out.println("Starting Download Reports porcess...");
                    AwReporting.main(args);
                    System.exit(0);

                }
            } else {
                errors = true;
                System.out.println("Configuration incomplete. Missing options for command line.");
            }
        }
    } catch (IOException e) {
        errors = true;
        System.out.println("Properties file (" + propertiesPath + ") not found: " + e.getMessage());
    } catch (ParseException e) {
        errors = true;
        System.out.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        System.out.println("Unexpected error: " + e.getMessage());
    }

    if (errors) {
        printHelpMessage(options);
        System.exit(1);
    }
}

From source file:com.google.api.ads.adwords.awreporting.AwReporting.java

/**
 * Main method./*  ww w. j  a  v  a 2s .co m*/
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = null;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            printSamplePropertiesFile();
            System.exit(0);
        }

        setLogLevel(cmdLine);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        } else {
            LOGGER.error("Missing required option: 'file'");
            System.exit(0);
        }
        LOGGER.info("Using properties file: " + propertiesPath);

        Set<Long> accountIdsSet = Sets.newHashSet();
        if (cmdLine.hasOption("accountIdsFile")) {
            String accountsFileName = cmdLine.getOptionValue("accountIdsFile");
            addAccountsFromFile(accountIdsSet, accountsFileName);
        }

        boolean forceOnFileProcessor = false;
        if (cmdLine.hasOption("onFileReport")) {
            if (!cmdLine.hasOption("csvReportFile") || !cmdLine.hasOption("startDate")
                    || !cmdLine.hasOption("endDate")) {
                LOGGER.error("Missing one or more of the required options: "
                        + "'csvReportFile', 'startDate' or 'endDate'");
                System.exit(0);
            }
            forceOnFileProcessor = true;
        }
        Properties properties = initApplicationContextAndProperties(propertiesPath, forceOnFileProcessor);

        LOGGER.debug("Creating ReportProcessor bean...");
        ReportProcessor processor = createReportProcessor();
        LOGGER.debug("... success.");

        String mccAccountId = properties.getProperty("mccAccountId").replaceAll("-", "");

        if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {
            // Generate Reports
            String dateStart = cmdLine.getOptionValue("startDate");
            String dateEnd = cmdLine.getOptionValue("endDate");

            if (cmdLine.hasOption("onFileReport")) {

                String reportTypeName = cmdLine.getOptionValue("onFileReport");
                String csvReportFile = cmdLine.getOptionValue("csvReportFile");

                File csvFile = new File(csvReportFile);
                if (!csvFile.exists()) {
                    LOGGER.error("Could not find CSV file: " + csvReportFile);
                    System.exit(0);
                }

                ReportProcessorOnFile onFileProcessor = (ReportProcessorOnFile) processor;
                List<File> localFiles = new ArrayList<File>();
                localFiles.add(csvFile);

                LOGGER.info(
                        "Starting report processing for dateStart: " + dateStart + " and dateEnd: " + dateEnd);
                onFileProcessor.processInputFiles(mccAccountId, reportTypeName, localFiles, dateStart, dateEnd,
                        ReportDefinitionDateRangeType.CUSTOM_DATE);

            } else {
                LOGGER.info(
                        "Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd);

                processor.generateReportsForMCC(mccAccountId, ReportDefinitionDateRangeType.CUSTOM_DATE,
                        dateStart, dateEnd, accountIdsSet, properties, null, null);
            }
        } else if (cmdLine.hasOption("dateRange")) {

            ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType
                    .fromValue(cmdLine.getOptionValue("dateRange"));

            LOGGER.info("Starting report download for dateRange: " + dateRangeType.name());

            processor.generateReportsForMCC(mccAccountId, dateRangeType, null, null, accountIdsSet, properties,
                    null, null);

        } else {
            errors = true;
            LOGGER.error("Configuration incomplete. Missing options for command line.");
        }

    } catch (IOException e) {
        errors = true;

        if (e.getMessage().contains("Insufficient Permission")) {
            LOGGER.error("Insufficient Permission error accessing the API" + e.getMessage());
        } else {
            LOGGER.error("File not found: " + e.getMessage());
        }

    } catch (ParseException e) {
        errors = true;
        System.err.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        LOGGER.error("Unexpected error accessing the API: " + e.getMessage());
        e.printStackTrace();
    }

    if (errors) {
        System.exit(1);
    } else {
        System.exit(0);
    }
}

From source file:com.google.api.ads.adwords.jaxws.extensions.AwReporting.java

/**
 * Main method.//from  w w w .  j av  a 2s . c  o m
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = null;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            printSamplePropertiesFile();
            System.exit(0);
        }

        setLogLevel(cmdLine);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        } else {
            LOGGER.error("Missing required option: 'file'");
            System.exit(0);
        }
        LOGGER.info("Using properties file: " + propertiesPath);

        Set<Long> accountIdsSet = Sets.newHashSet();
        if (cmdLine.hasOption("accountIdsFile")) {
            String accountsFileName = cmdLine.getOptionValue("accountIdsFile");
            addAccountsFromFile(accountIdsSet, accountsFileName);
        }

        Properties properties = initApplicationContextAndProperties(propertiesPath);

        ReportModeService.setReportMode(properties.getProperty("reportMode")); //TODO Any other approach?

        LOGGER.debug("Creating ReportProcessor bean...");
        ReportProcessor processor = createReportProcessor();
        LOGGER.debug("... success.");

        if (cmdLine.hasOption("generatePdf")) {

            LOGGER.debug("GeneratePDF option detected.");

            // Get HTML template and output directoy
            String[] pdfFiles = cmdLine.getOptionValues("generatePdf");
            File htmlTemplateFile = new File(pdfFiles[0]);
            File outputDirectory = new File(pdfFiles[1]);

            LOGGER.debug("Html template file to be used: " + htmlTemplateFile);
            LOGGER.debug("Output directory for PDF: " + outputDirectory);

            // Generate PDFs
            generatePdf(processor, cmdLine.getOptionValue("startDate"), cmdLine.getOptionValue("endDate"),
                    properties, htmlTemplateFile, outputDirectory);

        } else if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {
            // Generate Reports

            String dateStart = cmdLine.getOptionValue("startDate");
            String dateEnd = cmdLine.getOptionValue("endDate");

            LOGGER.info("Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd);

            processor.generateReportsForMCC(ReportDefinitionDateRangeType.CUSTOM_DATE, dateStart, dateEnd,
                    accountIdsSet, properties);

        } else if (cmdLine.hasOption("dateRange")) {

            ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType
                    .fromValue(cmdLine.getOptionValue("dateRange"));

            LOGGER.info("Starting report download for dateRange: " + dateRangeType.name());

            processor.generateReportsForMCC(dateRangeType, null, null, accountIdsSet, properties);

        } else {
            errors = true;
            LOGGER.error("Configuration incomplete. Missing options for command line.");
        }
    } catch (IOException e) {
        errors = true;
        LOGGER.error("File not found: " + e.getMessage());
    } catch (ParseException e) {
        errors = true;
        System.err.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        LOGGER.error("Unexpected error accessing the API: " + e.getMessage());
        e.printStackTrace();
    }

    if (errors) {
        System.exit(1);
    } else {
        System.exit(0);
    }
}

From source file:eu.delving.sip.base.HttpClientFactory.java

private static void handleProxy(String serverUrl, HttpClientBuilder builder) {
    try {//from  ww  w.  j a va2s.  c  om
        List<Proxy> proxies = ProxySelector.getDefault().select(new URI(serverUrl));
        for (Proxy proxy : proxies) {
            if (proxy.type() != Proxy.Type.HTTP)
                continue;
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            builder.setProxy(new HttpHost(host, port));
        }
    } catch (URISyntaxException e) {
        throw new RuntimeException("Bad address: " + serverUrl, e);
    }
}

From source file:eu.esdihumboldt.util.http.ProxyUtil.java

/**
 * Tries to find the system's proxy configuration for a given URI
 * //ww w .  j a  v  a2 s.  c  om
 * @param uri the URI
 * @return the proxy configuration (host and port)
 */
public static Proxy findProxy(URI uri) {
    init();

    // BUGFIX: Don't use this property since it makes the connection hang!
    // Rather set the proxy through the system properties
    // "http.proxyHost" and "http.proxyPort".
    // System.setProperty("java.net.useSystemProxies", "true");

    List<Proxy> proxies = ProxySelector.getDefault().select(uri);
    if (proxies != null && proxies.size() > 0) {
        for (Proxy proxy : proxies) {
            if (proxy.type() == Proxy.Type.HTTP) {
                return proxy;
            }
        }
    }

    return Proxy.NO_PROXY;

    /*
     * The following code is obsolete System properties are handled
     * correctly by proxy selector The only thing that the code supports
     * additionally is setting using a proxy for the host that is the proxy
     * host
     */
    /*
     * String strProxyHost = System.getProperty("http.proxyHost"); String
     * strProxyPort = System.getProperty("http.proxyPort"); String
     * strNonProxyHosts = System.getProperty("http.nonProxyHosts"); String[]
     * nonProxyHosts; if (strNonProxyHosts != null) { nonProxyHosts =
     * strNonProxyHosts.split("\\|"); } else { nonProxyHosts = new
     * String[0]; }
     * 
     * if (strProxyHost != null && strProxyPort != null) { boolean noProxy =
     * false; for (int i = 0; i < nonProxyHosts.length; ++i) { if
     * (nonProxyHosts[i].equalsIgnoreCase(uri.getHost())) { noProxy = true;
     * break; } }
     * 
     * if (!noProxy) { int proxyPort = Integer.parseInt(strProxyPort);
     * return new InetSocketAddress(strProxyHost, proxyPort); } }
     * 
     * return null;
     */
}

From source file:jfs.sync.util.WindowsProxySelector.java

private WindowsProxySelector() {
    root = ProxySelector.getDefault();
    ProxySelector.setDefault(null);
    if (LOG.isDebugEnabled()) {
        LOG.debug("select() root " + root);
    } // if/*from   w  w w  .  j  a  v a 2s .c  om*/
}

From source file:net.sf.zekr.engine.network.NetworkController.java

public NetworkController(PropertiesConfiguration props) {
    this.props = props;

    if (!props.getBoolean("network.proxy.internal.disableJvmUseSystemProxy", false)) {
        System.setProperty("java.net.useSystemProxies", "true");
    }//from  w ww.  jav  a  2  s  .  c  o  m

    proxySelector = ProxySelector.getDefault();
    defaultProxy = props.getString("network.proxy", "system");
    proxyType = props.getString("network.proxy.type", "HTTP");
    proxyServer = props.getString("network.proxy.server", "127.0.0.1");
    String port = props.getString("network.proxy.port");
    if (StringUtils.isNotBlank(port)) {
        proxyPort = Integer.parseInt(port);
    } else {
        proxyPort = 80;
    }
}