Example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore

List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore.

Prototype

public BasicCookieStore() 

Source Link

Usage

From source file:webtest.Test1.java

public void runTest1() {

    List<String> ouList = new ArrayList<>();

    int count = 0;
    try {/*  w  w w .j  ava 2 s.c  o m*/
        BufferedReader in;
        in = new BufferedReader(
                new FileReader("C:\\Users\\hallm8\\Documents\\NetBeansProjects\\WebTest\\src\\webtest\\OU"));
        String str;

        while ((str = in.readLine()) != null) {
            ouList.add(str);
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
    }

    FirefoxProfile fp = new FirefoxProfile(
            new File("C:\\Users\\hallm8\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\tiu8eb0h.default"));
    fp.setPreference("webdriver.load.strategy", "unstable");
    WebDriver driver = new FirefoxDriver(fp);

    driver.manage().window().maximize();
    driver.get("http://byui.brightspace.com/d2l/login?noredirect=true");
    WebElement myDynamicElement = (new WebDriverWait(driver, 60))
            .until(ExpectedConditions.presenceOfElementLocated(By.id("d2l_minibar_placeholder")));

    // times out after 60 seconds
    Actions actions = new Actions(driver);
    for (String ouList1 : ouList) {
        WebDriverWait wait = new WebDriverWait(driver, 60);
        /**
         * PULLING VALENCE REQUESTS
         *
         * Step 1: Open up Selenium and authenticate by having the user sign
         * in. This bypasses the Authorization Protection
         *
         * Step 2: Open up HTTP Client and pass the cookies into it.
         *
         * Step 3: Open up the JSON parser of your choosing and parse into
         * it!
         */

        try {

            Set<Cookie> seleniumCookies = driver.manage().getCookies();
            CookieStore cookieStore = new BasicCookieStore();

            for (Cookie seleniumCookie : seleniumCookies) {
                BasicClientCookie basicClientCookie = new BasicClientCookie(seleniumCookie.getName(),
                        seleniumCookie.getValue());
                basicClientCookie.setDomain(seleniumCookie.getDomain());
                basicClientCookie.setExpiryDate(seleniumCookie.getExpiry());
                basicClientCookie.setPath(seleniumCookie.getPath());
                cookieStore.addCookie(basicClientCookie);
            }
            HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
            HttpGet request = new HttpGet(
                    "https://byui.brightspace.com/d2l/api/le/1.7/" + ouList1 + "/content/toc");
            request.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();

            String jsonString = EntityUtils.toString(response.getEntity());

            JSONObject obj = new JSONObject(jsonString);
            JSONArray modules = obj.getJSONArray("Modules");
            System.out.println(jsonString);

            for (int i = 0; i < modules.length(); i++) {
                if (modules.getJSONObject(i).has("Modules")) {
                    modules.put(modules.getJSONObject(i).getJSONArray("Modules"));
                }

                System.out.println(modules.get(i));
                JSONArray topics = modules.getJSONObject(i).getJSONArray("Topics");
                for (int j = 0; j < topics.length(); j++) {
                    JSONObject topic = topics.getJSONObject(j);
                    System.out.println(topic.get("Title"));
                }
            }
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();

            /**
             * This covers Dropbox Folders
             *
             * System.out.println(ouList1);
             * driver.get("https://byui.brightspace.com/d2l/lms/dropbox/admin/folders_manage.d2l?ou="
             * + ouList1); driver.manage().timeouts().implicitlyWait(3,
             * TimeUnit.SECONDS);
             *
             * List<WebElement> links =
             * driver.findElements(By.xpath("//a[contains(@href,
             * '/d2l/lms/dropbox/admin/mark/')]"));
             *
             * ArrayList<String> dropBoxes = new ArrayList<>();
             *
             * System.out.println(links.size()); for (WebElement link :
             * links) {
             *
             * System.out.println(link.getAttribute("href")); if
             * (link.getAttribute("href") != null &&
             * link.getAttribute("href").contains("/d2l/lms/dropbox/admin/mark/"))
             * {
             * dropBoxes.add(link.getAttribute("href").replace("mark/folder_submissions_users",
             * "modify/folder_newedit_properties"));
             * System.out.println("successfully pulled: " +
             * link.getAttribute("href")); } }
             *
             * for (int j = 0; j < dropBoxes.size(); j++) { String dropBox =
             * dropBoxes.get(j); driver.get(dropBox);
             *
             * if (!driver.findElements(By.linkText("Show Submission
             * Options")).isEmpty()) { driver.findElement(By.linkText("Show
             * Submission Options")).click();
             * driver.manage().timeouts().implicitlyWait(1800,
             * TimeUnit.SECONDS); }
             *
             * if (driver.findElement(By.id("z_cd")).isSelected()) {
             * //((JavascriptExecutor)
             * driver).executeScript("arguments[0].scrollIntoView(true);",
             * driver.findElement(By.id("z_ce")));
             * actions.moveToElement(driver.findElement(By.id("z_ce"))).click().perform();
             * actions.moveToElement(driver.findElement(By.id("z_ci"))).click().perform();
             * driver.findElement(By.id("z_c")).click();
             * driver.manage().timeouts().implicitlyWait(3,
             * TimeUnit.SECONDS); } }
             *
             * // Response response = json.fromJson(, Response.class) /**
             * This covers content.
             */
            /*
            driver.get("https://byui.brightspace.com/d2l/le/content/9730/Home");
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            List<WebElement> dragElement = driver.findElements(By.xpath("//div[contains(@id,'TreeItem')]//div[contains(@class, 'd2l-textblock')]"));
            /*
            for (int i = 4; i < dragElement.size(); i++) {
                    
            WebElement drag = dragElement.get(i);
                    
                    
            drag.click();
                    
            wait.until(ExpectedConditions.elementToBeClickable(drag));
            /*
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
            System.out.println(driver.findElement(By.xpath("//h1[contains(@class, 'd2l-page-title d2l-heading vui-heading-1')]")).getText());
            (new WebDriverWait(driver, 60)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
            return drag.getText().contains(d.findElement(By.xpath("//h1[contains(@class, 'd2l-page-title d2l-heading vui-heading-1')]")).getText());
            }
            });
                    
                    
            try {
            // while the following loop runs, the DOM changes -
            // page is refreshed, or element is removed and re-added
            // This took me forever to figure out!!!
            Thread.sleep(2000);
            } catch (InterruptedException ex) {
            Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
            }
                    
                    
            List<WebElement> contentItems = driver.findElements(By.className("d2l-fuzzydate"));
                    
            for (int k = 1; k < contentItems.size(); k++) {
            WebElement content = contentItems.get(k);
            wait.until(presenceOfElementLocated(By.className(content.getAttribute("class"))));
            WebElement parent1 = content.findElement(By.xpath(".."));
            System.out.println(parent1.getTagName());
            WebElement parent2 = parent1.findElement(By.xpath(".."));
            System.out.println(parent2.getTagName());
            WebElement parent3 = parent2.findElement(By.xpath(".."));
            System.out.println(parent3.getTagName());
            WebElement parent4 = parent3.findElement(By.xpath(".."));
            System.out.println(parent4.getTagName());
            WebElement parent5 = parent4.findElement(By.xpath(".."));
            System.out.println(parent5.getTagName());
            WebElement parent6 = parent5.findElement(By.xpath(".."));
            System.out.println(parent6.getTagName());
            //System.out.println(parent5.getText());
            System.out.println(parent6.getAttribute("title"));
            }
                    
            }
             */
            /**
             * This covers quizzes
             */
            /*
            driver.get("https://byui.brightspace.com/d2l/lms/quizzing/admin/quizzes_manage.d2l?ou=" + ouList1);
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            List<WebElement> links = driver.findElements(By.className("vui-outline"));
                    
            ArrayList<String> quizzes = new ArrayList<>();
                    
            for (WebElement link : links) {
            if (link.getAttribute("href") != null && link.getAttribute("href").contains("byui.brightspace.com/d2l/lms/quizzing/admin/modify")) {
            quizzes.add(link.getAttribute("href"));
            System.out.println("successfully pulled: " + link.getAttribute("href"));
                    
            }
            }
                    
            for (int j = 0; j < quizzes.size(); j++) {
            String quiz = quizzes.get(j);
            boolean isLA = false;
            driver.get(quiz);
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            if (!driver.findElements(By.linkText("Expand optional advanced properties")).isEmpty()) {
            driver.findElement(By.linkText("Expand optional advanced properties")).click();
            driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
                    
            }
                    
            if (driver.findElement(By.name("disableRightClick")).isSelected()) {
            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", driver.findElement(By.name("disableRightClick")));
            driver.findElement(By.name("disableRightClick")).click();
            driver.findElement(By.id("z_b")).click();
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
            count++;
            }
                    
            List<WebElement> labels = driver.findElements(By.tagName("label"));
            for (WebElement label : labels) {
            if (label.getText().contains("LA")) {
            isLA = true;
            break;
            }
            }
                    
            driver.findElement(By.id("z_h_Assessment_l")).click();
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            if (driver.findElement(By.name("autoExportGrades")).isSelected()
            && isLA == true) {
            driver.findElement(By.name("autoExportGrades")).click();
            count++;
            }
                    
            if (driver.findElement(By.name("autoSetGraded")).isSelected()
            && isLA == true) {
            driver.findElement(By.name("autoSetGraded")).click();
            count++;
            }
                    
            if (!driver.findElement(By.name("autoSetGraded")).isSelected()
            && isLA == false) {
            driver.findElement(By.name("autoSetGraded")).click();
            count++;
                    
            }
                    
            if (!driver.findElement(By.name("autoExportGrades")).isSelected()
            && isLA == false) {
            driver.findElement(By.name("autoExportGrades")).click();
            count++;
            }
                    
            driver.findElement(By.id("z_b")).click();
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            System.out.println("count is: " + count);
                    
            /**
            *
            * Submission Views
            *
             */
            /*
                           driver.findElement(By.linkText("Submission Views")).click();
                           driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                                   
                           driver.findElement(By.linkText("Default View")).click();
                           driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                                   
                           if (!driver.findElement(By.name("showQuestions")).isSelected()) {
                           System.out.println("show answers clicked!!!  URL: " + quiz);
                           driver.findElement(By.name("showQuestions")).click();
                           }
                                   
                           if (!driver.findElement(By.id("z_p")).isSelected()) {
                           driver.findElement(By.id("z_p")).click();
                           }
                           if (!driver.findElement(By.name("showCorrectAnswers")).isSelected()) {
                           driver.findElement(By.name("showCorrectAnswers")).click();
                           }
                           if (!driver.findElement(By.name("showQuestionScore")).isSelected()) {
                           driver.findElement(By.name("showQuestionScore")).click();
                           }
                           if (!driver.findElement(By.name("showScore")).isSelected()) {
                           driver.findElement(By.name("showScore")).click();
                           }
                                   
                           driver.findElement(By.id("z_a")).click();
                            */
            //}
            /**
             * This covers content.
             */
            /*
            driver.get("https://byui.brightspace.com/d2l/le/content/9730/Home");
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            List<WebElement> dragElement = driver.findElements(By.xpath("//div[contains(@id,'TreeItem')]//div[contains(@class, 'd2l-textblock')]"));
            /*
            for (int i = 4; i < dragElement.size(); i++) {
                    
            WebElement drag = dragElement.get(i);
                    
                    
            drag.click();
                    
            wait.until(ExpectedConditions.elementToBeClickable(drag));
            /*
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
            System.out.println(driver.findElement(By.xpath("//h1[contains(@class, 'd2l-page-title d2l-heading vui-heading-1')]")).getText());
            (new WebDriverWait(driver, 60)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
            return drag.getText().contains(d.findElement(By.xpath("//h1[contains(@class, 'd2l-page-title d2l-heading vui-heading-1')]")).getText());
            }
            });
                    
                    
            try {
            // while the following loop runs, the DOM changes -
            // page is refreshed, or element is removed and re-added
            // This took me forever to figure out!!!
            Thread.sleep(2000);
            } catch (InterruptedException ex) {
            Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
            }
                    
                    
            List<WebElement> contentItems = driver.findElements(By.className("d2l-fuzzydate"));
                    
            for (int k = 1; k < contentItems.size(); k++) {
            WebElement content = contentItems.get(k);
            wait.until(presenceOfElementLocated(By.className(content.getAttribute("class"))));
            WebElement parent1 = content.findElement(By.xpath(".."));
            System.out.println(parent1.getTagName());
            WebElement parent2 = parent1.findElement(By.xpath(".."));
            System.out.println(parent2.getTagName());
            WebElement parent3 = parent2.findElement(By.xpath(".."));
            System.out.println(parent3.getTagName());
            WebElement parent4 = parent3.findElement(By.xpath(".."));
            System.out.println(parent4.getTagName());
            WebElement parent5 = parent4.findElement(By.xpath(".."));
            System.out.println(parent5.getTagName());
            WebElement parent6 = parent5.findElement(By.xpath(".."));
            System.out.println(parent6.getTagName());
            //System.out.println(parent5.getText());
            System.out.println(parent6.getAttribute("title"));
            }
                    
            }
             */
            /**
             * This covers quizzes
             */
            /*
            driver.get("https://byui.brightspace.com/d2l/lms/quizzing/admin/quizzes_manage.d2l?ou=" + ouList1);
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
            System.out.println("Opening OU# " + ouList1);
            wait.until(ExpectedConditions.elementToBeClickable(By.className("d2l-tool-areas")));
                    
            List<WebElement> links = driver.findElements(By.xpath("//a[contains(@href,'/d2l/lms/quizzing/admin/modify/quiz_newedit_properties.d2l?qi=')]"));
            System.out.println("viu outline obtained");
                    
            ArrayList<String> quizzes = new ArrayList<>();
                    
            System.out.println(links.size());
                    
            for (WebElement link : links) {
            if (link.getAttribute("href") != null && link.getAttribute("href").contains("byui.brightspace.com/d2l/lms/quizzing/admin/modify")) {
            quizzes.add(link.getAttribute("href"));
            System.out.println("successfully pulled: " + link.getAttribute("href"));
            }
            }
            System.out.println(quizzes.size());
                    
            for (int j = 0; j < quizzes.size(); j++) {
            String quiz = quizzes.get(j);
            boolean isLA = false;
            driver.get(quiz);
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            if (!driver.findElements(By.linkText("Expand optional advanced properties")).isEmpty()) {
            driver.findElement(By.linkText("Expand optional advanced properties")).click();
            driver.manage().timeouts().implicitlyWait(1800, TimeUnit.SECONDS);
                    
            }
                    
            wait.until(ExpectedConditions.elementToBeClickable(By.name("disableRightClick")));
            if (driver.findElement(By.name("disableRightClick")).isSelected()) {
            driver.findElement(By.name("disableRightClick")).click();
            driver.findElement(By.id("z_b")).click();
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
            count++;
            }
                    
            List<WebElement> longAnswer = driver.findElements(By.xpath("//label[contains(.,'LA')]"));
            if (longAnswer.size() > 0) {
            isLA = true;
            }
                    
            quiz = quiz.replace("/quiz_newedit_properties", "/quiz_newedit_assessment");
            driver.get(quiz);
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.name("autoExportGrades")));
            if (driver.findElement(By.name("autoExportGrades")).isSelected()
                && isLA == true) {
            driver.findElement(By.name("autoExportGrades")).click();
            count++;
            }
                    
            wait.until(ExpectedConditions.elementToBeClickable(By.name("autoSetGraded")));
            if (driver.findElement(By.name("autoSetGraded")).isSelected()
                && isLA == true) {
            driver.findElement(By.name("autoSetGraded")).click();
            count++;
            }
                    
            wait.until(ExpectedConditions.elementToBeClickable(By.name("autoSetGraded")));
            if (!driver.findElement(By.name("autoSetGraded")).isSelected()
                && isLA == false) {
            driver.findElement(By.name("autoSetGraded")).click();
            count++;
                    
            }
                    
            wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.name("autoExportGrades")));
            if (!driver.findElement(By.name("autoExportGrades")).isSelected()
                && isLA == false) {
            driver.findElement(By.name("autoExportGrades")).click();
            count++;
            }
                    
            wait.until(ExpectedConditions.elementToBeClickable(By.id("z_b")));
            driver.findElement(By.id("z_b")).click();
            driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                    
            System.out.println("count is: " + count);
                    
            /**
             *
             * Submission Views
             *
             */
            /*
                           driver.findElement(By.linkText("Submission Views")).click();
                           driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                                   
                           driver.findElement(By.linkText("Default View")).click();
                           driver.manage().timeouts().pageLoadTimeout(1800, TimeUnit.SECONDS);
                                   
                           if (!driver.findElement(By.name("showQuestions")).isSelected()) {
                           System.out.println("show answers clicked!!!  URL: " + quiz);
                           driver.findElement(By.name("showQuestions")).click();
                           }
                                   
                           if (!driver.findElement(By.id("z_p")).isSelected()) {
                           driver.findElement(By.id("z_p")).click();
                           }
                           if (!driver.findElement(By.name("showCorrectAnswers")).isSelected()) {
                           driver.findElement(By.name("showCorrectAnswers")).click();
                           }
                           if (!driver.findElement(By.name("showQuestionScore")).isSelected()) {
                           driver.findElement(By.name("showQuestionScore")).click();
                           }
                           if (!driver.findElement(By.name("showScore")).isSelected()) {
                           driver.findElement(By.name("showScore")).click();
                           }
                                   
                           driver.findElement(By.id("z_a")).click();
                            */
            //}
            /**
             * End of FOR LOOP stub
             */
        } catch (IOException ex) {
            Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

/**
 * no-arg constructor for client//w ww. java  2 s .  c  o  m
 */
public TankHttpClient4() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
            .setCircularRedirectsAllowed(true).setAuthenticationEnabled(true).setRedirectsEnabled(true)
            .setMaxRedirects(100).build();

    // Make sure the same context is used to execute logically related
    // requests
    context = HttpClientContext.create();
    context.setCredentialsProvider(new BasicCredentialsProvider());
    context.setCookieStore(new BasicCookieStore());
    context.setRequestConfig(requestConfig);
}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
public void configure(HttpConfig config) {
    clientBuilder = HttpClientBuilder.create();
    cookieStore = new BasicCookieStore();
    clientBuilder.setDefaultCookieStore(cookieStore);
    AtomicInteger counter = new AtomicInteger();
    clientBuilder.addInterceptorLast(new RequestLoggingInterceptor(counter));
    clientBuilder.addInterceptorLast(new ResponseLoggingInterceptor(counter));
    if (config.isSslEnabled()) {
        // System.setProperty("jsse.enableSNIExtension", "false");
        String sslAlgorithm = config.getSslAlgorithm();
        logger.info("ssl enabled, initializing generic trusted certificate / key-store with algorithm: {}",
                sslAlgorithm);//from w  w w .j a v  a2  s .  c  o m
        SSLContext sslContext = HttpUtils.getSslContext(sslAlgorithm);
        SSLConnectionSocketFactory socketFactory = new LenientSslConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());
        clientBuilder.setSSLSocketFactory(socketFactory);
    }

    RequestConfig.Builder configBuilder = RequestConfig.custom().setConnectTimeout(config.getConnectTimeout())
            .setSocketTimeout(config.getReadTimeout());
    clientBuilder.setDefaultRequestConfig(configBuilder.build());
    if (config.getProxyUri() != null) {
        try {
            URI proxyUri = new URIBuilder(config.getProxyUri()).build();
            clientBuilder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()));
            if (config.getProxyUsername() != null && config.getProxyPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()),
                        new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection//w w  w.j  av a  2s.  c  om
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception
 */
@Override
public void prepareConnection() throws EWSHttpException {
    try {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        if (getProxy() != null) {
            HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort());
            builder.setProxy(proxy);

            if (HttpProxyCredentials.isProxySet()) {
                NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(),
                        HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxy), cred);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        if (getUserName() != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(getUserName(), getPassword(), "", getDomain()));
            builder.setDefaultCredentialsProvider(credsProvider);
        }

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setAuthenticationEnabled(true);
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setRedirectsEnabled(isAllowAutoRedirect());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        if (getUserName() != null) {
            ArrayList<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthSchemes.NTLM);
            rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        }
        //
        builder.setDefaultRequestConfig(rcBuilder.build());

        httpPostReq = new HttpPost(getUrl().toString());
        httpPostReq.addHeader("Content-type", getContentType());
        //httpPostReq.setDoAuthentication(true);
        httpPostReq.addHeader("User-Agent", getUserAgent());
        httpPostReq.addHeader("Accept", getAccept());
        httpPostReq.addHeader("Keep-Alive", "300");
        httpPostReq.addHeader("Connection", "Keep-Alive");

        if (isAcceptGzipEncoding()) {
            httpPostReq.addHeader("Accept-Encoding", "gzip,deflate");
        }

        if (getHeaders().size() > 0) {
            for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
                httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue());
            }
        }

        //create the client
        client = builder.build();
    } catch (Exception er) {
        er.printStackTrace();
    }
}

From source file:io.undertow.server.handlers.session.InMemorySessionTestCase.java

@Test
public void inMemoryMaxSessionsTest() throws IOException {

    TestHttpClient client1 = new TestHttpClient();
    client1.setCookieStore(new BasicCookieStore());
    TestHttpClient client2 = new TestHttpClient();
    client2.setCookieStore(new BasicCookieStore());

    try {/*from ww w  .  j  ava2s .c o m*/
        final SessionCookieConfig sessionConfig = new SessionCookieConfig();
        final SessionAttachmentHandler handler = new SessionAttachmentHandler(
                new InMemorySessionManager("", 1, true), sessionConfig);
        handler.setNext(new HttpHandler() {
            @Override
            public void handleRequest(final HttpServerExchange exchange) throws Exception {
                final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
                Session session = manager.getSession(exchange, sessionConfig);
                if (session == null) {
                    session = manager.createSession(exchange, sessionConfig);
                    session.setAttribute(COUNT, 0);
                }
                Integer count = (Integer) session.getAttribute(COUNT);
                exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
                session.setAttribute(COUNT, ++count);
            }
        });
        DefaultServer.setRootHandler(handler);

        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        HttpResponse result = client1.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        Header[] header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client1.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("1", header[0].getValue());

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client2.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client1.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());

    } finally {
        client1.getConnectionManager().shutdown();
        client2.getConnectionManager().shutdown();
    }
}

From source file:org.wso2.carbon.registry.notes.test.PublisherNotesTestCase.java

@Test(groups = "wso2.greg", description = "Add Schema without name", dependsOnMethods = "createSOAPService")
public void addNoteTestCase() throws Exception {
    String session_id = authenticateJaggeryAPI();
    String endPoint = "https://localhost:10343/publisher/apis/assets?type=note";

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(endPoint);
    post.setHeader("Cookie", "JSESSIONID=" + session_id);
    List nameValuePairs = new ArrayList(5);
    nameValuePairs.add(new BasicNameValuePair("overview_note", "note_one"));
    nameValuePairs.add(new BasicNameValuePair("overview_resourcepath",
            "/_system/governance/trunk/soapservices/4.5.0/SOAPService1"));
    nameValuePairs.add(new BasicNameValuePair("overview_visibility", "public"));
    nameValuePairs.add(new BasicNameValuePair("overview_note", "admin"));
    nameValuePairs.add(new BasicNameValuePair("overview_status", "open"));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = client.execute(post);
    assertEquals("Created", response.getStatusLine().getReasonPhrase());
}

From source file:org.fao.geonet.utils.GeonetHttpRequestFactory.java

/**
 * Ceate an XmlRequest from a url.//from   ww w  .ja v  a 2 s . com
 *
 * @param url the url of the request.
 * @return the XmlRequest.
 */
public final XmlRequest createXmlRequest(URL url) {
    final int port = url.getPort();
    final XmlRequest request = createXmlRequest(url.getHost(), port, url.getProtocol());

    request.setAddress(url.getPath());
    request.setQuery(url.getQuery());
    request.setFragment(url.getRef());
    request.setUserInfo(url.getUserInfo());
    request.setCookieStore(new BasicCookieStore());
    return request;
}

From source file:org.jspringbot.keyword.http.HTTPHelper.java

public void newSession() {
    LOG.info("Created New HTTP Session.");

    this.context = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    reset();//from  w  w w. j  a  va2  s .c  om
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }//from  w w w.  ja  v a 2s . com

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}