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.diablominer.DiabloMiner.DiabloMiner.java

void execute(String[] args) throws Exception {
    threads.add(Thread.currentThread());

    Options options = new Options();
    options.addOption("u", "user", true, "bitcoin host username");
    options.addOption("p", "pass", true, "bitcoin host password");
    options.addOption("o", "host", true, "bitcoin host IP");
    options.addOption("r", "port", true, "bitcoin host port");
    options.addOption("l", "url", true, "bitcoin host url");
    options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>");
    options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds");
    options.addOption("d", "debug", false, "enable debug output");
    options.addOption("dt", "debugtimer", false, "run for 1 minute and quit");
    options.addOption("D", "devices", true, "devices to enable, default all");
    options.addOption("f", "fps", true, "target GPU execution timing");
    options.addOption("na", "noarray", false, "turn GPU kernel array off");
    options.addOption("v", "vectors", true, "vector size in GPU kernel");
    options.addOption("w", "worksize", true, "override GPU worksize");
    options.addOption("ds", "ksource", false, "output GPU kernel source and quit");
    options.addOption("h", "help", false, "this help");

    PosixParser parser = new PosixParser();

    CommandLine line = null;//from   w w  w . j a v  a 2s .com

    try {
        line = parser.parse(options, args);

        if (line.hasOption("help")) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options,
                "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf "
                        + "before starting bitcoind or bitcoin --daemon");
        return;
    }

    String splitUrl[] = null;
    String splitUser[] = null;
    String splitPass[] = null;
    String splitHost[] = null;
    String splitPort[] = null;

    if (line.hasOption("url"))
        splitUrl = line.getOptionValue("url").split(",");

    if (line.hasOption("user"))
        splitUser = line.getOptionValue("user").split(",");

    if (line.hasOption("pass"))
        splitPass = line.getOptionValue("pass").split(",");

    if (line.hasOption("host"))
        splitHost = line.getOptionValue("host").split(",");

    if (line.hasOption("port"))
        splitPort = line.getOptionValue("port").split(",");

    int networkStatesCount = 0;

    if (splitUrl != null)
        networkStatesCount = splitUrl.length;

    if (splitUser != null)
        networkStatesCount = Math.max(splitUser.length, networkStatesCount);

    if (splitPass != null)
        networkStatesCount = Math.max(splitPass.length, networkStatesCount);

    if (splitHost != null)
        networkStatesCount = Math.max(splitHost.length, networkStatesCount);

    if (splitPort != null)
        networkStatesCount = Math.max(splitPort.length, networkStatesCount);

    if (networkStatesCount == 0) {
        error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r");
        System.exit(-1);
    }

    int j = 0;

    for (int i = 0; j < networkStatesCount; i++, j++) {
        String protocol = "http";
        String host = "localhost";
        int port = 8332;
        String path = "/";
        String user = "diablominer";
        String pass = "diablominer";
        byte hostChain = 0;

        if (splitUrl != null && splitUrl.length > i) {
            String[] usernameFix = splitUrl[i].split("@", 3);
            if (usernameFix.length > 2)
                splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2];

            URL url = new URL(splitUrl[i]);

            if (url.getProtocol() != null && url.getProtocol().length() > 1)
                protocol = url.getProtocol();

            if (url.getHost() != null && url.getHost().length() > 1)
                host = url.getHost();

            if (url.getPort() != -1)
                port = url.getPort();

            if (url.getPath() != null && url.getPath().length() > 1)
                path = url.getPath();

            if (url.getUserInfo() != null && url.getUserInfo().length() > 1) {
                String[] userPassSplit = url.getUserInfo().split(":");

                user = userPassSplit[0].replace("+++++", "@");

                if (userPassSplit.length > 1 && userPassSplit[1].length() > 1)
                    pass = userPassSplit[1];
            }
        }

        if (splitUser != null && splitUser.length > i)
            user = splitUser[i];

        if (splitPass != null && splitPass.length > i)
            pass = splitPass[i];

        if (splitHost != null && splitHost.length > i)
            host = splitHost[i];

        if (splitPort != null && splitPort.length > i)
            port = Integer.parseInt(splitPort[i]);

        NetworkState networkState;

        try {
            networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass,
                    hostChain);
        } catch (MalformedURLException e) {
            throw new DiabloMinerFatalException(this, "Malformed connection paramaters");
        }

        if (networkStateHead == null) {
            networkStateHead = networkStateTail = networkState;
        } else {
            networkStateTail.setNetworkStateNext(networkState);
            networkStateTail = networkState;
        }
    }

    networkStateTail.setNetworkStateNext(networkStateHead);

    if (line.hasOption("proxy")) {
        final String[] proxySettings = line.getOptionValue("proxy").split(":");

        if (proxySettings.length >= 2) {
            proxy = new Proxy(Type.HTTP,
                    new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1])));
        }

        if (proxySettings.length >= 3) {
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray());
                }
            });
        }
    }

    if (line.hasOption("worklifetime"))
        workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000;

    if (line.hasOption("debug"))
        debug = true;

    if (line.hasOption("debugtimer")) {
        debugtimer = true;
    }

    if (line.hasOption("devices")) {
        String devices[] = line.getOptionValue("devices").split(",");
        enabledDevices = new HashSet<String>();
        for (String s : devices) {
            enabledDevices.add(s);

            if (Integer.parseInt(s) == 0) {
                error("Do not use 0 with -D, devices start at 1");
                System.exit(-1);
            }
        }
    }

    if (line.hasOption("fps")) {
        GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps"));

        if (GPUTargetFPS < 0.1) {
            error("--fps argument is too low, adjusting to 0.1");
            GPUTargetFPS = 0.1;
        }
    }

    if (line.hasOption("noarray")) {
        GPUNoArray = true;
    }

    if (line.hasOption("worksize"))
        GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize"));

    if (line.hasOption("vectors")) {
        String tempVectors[] = line.getOptionValue("vectors").split(",");

        GPUVectors = new Integer[tempVectors.length];

        try {
            for (int i = 0; i < GPUVectors.length; i++) {
                GPUVectors[i] = Integer.parseInt(tempVectors[i]);

                if (GPUVectors[i] > 16) {
                    error("DiabloMiner now uses comma-seperated vector layouts, use those instead");
                    System.exit(-1);
                } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4
                        && GPUVectors[i] != 8 && GPUVectors[i] != 16) {
                    error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16");
                    System.exit(-1);
                }
            }

            Arrays.sort(GPUVectors, Collections.reverseOrder());
        } catch (NumberFormatException e) {
            error("Cannot parse --vector argument(s)");
            System.exit(-1);
        }
    } else {
        GPUVectors = new Integer[1];
        GPUVectors[0] = 1;
    }

    if (line.hasOption("ds"))
        GPUDebugSource = true;

    info("Started");

    StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString());
    NetworkState networkState = networkStateHead.getNetworkStateNext();

    while (networkState != networkStateHead) {
        list.append(", " + networkState.getQueryUrl());
        networkState = networkState.getNetworkStateNext();
    }

    info("Connecting to: " + list);

    long previousHashCount = 0;
    double previousAdjustedHashCount = 0.0;
    long previousAdjustedStartTime = startTime = (now()) - 1;
    StringBuilder hashMeter = new StringBuilder(80);
    Formatter hashMeterFormatter = new Formatter(hashMeter);

    int deviceCount = 0;

    List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>();

    List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates();
    deviceCount += GPUDeviceStates.size();
    allDeviceStates.add(GPUDeviceStates);

    while (running.get()) {
        for (List<? extends DeviceState> deviceStates : allDeviceStates) {
            for (DeviceState deviceState : deviceStates) {
                deviceState.checkDevice();
            }
        }

        long now = now();
        long currentHashCount = hashCount.get();
        double adjustedHashCount = (double) (currentHashCount - previousHashCount)
                / (double) (now - previousAdjustedStartTime);
        double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0;

        if (now - startTime > TIME_OFFSET * 2) {
            double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0;

            hashMeter.setLength(0);

            if (!debug) {
                hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d",
                        averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get());
            } else {
                hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount,
                        hashLongCount, blocks.get(), rejects.get(), hwErrors.get());

                double basisAverage = 0.0;

                for (List<? extends DeviceState> deviceStates : allDeviceStates) {
                    for (DeviceState deviceState : deviceStates) {
                        hashMeterFormatter.format("%.1f ",
                                deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0);
                        basisAverage += deviceState.getBasis();
                    }
                }

                basisAverage = 1000 / (basisAverage / deviceCount);

                hashMeterFormatter.format("| fps: %.1f", basisAverage);
            }

            System.out.print(hashMeter);
        } else {
            System.out.print("\rWaiting...");
        }

        if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) {
            previousHashCount = currentHashCount;
            previousAdjustedHashCount = adjustedHashCount;
            previousAdjustedStartTime = now - 1;
        }

        if (debugtimer && now() > startTime + 60 * 1000) {
            System.out.print("\n");
            info("Debug timer is up, quitting...");
            System.exit(0);
        }

        try {
            if (now - startTime > TIME_OFFSET)
                Thread.sleep(1000);
            else
                Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }

    hashMeterFormatter.close();
}

From source file:forge.download.GuiDownloadService.java

protected Proxy getProxy() {
    if (type == 0) {
        return Proxy.NO_PROXY;
    } else {//from w  w w.  j av a  2s.co  m
        try {
            return new Proxy(TYPES[type],
                    new InetSocketAddress(txtAddress.getText(), Integer.parseInt(txtPort.getText())));
        } catch (final Exception ex) {
            BugReporter.reportException(ex,
                    "Proxy connection could not be established!\nProxy address: %s\nProxy port: %s",
                    txtAddress.getText(), txtPort.getText());
        }
    }
    return null;
}

From source file:org.owasp.ProcessMojo.java

/**
 * execute the whole shabang/*from   w  w w . ja v a2  s .c  om*/
 *
 * @throws MojoExecutionException
 */
public void execute() throws MojoExecutionException {
    System.setProperty("java.net.debug", "all");

    try {

        zapClientAPI = new ClientApi(zapProxyHost, zapProxyPort);
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(zapProxyHost, zapProxyPort));

        if (spiderURL) {
            getLog().info("Spider the site [" + targetURL + "]");
            spiderURL(targetURL);
        } else {
            getLog().info("skip spidering the site [" + targetURL + "]");
        }

        if (scanURL) {
            getLog().info("Scan the site [" + targetURL + "]");
            scanURL(targetURL);
        } else {
            getLog().info("skip scanning the site [" + targetURL + "]");
        }

        // filename to share between the session file and the report file
        String fileName = "";
        if (saveSession) {

            fileName = createTempFilename("ZAP", "");

            zapClientAPI.core.saveSession(fileName, "true", "");
        } else {
            getLog().info("skip saveSession");
        }

        if (reportAlerts) {

            // reuse fileName of the session file
            if ((reportsFilenameNoExtension == null) || reportsFilenameNoExtension.isEmpty()) {
                if ((fileName == null) || (fileName.length() == 0)) {
                    fileName = createTempFilename("ZAP", "");
                }
            } else {
                fileName = reportsFilenameNoExtension;
            }

            String fileName_no_extension = FilenameUtils.concat(reportsDirectory, fileName);

            try {
                String alerts = getAllAlerts(getAllAlertsFormat(format));
                String fullFileName = fileName_no_extension + "." + getAllAlertsFormat(format);
                FileUtils.writeStringToFile(new File(fullFileName), alerts);
                getLog().info("File save in format in [" + getAllAlertsFormat(format) + "]");
                if (format.equals("json")) {
                    Utils.copyResourcesRecursively(getClass().getResource("/zap-reports/"),
                            new File(reportsDirectory));
                }
            } catch (Exception e) {
                getLog().error(e.toString());
                e.printStackTrace();
            }
        }

        if ((propertyFile != null) && !propertyFile.isEmpty()) {
            restoreProperties();
        }

    } catch (Exception e) {
        getLog().error(e.toString());
        throw new MojoExecutionException("Processing with ZAP failed");
    } finally {
        if (shutdownZAP && (zapClientAPI != null)) {
            try {
                getLog().info("Shutdown ZAProxy");
                zapClientAPI.core.shutdown(apiKEY);
            } catch (Exception e) {
                getLog().error(e.toString());
                e.printStackTrace();
            }
        } else {
            getLog().info("No shutdown of ZAP");
        }
    }
}

From source file:com.yahoo.sql4d.sql4ddriver.DDataSource.java

/**
 * For firing simple queries(i.e non join queries).
 * @param jsonQuery/*from  w  ww  .j a  v a  2s  .c  om*/
 * @param print
 * @return 
 */
private Either<String, Either<Mapper4All, JSONArray>> fireQuery(String jsonQuery, boolean requiresMapping) {
    StringBuilder buff = new StringBuilder();
    try {
        URL url = null;
        try {
            url = new URL(String.format(brokerUrl, brokerHost, brokerPort));
        } catch (MalformedURLException ex) {
            Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
            return new Left<>("Bad Url : " + ex);
        }
        Proxy proxy = Proxy.NO_PROXY;
        if (proxyHost != null) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        }
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy);
        httpConnection.setRequestMethod("POST");
        httpConnection.addRequestProperty("content-type", "application/json");
        httpConnection.setDoOutput(true);
        httpConnection.getOutputStream().write(jsonQuery.getBytes());
        if (httpConnection.getResponseCode() == 500 || httpConnection.getResponseCode() == 404) {
            return new Left<>(String.format("Http %d : %s \n", httpConnection.getResponseCode(),
                    httpConnection.getResponseMessage()));
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String line = null;
        while ((line = stdInput.readLine()) != null) {
            buff.append(line);
        }
    } catch (IOException ex) {
        Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
    }
    JSONArray possibleResArray = null;
    try {
        possibleResArray = new JSONArray(buff.toString());
    } catch (JSONException je) {
        return new Left<>(String.format("Recieved data %s not in json format. \n", buff.toString()));
    }
    if (requiresMapping) {
        return new Right<String, Either<Mapper4All, JSONArray>>(
                new Left<Mapper4All, JSONArray>(new Mapper4All(possibleResArray)));
    }
    return new Right<String, Either<Mapper4All, JSONArray>>(new Right<Mapper4All, JSONArray>(possibleResArray));
}

From source file:org.cryptable.zap.mavenplugin.ProcessMojo.java

/**
 *
 * Execute the whole shabang//from   ww  w  . ja va 2  s.  c o m
 * @throws MojoExecutionException Throws exception when ZAProxy fails
 */
public void execute() throws MojoExecutionException {
    System.setProperty("java.net.debug", "all");

    try {

        zapClientAPI = new ClientApi(zapProxyHost, zapProxyPort);
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(zapProxyHost, zapProxyPort));

        if (spiderURL) {
            getLog().info("Spider the site [" + targetURL + "]");
            spiderURL(targetURL);
        } else {
            getLog().info("skip spidering the site [" + targetURL + "]");
        }

        if (scanURL) {
            getLog().info("Scan the site [" + targetURL + "]");
            scanURL(targetURL);
        } else {
            getLog().info("skip scanning the site [" + targetURL + "]");
        }

        // filename to share between the session file and the report file
        String fileName = "";
        if (saveSession) {

            fileName = createTempFilename("ZAP", "");

            zapClientAPI.core.saveSession(fileName, "true", "");
        } else {
            getLog().info("skip saveSession");
        }

        if (reportAlerts) {

            // reuse fileName of the session file
            if ((reportsFilenameNoExtension == null) || reportsFilenameNoExtension.isEmpty()) {
                if ((fileName == null) || (fileName.length() == 0)) {
                    fileName = createTempFilename("ZAP", "");
                }
            } else {
                fileName = reportsFilenameNoExtension;
            }

            String fileName_no_extension = FilenameUtils.concat(reportsDirectory, fileName);

            try {
                String alerts = getAllAlerts(getAllAlertsFormat(format));
                String fullFileName = fileName_no_extension + "." + getAllAlertsFormat(format);
                FileUtils.writeStringToFile(new File(fullFileName),
                        (jsonp ? "var zaproxy_jsonpData = " : "") + alerts);
                getLog().info("File save in format in [" + getAllAlertsFormat(format) + "]");
                if (format.equals("json")) {
                    Utils.copyResourcesRecursively(getClass().getResource("/zap-reports/"),
                            new File(reportsDirectory));
                }
            } catch (Exception e) {
                getLog().error(e.toString());
                e.printStackTrace();
            }
        }

        if ((propertyFile != null) && !propertyFile.isEmpty()) {
            restoreProperties();
        }

    } catch (Exception e) {
        getLog().error(e.toString());
        throw new MojoExecutionException("Processing with ZAP failed");
    } finally {
        if (shutdownZAP && (zapClientAPI != null)) {
            try {
                getLog().info("Shutdown ZAProxy");
                zapClientAPI.core.shutdown(apiKEY);
            } catch (Exception e) {
                getLog().error(e.toString());
                e.printStackTrace();
            }
        } else {
            getLog().info("No shutdown of ZAP");
        }
    }
}

From source file:org.fuin.esmp.AbstractEventStoreMojo.java

private void addProxySelector(final String proxyHost, final int proxyPort, final String proxyUser,
        final String proxyPassword, final URL downloadUrl) throws URISyntaxException {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override/*from  www.ja va2 s  .  c o m*/
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }
    final ProxySelector defaultProxySelector = ProxySelector.getDefault();

    final URI downloadUri = downloadUrl.toURI();

    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals(downloadUri.getHost()) && proxyHost != null && proxyHost.length() != 0) {
                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.apache.maven.wagon.providers.http.LightweightHttpWagon.java

private Proxy getProxy(ProxyInfo proxyInfo) {
    return new Proxy(getProxyType(proxyInfo), getSocketAddress(proxyInfo));
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailConnection.java

public void setProxy(final String host, final int port) {
    setProxy(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
}

From source file:org.apdplat.superword.tools.ProxyIp.java

/**
 * ??IP?????IP// ww  w. j  a va 2 s .c o m
 * @param host
 * @param port
 * @return
 */
public static boolean verify(String host, int port) {
    try {
        String url = "http://apdplat.org";
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setUseCaches(false);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder html = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            html.append(line);
        }
        LOGGER.info("HTML" + html);
        if (html.toString().contains("APDPlat???")) {
            LOGGER.info("?IP??" + host + ":" + port);
            return true;
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    LOGGER.info("?IP?" + host + ":" + port);
    return false;
}