Example usage for java.net Proxy NO_PROXY

List of usage examples for java.net Proxy NO_PROXY

Introduction

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

Prototype

Proxy NO_PROXY

To view the source code for java.net Proxy NO_PROXY.

Click Source Link

Document

A proxy setting that represents a DIRECT connection, basically telling the protocol handler not to use any proxying.

Usage

From source file:org.jmxtrans.embedded.config.EtcdKVStore.java

private String httpGET(URL base, String key) {

    InputStream is = null;/*  w  ww  .  ja v  a  2  s  .co  m*/
    HttpURLConnection conn = null;
    String json = null;
    try {
        URL url = new URL(base + "/v2/keys/" + key);
        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();
        int respCode = conn.getResponseCode();

        if (respCode == 404) {
            return null;
        } else if (respCode > 400) {
            return HTTP_ERR;
        }

        is = conn.getInputStream();
        String contentEncoding = conn.getContentEncoding() != null ? conn.getContentEncoding() : "UTF-8";
        json = IOUtils.toString(is, contentEncoding);
    } catch (MalformedURLException e) {
        json = HTTP_ERR;
        // nothing to do, try next server
    } catch (ProtocolException e) {
        // nothing to do, try next server
        json = HTTP_ERR;
    } catch (IOException e) {
        // nothing to do, try next server
        json = HTTP_ERR;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // nothing to do, try next server
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return json;
}

From source file:org.eclipsetrader.archipelago.Level2Feed.java

@Override
public void run() {
    String HOST = "datasvr.tradearca.com";
    Set<String> sTit = new HashSet<String>();

    for (int i = 0; i < 5 && !stopping; i++) {
        try {//from  ww w.j  a v  a 2  s . com
            Proxy socksProxy = Proxy.NO_PROXY;
            if (ArchipelagoPlugin.getDefault() != null) {
                BundleContext context = ArchipelagoPlugin.getDefault().getBundle().getBundleContext();
                ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
                if (reference != null) {
                    IProxyService proxy = (IProxyService) context.getService(reference);
                    IProxyData data = proxy.getProxyDataForHost(HOST, IProxyData.SOCKS_PROXY_TYPE);
                    if (data != null) {
                        if (data.getHost() != null) {
                            socksProxy = new Proxy(Proxy.Type.SOCKS,
                                    new InetSocketAddress(data.getHost(), data.getPort()));
                        }
                    }
                    context.ungetService(reference);
                }
            }
            socket = new Socket(socksProxy);
            socket.connect(new InetSocketAddress(HOST, 80));
            os = new BufferedOutputStream(socket.getOutputStream());
            is = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            os.write("GET http://datasvr.tradearca.com/zrepeaterz/ HTTP/1.1\r\n\r\n".getBytes());
            os.write("LogonRequest=DISABLED\r\n".getBytes());
            os.flush();
            break;
        } catch (Exception e) {
            Status status = new Status(IStatus.ERROR, ArchipelagoPlugin.PLUGIN_ID, 0,
                    "Error connecting to server", e);
            ArchipelagoPlugin.log(status);

            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e1) {
            }
            socket = null;
            is = null;
            os = null;
        }
    }
    if (socket == null || os == null || is == null) {
        thread = null;
        return;
    }

    while (!stopping) {
        try {
            if (subscriptionsChanged) {
                Set<String> toAdd = new HashSet<String>();
                Set<String> toRemove = new HashSet<String>();

                synchronized (symbolSubscriptions) {
                    for (String s : symbolSubscriptions.keySet()) {
                        if (!sTit.contains(s)) {
                            toAdd.add(s);
                        }
                    }
                    for (String s : sTit) {
                        if (!symbolSubscriptions.containsKey(s)) {
                            toRemove.add(s);
                        }
                    }
                    subscriptionsChanged = false;
                }

                if (toRemove.size() != 0) {
                    for (String s : toRemove) {
                        os.write("MsgType=UnregisterBook&Symbol=".getBytes());
                        os.write(s.getBytes());
                        os.write("\r\n".getBytes());
                    }
                    logger.info("Removing " + toRemove);
                    os.flush();
                }

                if (toAdd.size() != 0) {
                    for (String s : toAdd) {
                        os.write("MsgType=RegisterBook&Symbol=".getBytes());
                        os.write(s.getBytes());
                        os.write("\r\n".getBytes());
                    }
                    logger.info("Adding " + toAdd);
                    os.flush();
                }

                sTit.removeAll(toRemove);
                sTit.addAll(toAdd);
            }

            if (!is.ready()) {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
                continue;
            }

            String inputLine = is.readLine();
            if (inputLine.startsWith("BK&")) {
                String[] sections = inputLine.split("&");
                if (sections.length < 4) {
                    continue;
                }

                String symbol = sections[1];

                int index = 0, item = 0;
                String[] elements = sections[2].split("#");

                List<BookEntry> bid = new ArrayList<BookEntry>();
                while (index < elements.length) {
                    Double price = new Double(elements[index++]);
                    Long quantity = new Long(elements[index++]);
                    index++; // Time
                    String id = elements[index++];
                    bid.add(new BookEntry(null, price, quantity, 1L, id));
                    item++;
                }

                index = 0;
                item = 0;
                elements = sections[3].split("#");
                List<BookEntry> ask = new ArrayList<BookEntry>();
                while (index < elements.length) {
                    Double price = new Double(elements[index++]);
                    Long quantity = new Long(elements[index++]);
                    index++; // Time
                    String id = elements[index++];
                    ask.add(new BookEntry(null, price, quantity, 1L, id));
                    item++;
                }

                FeedSubscription subscription = symbolSubscriptions.get(symbol);
                if (subscription != null) {
                    IBook oldValue = subscription.getBook();
                    IBook newValue = new org.eclipsetrader.core.feed.Book(
                            bid.toArray(new IBookEntry[bid.size()]), ask.toArray(new IBookEntry[ask.size()]));
                    subscription.setBook(newValue);
                    subscription.addDelta(new QuoteDelta(subscription.getIdentifier(), oldValue, newValue));
                    subscription.fireNotification();
                }
            }
        } catch (SocketException e) {
            for (int i = 0; i < 5 && !stopping; i++) {
                try {
                    socket = new Socket("datasvr.tradearca.com", 80);
                    is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    os = new BufferedOutputStream(socket.getOutputStream());

                    os.write("GET http://datasvr.tradearca.com/zrepeaterz/ HTTP/1.1\r\n\r\n".getBytes());
                    os.write("LogonRequest=DISABLED\r\n".getBytes());
                    os.flush();

                    for (String s : sTit) {
                        os.write("MsgType=RegisterBook&Symbol=".getBytes());
                        os.write(s.getBytes());
                        os.write("\r\n".getBytes());
                    }
                    os.flush();
                    break;
                } catch (Exception e1) {
                    Status status = new Status(IStatus.ERROR, ArchipelagoPlugin.PLUGIN_ID, 0,
                            "Error connecting to server", e);
                    ArchipelagoPlugin.log(status);
                }
            }
            if (socket == null || os == null || is == null) {
                thread = null;
                return;
            }
        } catch (Exception e) {
            Status status = new Status(IStatus.ERROR, ArchipelagoPlugin.PLUGIN_ID, 0, "Error receiving stream",
                    e);
            ArchipelagoPlugin.log(status);
            break;
        }
    }

    try {
        if (socket != null) {
            socket.close();
        }
        socket = null;
        os = null;
        is = null;
    } catch (Exception e) {
        // Do nothing
    }

    thread = null;
}

From source file:org.eclipse.mylyn.commons.net.WebUtil.java

private static void configureHttpClientProxy(HttpClient client, HostConfiguration hostConfiguration,
        AbstractWebLocation location) {//  w w w.j  a v a 2  s.  c o m
    String host = WebUtil.getHost(location.getUrl());

    Proxy proxy;
    if (WebUtil.isRepositoryHttps(location.getUrl())) {
        proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE);
    } else {
        proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE);
    }

    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        hostConfiguration.setProxy(address.getHostName(), address.getPort());
        if (proxy instanceof AuthenticatedProxy) {
            AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy;
            Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(),
                    address.getAddress());
            AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(),
                    AuthScope.ANY_REALM);
            client.getState().setProxyCredentials(proxyAuthScope, credentials);
        }
    } else {
        hostConfiguration.setProxyHost(null);
    }
}

From source file:URLTree.FindOptimalPath.java

public void printMap(List<Node> node, int stage, String outputFile, int threshold, String ouptputFrequencyFile,
        String filed3) {//from w  w  w .ja  va2s  . c  om

    Map<String, Integer> countSimilarNode = new HashMap<String, Integer>();
    String nodeMatrix[][] = new String[node.size()][stage];
    for (int i = 0; i < node.size(); i++) {

        //System.out.println(Arrays.toString(node.get(i).getNodeArr()));
        String arr[] = node.get(i).getNodeArr();

        for (int j = 0; j < arr.length; j++) {
            if (j < stage) {
                nodeMatrix[i][j] = arr[j];
            }
        }

    }
    List<MergeSimilarNode> similarNode = new ArrayList<MergeSimilarNode>();
    Map<String, Integer> wordMap = new HashMap<String, Integer>();

    for (int i = 0; i < node.size(); i++) {
        for (int j = 0; j < stage; j++) {
            if (nodeMatrix[i][j] != null) {

                FreqWords nodeFreq = new FreqWords();
                System.out.print("[" + i + j + "]: " + nodeMatrix[i][j]);
                if (wordMap.containsKey(nodeMatrix[i][j] + "," + j)) {
                    wordMap.put(nodeMatrix[i][j] + "," + j, wordMap.get(nodeMatrix[i][j] + "," + j) + 1);
                } else {

                    wordMap.put(nodeMatrix[i][j] + "," + j, 1);
                }

            }
        }
        System.out.println();
    }
    List<FreqWords> freq = new ArrayList<FreqWords>();
    for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {

        FreqWords fwords = new FreqWords();
        String key = entry.getKey();
        Integer value = entry.getValue();
        //String nodeStr[]=key.split(",");
        String[] nodeStr = new String[2];
        StringTokenizer st = new StringTokenizer(key, ",");
        int k = 0;
        while (st.hasMoreTokens()) {
            nodeStr[k] = st.nextToken();
            k++;
        }
        fwords.setNode(nodeStr[0]);
        System.out.println("node freq: " + nodeStr[1]);
        if (nodeStr[1] != null) {
            fwords.setFreq(Integer.parseInt(nodeStr[1]));
        } else {
            System.out.println("null value at" + nodeStr[0] + ": " + nodeStr[1]);
        }

        fwords.setValue(value);
        freq.add(fwords);

    }
    System.out.println("Done Matrix");
    //System.out.println();
    PrintWriter writer = null;
    List<String> urlList = new ArrayList<String>();
    List<FilterURL> varifiedList = new ArrayList<FilterURL>();
    try {

        writer = new PrintWriter(outputFile, "UTF-8");

        for (int i = 0; i < node.size(); i++) {
            String urlArr[] = new String[stage];

            int flag = 0;
            int sum = 0;
            for (int j = 0; j < stage; j++) {
                if (nodeMatrix[i][j] != null) {
                    for (FreqWords words : freq) {
                        //System.out.println();
                        //if(words.getNode().equals("ca"))
                        // System.out.println("words: "+words.getNode()+" i: "+i+"j: "+j+"  value: "+nodeMatrix[i][j]+" word Freq: "+ words.getFreq());
                        if (words.getNode().equals(nodeMatrix[i][j])) {
                            //if(words.getFreq()!=0)
                            //{
                            if (words.getFreq() == j) {
                                int count = node.get(i).getCount();
                                //url=url.append(nodeMatrix[i][j]).append("(").append(value+node.get(i).getCount()).append(")-");

                                if (threshold > words.getValue()) {

                                    flag = 1;
                                    break;
                                } else {
                                    sum += count;
                                    urlArr[j] = nodeMatrix[i][j];
                                    // System.out.println("i: "+i+"j: "+j+" found: "+urlArr[j]);

                                    break;

                                    //System.out.print(nodeMatrix[i][j]+"("+value+")");
                                }
                            }
                            //}

                        }

                    }

                }
                if (flag == 1) {
                    flag = 0;
                    break;
                }

            }

            //String urldata=StringUtils.join(urlArr,"-");                
            String urldata = Joiner.on("-").skipNulls().join(urlArr).trim();
            //System.out.println("Mearge URL"+urldata);

            if (urldata.endsWith("-")) {
                urldata = urldata.substring(0, urldata.length() - 1);
            }
            urldata = StringUtils.stripEnd(urldata, null);
            // System.out.print(urldata);
            if (!urldata.isEmpty()) {
                if (urldata.contains("-")) {
                    // writer.println(urldata+","+sum);

                    FilterURL filter = new FilterURL();
                    filter.setReversedURL(urldata);
                    filter.setCount(sum);
                    varifiedList.add(filter);
                }
            }

            //System.out.println(i);
            // System.out.println(i);

        }
        //varifiedSequece(varifiedList,writer);
        for (int i = 0; i < varifiedList.size() - 1; i++) {
            if (varifiedList.get(i).getReversedURL().contains(varifiedList.get(i + 1).getReversedURL())) {

            } else {
                if (threshold != 0) {
                    String nodesName[] = varifiedList.get(i).getReversedURL().split("-");
                    if (nodesName.length == 2) {
                        try {
                            String url2Domain = "http://" + nodesName[1] + "." + nodesName[0];
                            URL url = new URL(url2Domain);
                            // open connection
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                                    .openConnection(Proxy.NO_PROXY);

                            // stop following browser redirect
                            httpURLConnection.setInstanceFollowRedirects(false);
                            httpURLConnection.setConnectTimeout(15000);
                            httpURLConnection.setReadTimeout(15000);
                            // extract location header containing the actual destination URL
                            String expandedURL = httpURLConnection.getHeaderField("Location");
                            httpURLConnection.disconnect();
                            if (expandedURL != null) {
                                System.out.println("Correct: " + expandedURL);
                                writer.println(varifiedList.get(i).getReversedURL() + ","
                                        + varifiedList.get(i).getCount());
                            }

                        } catch (Exception e) {
                            System.out.println("Incorrect: " + e);
                        }
                    } else {
                        writer.println(
                                varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount());
                    }
                } else {
                    writer.println(varifiedList.get(i).getReversedURL() + "," + varifiedList.get(i).getCount());
                }

            }

        }

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);
    } finally {
        if (writer != null) {
            writer.close(); // **** closing it flushes it and reclaims resources ****
        }
    }
    System.out.println("Write into File->" + outputFile);

    Path obj = new Path();
    obj.finalFrequency(outputFile, ouptputFrequencyFile);
    // obj.preSunbrust(ouptputFrequencyFile,filed3);

}

From source file:com.vuze.plugin.azVPN_Helper.Checker_AirVPN.java

@Override
protected boolean callRPCforPort(InetAddress bindIP, StringBuilder sReply) {
    InetAddress[] resolve = null;
    try {//from  w  ww. j ava2 s  .co  m

        String user = getDefaultUsername();
        String pass = null;
        if (user == null || user.length() == 0) {
            user = config.getPluginStringParameter(PluginConstants.CONFIG_USER);
            pass = new String(config.getPluginByteParameter(PluginConstants.CONFIG_P, new byte[0]), "utf-8");
        } else {
            pass = getPassword();
        }

        if (user == null || user.length() == 0 || pass == null || pass.length() == 0) {
            addReply(sReply, CHAR_WARN, "airvpn.rpc.nocreds");
            return false;
        }

        // If Vuze has a proxy set up (Tools->Options->Connection->Proxy), then
        // we'll need to disable it for the URL
        AEProxySelector selector = AEProxySelectorFactory.getSelector();
        if (selector != null) {
            resolve = SystemDefaultDnsResolver.INSTANCE.resolve(VPN_DOMAIN);

            for (InetAddress address : resolve) {
                selector.setProxy(new InetSocketAddress(address, 443), Proxy.NO_PROXY);
            }
        }

        RequestConfig requestConfig;
        StringBuffer token = new StringBuffer();

        boolean skipLoginPage = false;
        boolean alreadyLoggedIn = false;
        PortInfo[] ports = null;

        if (httpClientContext == null) {
            httpClientContext = HttpClientContext.create();
        } else {
            PluginVPNHelper.log("Have existing context.  Trying to grab port list without logging in.");
            ports = scrapePorts(bindIP, token);
            // assume no token means we aren't logged in
            if (token.length() > 0) {
                PluginVPNHelper.log("Valid ports page. Skipping Login");
                skipLoginPage = true;
                alreadyLoggedIn = true;

                if (ports == null) {
                    addReply(sReply, CHAR_WARN, "airvpn.vpnhelper.rpc.notconnected");
                    return false;
                }
            } else {
                ports = null;
            }
        }

        if (!skipLoginPage) {
            String loginURL = null;
            String authKey = null;

            PluginVPNHelper.log("Getting Login post URL and auth_key");

            HttpGet getLoginPage = new HttpGet(VPN_LOGIN_URL);
            requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(15000).build();
            getLoginPage.setConfig(requestConfig);
            getLoginPage.setHeader("User-Agent", USER_AGENT);

            CloseableHttpClient httpClientLoginPage = HttpClients.createDefault();
            CloseableHttpResponse loginPageResponse = httpClientLoginPage.execute(getLoginPage,
                    httpClientContext);

            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(loginPageResponse.getEntity().getContent()));

            Pattern patAuthKey = Pattern.compile(REGEX_AuthKey);

            String line = "";
            while ((line = rd.readLine()) != null) {
                if (line.contains("<form") && line.matches(".*id=['\"]login['\"].*")) {
                    Matcher matcher = Pattern.compile(REGEX_ActionURL).matcher(line);
                    if (matcher.find()) {
                        loginURL = matcher.group(1);
                        if (authKey != null) {
                            break;
                        }
                    }
                }
                Matcher matcherAuthKey = patAuthKey.matcher(line);
                if (matcherAuthKey.find()) {
                    authKey = matcherAuthKey.group(1);
                    if (loginURL != null) {
                        break;
                    }
                }

                if (line.contains("['member_id']") && line.matches(".*parseInt\\s*\\(\\s*[1-9][0-9]*\\s*.*")) {
                    alreadyLoggedIn = true;
                }
            }
            rd.close();

            if (loginURL == null) {
                PluginVPNHelper.log("Could not scrape Login URL.  Using default");
                loginURL = "https://airvpn.org/index.php?app=core&module=global&section=login&do=process";
            }
            if (authKey == null) {
                addReply(sReply, CHAR_WARN, "vpnhelper.rpc.noauthkey");
                return false;
            }

            loginURL = UrlUtils.unescapeXML(loginURL);

            ///////////////////////////////

            if (alreadyLoggedIn) {
                PluginVPNHelper.log("Already Logged In");
            } else {
                PluginVPNHelper.log("Login URL:" + loginURL);
                //https://airvpn.org/index.php?app=core&module=global&section=login&do=process
                //https://airvpn.org/index.php?app=core&module=global&section=login&do=process

                HttpPost httpPostLogin = new HttpPost(loginURL);

                requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(15000).build();

                httpPostLogin.setConfig(requestConfig);
                httpPostLogin.setHeader("User-Agent", USER_AGENT);

                CloseableHttpClient httpClient = HttpClients.createDefault();

                List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                urlParameters.add(new BasicNameValuePair("ips_username", user));
                urlParameters.add(new BasicNameValuePair("ips_password", pass));
                urlParameters.add(new BasicNameValuePair("auth_key", authKey));
                urlParameters.add(new BasicNameValuePair("referer", "http://airvpn.org/"));
                urlParameters.add(new BasicNameValuePair("anonymous", "1"));
                urlParameters.add(new BasicNameValuePair("rememberMe", "1"));

                httpPostLogin.setEntity(new UrlEncodedFormEntity(urlParameters));

                CloseableHttpResponse response = httpClient.execute(httpPostLogin, httpClientContext);

                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                line = "";
                while ((line = rd.readLine()) != null) {
                }

                PluginVPNHelper.log("Login Result: " + response.getStatusLine().toString());
            }
        }

        ////////////////////////////

        if (ports == null) {
            ports = scrapePorts(bindIP, token);
            if (ports == null && token.length() > 0) {
                addReply(sReply, CHAR_WARN, "airvpn.vpnhelper.rpc.notconnected");
                return false;
            }
        }

        PluginVPNHelper.log("Found Ports: " + Arrays.toString(ports));

        int existingIndex = ourPortInList(ports);
        if (existingIndex >= 0) {
            addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc.match",
                    new String[] { ports[existingIndex].port });
            return true;
        }

        boolean gotPort = false;

        // There's a limit of 20 ports.  If [0] isn't ours and 20 of them are
        // created, then assume our detection of "ours" is broke and just use
        // the first one
        if (ports != null && ((ports.length > 0 && ports[0].ourBinding) || ports.length == 20)) {
            int port = Integer.parseInt(ports[0].port);
            gotPort = true;

            addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc", new String[] { Integer.toString(port) });

            changePort(port, sReply);
        } else if (ports != null) {
            // create port
            ports = createPort(bindIP, token);
            if (ports.length == 0) {
                // form post should have got the new port, but if it didn't, try
                // reloading the ports page again.
                token.setLength(0);
                ports = scrapePorts(bindIP, token);
            }

            PluginVPNHelper.log("Added a port. Ports: " + Arrays.toString(ports));

            existingIndex = ourPortInList(ports);
            if (existingIndex >= 0) {
                addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc.match",
                        new String[] { ports[existingIndex].port });
                return true;
            }

            if ((ports.length > 0 && ports[0].ourBinding) || ports.length == 20) {
                int port = Integer.parseInt(ports[0].port);
                gotPort = true;

                addReply(sReply, CHAR_GOOD, "vpnhelper.port.from.rpc", new String[] { Integer.toString(port) });

                changePort(port, sReply);
            }

        }

        if (!gotPort) {
            addReply(sReply, CHAR_WARN, "vpnhelper.rpc.no.connect", new String[] { bindIP.toString() });

            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "vpnhelper.rpc.no.connect", new String[] { bindIP + ": " + e.getMessage() });

        return false;
    } finally {
        AEProxySelector selector = AEProxySelectorFactory.getSelector();
        if (selector != null && resolve != null) {
            for (InetAddress address : resolve) {
                AEProxySelectorFactory.getSelector().removeProxy(new InetSocketAddress(address, 443));
            }
        }
    }
    return true;
}

From source file:com.vuze.plugin.azVPN_Helper.Checker_PIA.java

private boolean callRPCforPort(File pathPIAManagerData, InetAddress bindIP, StringBuilder sReply) {
    InetAddress[] resolve = null;
    try {//from w w w  .  ja  va 2 s. c  o  m
        // Let's assume the client_id.txt file is the one for port forwarding.
        File fileClientID = new File(pathPIAManagerData, "client_id.txt");
        String clientID;
        if (fileClientID.isFile() && fileClientID.canRead()) {
            clientID = FileUtil.readFileAsString(fileClientID, -1);
        } else {
            clientID = config.getPluginStringParameter("client.id", null);
            if (clientID == null) {
                clientID = RandomUtils.generateRandomAlphanumerics(20);
                config.setPluginParameter("client.id", clientID);
            }
        }

        HttpPost post = new HttpPost(PIA_RPC_URL);

        String user = config.getPluginStringParameter(PluginConstants.CONFIG_USER);
        String pass = new String(config.getPluginByteParameter(PluginConstants.CONFIG_P, new byte[0]), "utf-8");

        if (user == null || user.length() == 0 || pass == null || pass.length() == 0) {
            return false;
        }

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("user", user));
        urlParameters.add(new BasicNameValuePair("pass", pass));
        urlParameters.add(new BasicNameValuePair("client_id", clientID));
        urlParameters.add(new BasicNameValuePair("local_ip", bindIP.getHostAddress()));

        // Call needs to be from the VPN interface (the bindIP)
        RequestConfig requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(15000)
                .build();

        post.setConfig(requestConfig);

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        CloseableHttpClient httpClient = HttpClients.createDefault();

        // If Vuze has a proxy set up (Tools->Options->Connection->Proxy), then
        // we'll need to disable it for the URL
        AEProxySelector selector = AEProxySelectorFactory.getSelector();
        if (selector != null) {
            resolve = SystemDefaultDnsResolver.INSTANCE.resolve(VPN_DOMAIN);

            for (InetAddress address : resolve) {
                selector.setProxy(new InetSocketAddress(address, 443), Proxy.NO_PROXY);
            }
        }

        CloseableHttpResponse response = httpClient.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        boolean gotPort = false;
        // should be {"port":xyz}

        Map<?, ?> mapResult = JSONUtils.decodeJSON(result.toString());
        if (mapResult.containsKey("port")) {
            Object oPort = mapResult.get("port");
            if (oPort instanceof Number) {
                gotPort = true;
                Number nPort = (Number) oPort;
                int port = nPort.intValue();

                addReply(sReply, CHAR_GOOD, "pia.port.from.rpc", new String[] { Integer.toString(port) });

                changePort(port, sReply);
            }
        }

        if (!gotPort) {
            addReply(sReply, CHAR_WARN, "vpnhelper.rpc.bad", new String[] { result.toString() });

            // mapResult.containsKey("error")
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "vpnhelper.rpc.no.connect", new String[] { bindIP + ": " + e.getMessage() });

        return false;
    } finally {
        AEProxySelector selector = AEProxySelectorFactory.getSelector();
        if (selector != null && resolve != null) {
            for (InetAddress address : resolve) {
                AEProxySelectorFactory.getSelector().removeProxy(new InetSocketAddress(address, 443));
            }
        }
    }
    return true;
}

From source file:forge.download.GuiDownloadService.java

protected Proxy getProxy() {
    if (type == 0) {
        return Proxy.NO_PROXY;
    } else {//  ww  w.ja va  2  s .  c o 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.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java

public static void configureProxy(AbstractHttpClient client, RepositoryLocation location) {
    Assert.isNotNull(client);/*from w  ww.  j  av  a 2  s.c  om*/
    Assert.isNotNull(location);
    String url = location.getUrl();
    Assert.isNotNull(url, "The location url must not be null"); //$NON-NLS-1$

    String host = NetUtil.getHost(url);
    Proxy proxy;
    if (NetUtil.isUrlHttps(url)) {
        proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE);
    } else {
        proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE);
    }

    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();

        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(address.getHostName(), address.getPort()));

        if (proxy instanceof AuthenticatedProxy) {
            AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy;
            Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(),
                    address.getAddress(), false);
            if (credentials instanceof NTCredentials) {
                AuthScope proxyAuthScopeNTLM = new AuthScope(address.getHostName(), address.getPort(),
                        AuthScope.ANY_REALM, AuthPolicy.NTLM);
                client.getCredentialsProvider().setCredentials(proxyAuthScopeNTLM, credentials);

                AuthScope proxyAuthScopeAny = new AuthScope(address.getHostName(), address.getPort(),
                        AuthScope.ANY_REALM);
                Credentials usernamePasswordCredentials = getCredentials(authProxy.getUserName(),
                        authProxy.getPassword(), address.getAddress(), true);
                client.getCredentialsProvider().setCredentials(proxyAuthScopeAny, usernamePasswordCredentials);

            } else {
                AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(),
                        AuthScope.ANY_REALM);
                client.getCredentialsProvider().setCredentials(proxyAuthScope, credentials);
            }
        }
    } else {
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
    }
}

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

/**
 * For firing simple queries(i.e non join queries).
 * @param jsonQuery/*from   ww  w.jav a 2s . co  m*/
 * @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.sonar.api.utils.HttpDownloaderTest.java

@Test
public void shouldGetDirectProxySynthesis() throws URISyntaxException {
    ProxySelector proxySelector = mock(ProxySelector.class);
    when(proxySelector.select((URI) anyObject())).thenReturn(Arrays.asList(Proxy.NO_PROXY));
    assertThat(HttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector), is("no proxy"));
}