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.mapfish.print.config.Config.java

/**
 * Get or create the http client to be used to fetch all the map data.
 *//*from  w w  w.java  2  s  .  c  o  m*/
public HttpClient getHttpClient(URI uri) {
    MultiThreadedHttpConnectionManager connectionManager = getConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);

    // httpclient is a bit pesky about loading everything in memory...
    // disabling the warnings.
    Logger.getLogger(HttpMethodBase.class).setLevel(Level.ERROR);

    // configure proxies for URI
    ProxySelector selector = ProxySelector.getDefault();

    List<Proxy> proxyList = selector.select(uri);
    Proxy proxy = proxyList.get(0);

    if (!proxy.equals(Proxy.NO_PROXY)) {
        InetSocketAddress socketAddress = (InetSocketAddress) proxy.address();
        String hostName = socketAddress.getHostName();
        int port = socketAddress.getPort();

        httpClient.getHostConfiguration().setProxy(hostName, port);
    }

    for (SecurityStrategy sec : security)
        if (sec.matches(uri)) {
            sec.configure(uri, httpClient);
            break;
        }
    return httpClient;
}

From source file:URLTree.FindOptimalPath.java

public void varifiedSequece(List<FilterURL> varifiedList, PrintWriter writer) {
    for (int i = 0; i < varifiedList.size() - 1; i++) {
        if (varifiedList.get(i).getReversedURL().contains(varifiedList.get(i + 1).getReversedURL())) {

        } else {/*ww  w .  j a  v a 2 s .  c  om*/
            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());
            }

        }

    }
}

From source file:com.delicious.deliciousfeeds4J.DeliciousUtil.java

public static String expandShortenedUrl(String shortenedUrl, String userAgent) throws IOException {

    if (shortenedUrl == null || shortenedUrl.isEmpty())
        return shortenedUrl;

    if (userAgent == null || userAgent.isEmpty())
        throw new IllegalArgumentException("UserAgent must not be null or empty!");

    if (shortenedUrl.contains(URL_SHORTENED_SNIPPET) == false)
        return shortenedUrl;

    logger.debug("Trying to expand shortened url: " + shortenedUrl);

    final URL url = new URL(shortenedUrl);

    final HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

    try {/*www. j  a v  a 2  s  .  co  m*/
        connection.setInstanceFollowRedirects(false);
        connection.setRequestProperty("User-Agent", userAgent);
        connection.connect();
        final String expandedDeliciousUrl = connection.getHeaderField("Location");

        if (expandedDeliciousUrl.contains("url=")) {

            final Matcher matcher = URL_PARAMETER_PATTERN.matcher(expandedDeliciousUrl);

            if (matcher.find()) {
                final String expanded = matcher.group();

                logger.trace("Successfully expanded: " + shortenedUrl + " -> " + expandedDeliciousUrl + " -> "
                        + expanded);

                return expanded;
            }
        }
    } catch (Exception ex) {
        logger.debug("Error while trying to expand shortened url: " + shortenedUrl, ex);
    } finally {
        connection.getInputStream().close();
    }

    return shortenedUrl;
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

private ProxyHost getProxyHost() {
    ProxyHost theProxyHost = null;//  w  ww  .j av  a2  s  .c o  m
    ProxySelector ps = ProxySelector.getDefault();
    List<Proxy> p = null;
    // select the proxy for the URI of this repository
    try {
        if (ps != null) {
            // log.info( "Getting Proxy List." );
            p = ps.select(new java.net.URI(this.servletURL));
        }
    } catch (Exception e) {
        // log.warn( "Exception getting proxy: " + e.toString() );
    }
    if (p == null) {
        // log.warn( "No proxy information available." );
    } else {
        // log.info( "Received proxy list: " + p.toString() );
        Iterator<Proxy> proxies = p.iterator();
        // just take the first for now
        if (proxies != null && proxies.hasNext()) {
            Proxy theProxy = (Proxy) proxies.next();
            // log.info( "Proxy set to: " + theProxy.toString() );
            if (!Proxy.NO_PROXY.equals(theProxy)) {
                InetSocketAddress theSock = (InetSocketAddress) theProxy.address();
                theProxyHost = new ProxyHost(theSock.getHostName(), theSock.getPort());
            }
        } else {
            // log.warn( "Proxy list has zero members." );
        }
    }
    return theProxyHost;
}

From source file:org.c99.wear_imessage.RemoteInputService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_REPLY.equals(action)) {
            JSONObject conversations = null, conversation = null;
            try {
                conversations = new JSONObject(
                        getSharedPreferences("data", 0).getString("conversations", "{}"));
            } catch (JSONException e) {
                conversations = new JSONObject();
            }/*  ww w.j  a v  a  2s. co m*/

            try {
                String key = intent.getStringExtra("service") + ":" + intent.getStringExtra("handle");
                if (conversations.has(key)) {
                    conversation = conversations.getJSONObject(key);
                } else {
                    conversation = new JSONObject();
                    conversations.put(key, conversation);

                    long time = new Date().getTime();
                    String tmpStr = String.valueOf(time);
                    String last4Str = tmpStr.substring(tmpStr.length() - 5);
                    conversation.put("notification_id", Integer.valueOf(last4Str));
                    conversation.put("msgs", new JSONArray());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
            if (remoteInput != null || intent.hasExtra("reply")) {
                String reply = remoteInput != null ? remoteInput.getCharSequence("extra_reply").toString()
                        : intent.getStringExtra("reply");

                if (intent.hasExtra(Intent.EXTRA_STREAM)) {
                    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                            .setContentTitle("Uploading File").setProgress(0, 0, true).setLocalOnly(true)
                            .setOngoing(true).setSmallIcon(android.R.drawable.stat_sys_upload);
                    NotificationManagerCompat.from(this).notify(1337, notification.build());

                    InputStream fileIn = null;
                    InputStream responseIn = null;
                    HttpURLConnection http = null;
                    try {
                        String filename = "";
                        int total = 0;
                        String type = getContentResolver()
                                .getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
                        if (type == null || type.length() == 0)
                            type = "application/octet-stream";
                        fileIn = getContentResolver()
                                .openInputStream((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));

                        Cursor c = getContentResolver().query(
                                (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM),
                                new String[] { OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME }, null, null,
                                null);
                        if (c != null && c.moveToFirst()) {
                            total = c.getInt(0);
                            filename = c.getString(1);
                            c.close();
                        } else {
                            total = fileIn.available();
                        }

                        String boundary = UUID.randomUUID().toString();
                        http = (HttpURLConnection) new URL(
                                "http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/upload")
                                        .openConnection();
                        http.setReadTimeout(60000);
                        http.setConnectTimeout(60000);
                        http.setDoOutput(true);
                        http.setFixedLengthStreamingMode(total + (boundary.length() * 5) + filename.length()
                                + type.length() + intent.getStringExtra("handle").length()
                                + intent.getStringExtra("service").length() + reply.length() + 251);
                        http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                        OutputStream out = http.getOutputStream();
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"handle\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("handle") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"service\"\r\n\r\n").getBytes());
                        out.write((intent.getStringExtra("service") + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"msg\"\r\n\r\n").getBytes());
                        out.write((reply + "\r\n").getBytes());
                        out.write(("--" + boundary + "\r\n").getBytes());
                        out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename
                                + "\"\r\n").getBytes());
                        out.write(("Content-Type: " + type + "\r\n\r\n").getBytes());

                        byte[] buffer = new byte[8192];
                        int count = 0;
                        int n = 0;
                        while (-1 != (n = fileIn.read(buffer))) {
                            out.write(buffer, 0, n);
                            count += n;

                            float progress = (float) count / (float) total;
                            if (progress < 1.0f)
                                notification.setProgress(1000, (int) (progress * 1000), false);
                            else
                                notification.setProgress(0, 0, true);
                            NotificationManagerCompat.from(this).notify(1337, notification.build());
                        }

                        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
                        out.flush();
                        out.close();
                        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            responseIn = http.getInputStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.i("iMessage", "Upload result: " + sb.toString());
                            try {
                                if (conversation != null) {
                                    JSONArray msgs = conversation.getJSONArray("msgs");
                                    JSONObject m = new JSONObject();
                                    m.put("msg", filename);
                                    m.put("service", intent.getStringExtra("service"));
                                    m.put("handle", intent.getStringExtra("handle"));
                                    m.put("type", "sent_file");
                                    msgs.put(m);

                                    while (msgs.length() > 10) {
                                        msgs.remove(0);
                                    }

                                    GCMIntentService.notify(getApplicationContext(),
                                            intent.getIntExtra("notification_id", 0), msgs, intent, true);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            responseIn = http.getErrorStream();
                            StringBuilder sb = new StringBuilder();
                            Scanner scanner = new Scanner(responseIn).useDelimiter("\\A");
                            while (scanner.hasNext()) {
                                sb.append(scanner.next());
                            }
                            android.util.Log.e("iMessage", "Upload failed: " + sb.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (responseIn != null)
                                responseIn.close();
                        } catch (Exception ignore) {
                        }
                        try {
                            if (http != null)
                                http.disconnect();
                        } catch (Exception ignore) {
                        }
                        try {
                            fileIn.close();
                        } catch (Exception ignore) {
                        }
                    }
                    NotificationManagerCompat.from(this).cancel(1337);
                } else if (reply.length() > 0) {
                    URL url = null;
                    try {
                        url = new URL("http://" + getSharedPreferences("prefs", 0).getString("host", "")
                                + "/send?service=" + intent.getStringExtra("service") + "&handle="
                                + intent.getStringExtra("handle") + "&msg="
                                + URLEncoder.encode(reply, "UTF-8"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    HttpURLConnection conn;

                    try {
                        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.setUseCaches(false);

                    BufferedReader reader = null;

                    try {
                        if (conn.getInputStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
                        }
                    } catch (IOException e) {
                        if (conn.getErrorStream() != null) {
                            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
                        }
                    }

                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    conn.disconnect();
                    try {
                        if (conversation != null) {
                            JSONArray msgs = conversation.getJSONArray("msgs");
                            JSONObject m = new JSONObject();
                            m.put("msg", reply);
                            m.put("service", intent.getStringExtra("service"));
                            m.put("handle", intent.getStringExtra("handle"));
                            m.put("type", "sent");
                            msgs.put(m);

                            while (msgs.length() > 10) {
                                msgs.remove(0);
                            }

                            GCMIntentService.notify(getApplicationContext(),
                                    intent.getIntExtra("notification_id", 0), msgs, intent, true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                SharedPreferences.Editor e = getSharedPreferences("data", 0).edit();
                e.putString("conversations", conversations.toString());
                e.apply();
            }
        }
    }
}

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

/**
 * All commands.//from w w w . ja  v a  2s  . co  m
 * @return 
 */
private Either<String, Either<JSONArray, JSONObject>> fireCommand(String endPoint, String optData,
        String httpType) {
    StringBuilder buff = new StringBuilder();
    try {
        URL url = null;
        try {
            url = new URL(String.format(coordinatorUrl + endPoint, coordinatorHost, coordinatorPort));
        } 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(httpType);
        httpConnection.addRequestProperty("content-type", "application/json");
        httpConnection.setDoOutput(true);
        if ("POST".equals(httpType) && optData != null) {
            httpConnection.getOutputStream().write(optData.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());
        return new Right<String, Either<JSONArray, JSONObject>>(
                new Left<JSONArray, JSONObject>(possibleResArray));
    } catch (JSONException je) {
        try {
            JSONObject possibleResObj = new JSONObject(buff.toString());
            return new Right<String, Either<JSONArray, JSONObject>>(
                    new Right<JSONArray, JSONObject>(possibleResObj));
        } catch (JSONException je2) {
            return new Left<>(String.format("Recieved data %s not in json format. \n", buff.toString()));
        }
    }
}

From source file:org.mozilla.gecko.updater.UpdateService.java

private URLConnection openConnectionWithProxy(URI uri)
        throws java.net.MalformedURLException, java.io.IOException {
    Log.i(LOGTAG, "opening connection with URI: " + uri);

    ProxySelector ps = ProxySelector.getDefault();
    Proxy proxy = Proxy.NO_PROXY;
    if (ps != null) {
        List<Proxy> proxies = ps.select(uri);
        if (proxies != null && !proxies.isEmpty()) {
            proxy = proxies.get(0);//from w w w .  j  ava  2s  . c  o m
        }
    }

    return uri.toURL().openConnection(proxy);
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private Map<String, String> performRequest(String action, ImmutablePair<String, String>... params) {
    byte[] outgoingData = createRequestXml(action, params);

    HttpURLConnection conn = null;

    try {/*w w  w.j a  v a 2 s .  c  o  m*/
        URL url = controlUrl.toURL();
        conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

        conn.setRequestMethod("POST");
        conn.setReadTimeout(3000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/xml");
        conn.setRequestProperty("SOAPAction", serviceType + "#" + action);
        conn.setRequestProperty("Connection", "Close");
    } catch (IOException ex) {
        throw new IllegalStateException(ex); // should never happen
    }

    try (OutputStream os = conn.getOutputStream()) {
        os.write(outgoingData);
    } catch (IOException ex) {
        IOUtils.close(conn);
        throw new ResponseException(ex);
    }

    byte[] incomingData;
    int respCode;
    try {
        respCode = conn.getResponseCode();
    } catch (IOException ioe) {
        IOUtils.close(conn);
        throw new ResponseException(ioe);
    }

    if (respCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
        try (InputStream is = conn.getErrorStream()) {
            incomingData = IOUtils.toByteArray(is);
        } catch (IOException ex) {
            IOUtils.close(conn);
            throw new ResponseException(ex);
        }
    } else {
        try (InputStream is = conn.getInputStream()) {
            incomingData = IOUtils.toByteArray(is);
        } catch (IOException ex) {
            IOUtils.close(conn);
            throw new ResponseException(ex);
        }
    }

    return parseResponseXml(action + "Response", incomingData);
}

From source file:hudson.plugins.ec2.EC2Cloud.java

/***
 * Connect to an EC2 instance.//w  ww .j a  v a2  s. com
 * @return {@link AmazonEC2} client
 */
public synchronized static AmazonEC2 connect(String accessId, Secret secretKey, URL endpoint) {
    awsCredentials = new BasicAWSCredentials(accessId, Secret.toString(secretKey));
    ClientConfiguration config = new ClientConfiguration();
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost());
    if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        config.setProxyHost(address.getHostName());
        config.setProxyPort(address.getPort());
        if (null != proxyConfig.getUserName()) {
            config.setProxyUsername(proxyConfig.getUserName());
            config.setProxyPassword(proxyConfig.getPassword());
        }
    }
    AmazonEC2 client = new AmazonEC2Client(awsCredentials, config);
    client.setEndpoint(endpoint.toString());
    return client;
}

From source file:com.vuze.plugin.azVPN_Air.Checker.java

private boolean callRPCforPort(InetAddress bindIP, StringBuilder sReply) {
    InetAddress[] resolve = null;
    try {//from ww w .j a va2 s . co  m

        String user = getDefaultUsername();
        String pass = null;
        if (user == null || user.length() == 0) {
            user = config.getPluginStringParameter(PluginAir.CONFIG_USER);
            pass = new String(config.getPluginByteParameter(PluginAir.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 {
            PluginAir.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) {
                PluginAir.log("Valid ports page. Skipping Login");
                skipLoginPage = true;
                alreadyLoggedIn = true;
            } else {
                ports = null;
            }
        }

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

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

            HttpGet getLoginPage = new HttpGet(VPN_LOGIN_URL);
            requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(10000).build();
            getLoginPage.setConfig(requestConfig);

            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) {
                PluginAir.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, "airvpn.rpc.noauthkey");
                return false;
            }

            loginURL = UrlUtils.unescapeXML(loginURL);

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

            if (alreadyLoggedIn) {
                PluginAir.log("Already Logged In");
            } else {
                PluginAir.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(10000).build();

                httpPostLogin.setConfig(requestConfig);

                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("invisible", "1"));
                urlParameters.add(new BasicNameValuePair("inline_invisible", "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) {
                }

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

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

        if (ports == null) {
            ports = scrapePorts(bindIP, token);
        }

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

        int existingIndex = ourPortInList(ports);
        if (existingIndex >= 0) {
            addReply(sReply, CHAR_GOOD, "airvpn.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.length > 0 && ports[0].ourBinding) || ports.length == 20) {
            int port = Integer.parseInt(ports[0].port);
            gotPort = true;

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

            changePort(port, sReply);
        } else {
            // 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);
            }

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

            existingIndex = ourPortInList(ports);
            if (existingIndex >= 0) {
                addReply(sReply, CHAR_GOOD, "airvpn.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, "airvpn.port.from.rpc", new String[] { Integer.toString(port) });

                changePort(port, sReply);
            }

        }

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

            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "airvpn.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;
}