Search in sources :

Example 51 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project NoraUi by NoraUi.

the class MailSteps method createRestTemplate.

private static RestTemplate createRestTemplate() {
    String proxyUser = "";
    String proxyPassword = "";
    String proxyUrl = "";
    int proxyPort = 0;
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    if (!"".equals(proxyUrl)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxyUrl, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
        HttpHost myProxy = new HttpHost(proxyUrl, proxyPort);
        clientBuilder.setProxy(myProxy).setDefaultCredentialsProvider(credsProvider).disableCookieManagement();
    }
    HttpClient httpClient = clientBuilder.build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
    return restTemplate;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) RestTemplate(org.springframework.web.client.RestTemplate) GsonHttpMessageConverter(org.springframework.http.converter.json.GsonHttpMessageConverter) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 52 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project ANNIS by korpling.

the class Helper method createRESTClient.

/**
 * Creates an authentificiated REST client
 *
 * @param userName
 * @param password
 * @return A newly created client.
 */
public static Client createRESTClient(String userName, String password) {
    DefaultApacheHttpClient4Config rc = new DefaultApacheHttpClient4Config();
    rc.getClasses().add(SaltProjectProvider.class);
    ThreadSafeClientConnManager clientConnMgr = new ThreadSafeClientConnManager();
    clientConnMgr.setDefaultMaxPerRoute(10);
    rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, clientConnMgr);
    if (userName != null && password != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider);
        rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, true);
    }
    Client c = ApacheHttpClient4.create(rc);
    return c;
}
Also used : DefaultApacheHttpClient4Config(com.sun.jersey.client.apache4.config.DefaultApacheHttpClient4Config) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Client(com.sun.jersey.api.client.Client) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 53 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project joynr by bmwcarit.

the class HttpClientProvider method createHttpClient.

public CloseableHttpClient createHttpClient(MessagingSettings mySettings, Properties withProperties) {
    // Create a HTTP client that uses the default pooling connection manager
    // and is configured by system properties
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(null).setMaxConnTotal(httpConstants.getHTTP_MAXIMUM_CONNECTIONS_TOTAL()).setMaxConnPerRoute(httpConstants.getHTTP_MAXIMUM_CONNECTIONS_TO_HOST()).useSystemProperties();
    String proxyHost = withProperties.getProperty("http.proxyhost");
    if (proxyHost != null) {
        // default proxy port is 8080
        int proxyPort = 8080;
        try {
            proxyPort = Integer.parseInt(withProperties.getProperty("http.proxyport"));
        } catch (Exception e) {
        }
        String proxyUser = withProperties.getProperty("http.proxyuser");
        if (proxyUser != null) {
            String proxyPassword = withProperties.getProperty("http.proxypassword");
            // default password is empty string
            proxyPassword = proxyPassword == null ? "" : proxyPassword;
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }
    }
    return httpClientBuilder.build();
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 54 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project cerberus-source by cerberustesting.

the class SeleniumServerService method startServer.

@Override
public void startServer(TestCaseExecution tCExecution) throws CerberusException {
    // message used for log purposes
    String logPrefix = "[" + tCExecution.getTest() + " - " + tCExecution.getTestCase() + "] ";
    try {
        LOG.info(logPrefix + "Start Robot Server (Selenium, Appium or Sikuli)");
        /**
         * Set Session
         */
        LOG.debug(logPrefix + "Setting the session.");
        String system = tCExecution.getApplicationObj().getSystem();
        /**
         * Get the parameters that will be used to set the servers
         * (selenium/appium) If timeout has been defined at the execution
         * level, set the selenium & appium wait element with this value,
         * else, take the one from parameter
         */
        Integer cerberus_selenium_pageLoadTimeout, cerberus_selenium_implicitlyWait, cerberus_selenium_setScriptTimeout, cerberus_selenium_wait_element, cerberus_appium_wait_element, cerberus_selenium_action_click_timeout;
        if (!tCExecution.getTimeout().isEmpty()) {
            cerberus_selenium_wait_element = Integer.valueOf(tCExecution.getTimeout());
            cerberus_appium_wait_element = Integer.valueOf(tCExecution.getTimeout());
        } else {
            cerberus_selenium_wait_element = parameterService.getParameterIntegerByKey("cerberus_selenium_wait_element", system, 90000);
            cerberus_appium_wait_element = parameterService.getParameterIntegerByKey("cerberus_appium_wait_element", system, 90000);
        }
        cerberus_selenium_pageLoadTimeout = parameterService.getParameterIntegerByKey("cerberus_selenium_pageLoadTimeout", system, 90000);
        cerberus_selenium_implicitlyWait = parameterService.getParameterIntegerByKey("cerberus_selenium_implicitlyWait", system, 0);
        cerberus_selenium_setScriptTimeout = parameterService.getParameterIntegerByKey("cerberus_selenium_setScriptTimeout", system, 90000);
        cerberus_selenium_action_click_timeout = parameterService.getParameterIntegerByKey("cerberus_selenium_action_click_timeout", system, 90000);
        LOG.debug(logPrefix + "TimeOut defined on session : " + cerberus_selenium_wait_element);
        Session session = new Session();
        session.setCerberus_selenium_implicitlyWait(cerberus_selenium_implicitlyWait);
        session.setCerberus_selenium_pageLoadTimeout(cerberus_selenium_pageLoadTimeout);
        session.setCerberus_selenium_setScriptTimeout(cerberus_selenium_setScriptTimeout);
        session.setCerberus_selenium_wait_element(cerberus_selenium_wait_element);
        session.setCerberus_appium_wait_element(cerberus_appium_wait_element);
        session.setCerberus_selenium_action_click_timeout(cerberus_selenium_action_click_timeout);
        session.setHost(tCExecution.getSeleniumIP());
        session.setHostUser(tCExecution.getSeleniumIPUser());
        session.setHostPassword(tCExecution.getSeleniumIPPassword());
        session.setPort(tCExecution.getPort());
        tCExecution.setSession(session);
        LOG.debug(logPrefix + "Session is set.");
        /**
         * SetUp Capabilities
         */
        LOG.debug(logPrefix + "Set Capabilities");
        DesiredCapabilities caps = this.setCapabilities(tCExecution);
        session.setDesiredCapabilities(caps);
        LOG.debug(logPrefix + "Set Capabilities - retreived");
        /**
         * SetUp Proxy
         */
        String hubUrl = StringUtil.cleanHostURL(SeleniumServerService.getBaseUrl(StringUtil.formatURLCredential(tCExecution.getSession().getHostUser(), tCExecution.getSession().getHostPassword()) + session.getHost(), session.getPort())) + "/wd/hub";
        LOG.debug(logPrefix + "Hub URL :" + hubUrl);
        URL url = new URL(hubUrl);
        HttpCommandExecutor executor = null;
        boolean isProxy = proxyService.useProxy(hubUrl, system);
        if (isProxy) {
            String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);
            int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);
            HttpClientBuilder builder = HttpClientBuilder.create();
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            builder.setProxy(proxy);
            if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {
                String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);
                String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
                if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
                    credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(tCExecution.getSession().getHostUser(), tCExecution.getSession().getHostPassword()));
                }
                builder.setDefaultCredentialsProvider(credsProvider);
            }
            Factory factory = new MyHttpClientFactory(builder);
            executor = new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);
        }
        /**
         * SetUp Driver
         */
        LOG.debug(logPrefix + "Set Driver");
        WebDriver driver = null;
        AppiumDriver appiumDriver = null;
        if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI)) {
            if (caps.getPlatform().is(Platform.ANDROID)) {
                if (executor == null) {
                    appiumDriver = new AndroidDriver(url, caps);
                } else {
                    appiumDriver = new AndroidDriver(executor, caps);
                }
                driver = (WebDriver) appiumDriver;
            } else if (caps.getPlatform().is(Platform.MAC)) {
                if (executor == null) {
                    appiumDriver = new IOSDriver(url, caps);
                } else {
                    appiumDriver = new IOSDriver(executor, caps);
                }
                driver = (WebDriver) appiumDriver;
            } else // Any Other
            {
                if (executor == null) {
                    driver = new RemoteWebDriver(url, caps);
                } else {
                    driver = new RemoteWebDriver(executor, caps);
                }
            }
        } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_APK)) {
            if (executor == null) {
                appiumDriver = new AndroidDriver(url, caps);
            } else {
                appiumDriver = new AndroidDriver(executor, caps);
            }
            driver = (WebDriver) appiumDriver;
        } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_IPA)) {
            if (executor == null) {
                appiumDriver = new IOSDriver(url, caps);
            } else {
                appiumDriver = new IOSDriver(executor, caps);
            }
            driver = (WebDriver) appiumDriver;
        } else if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_FAT)) {
            /**
             * Check sikuli extension is reachable
             */
            if (!sikuliService.isSikuliServerReachable(session)) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SIKULI_COULDNOTCONNECT);
                mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));
                mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));
                throw new CerberusException(mes);
            }
            /**
             * If CountryEnvParameter IP is set, open the App
             */
            if (!tCExecution.getCountryEnvironmentParameters().getIp().isEmpty()) {
                sikuliService.doSikuliActionOpenApp(session, tCExecution.getCountryEnvironmentParameters().getIp());
            }
        }
        /**
         * Defining the timeout at the driver level. Only in case of not
         * Appium Driver (see
         * https://github.com/vertigo17/Cerberus/issues/754)
         */
        if (driver != null && appiumDriver == null) {
            driver.manage().timeouts().pageLoadTimeout(cerberus_selenium_pageLoadTimeout, TimeUnit.MILLISECONDS);
            driver.manage().timeouts().implicitlyWait(cerberus_selenium_implicitlyWait, TimeUnit.MILLISECONDS);
            driver.manage().timeouts().setScriptTimeout(cerberus_selenium_setScriptTimeout, TimeUnit.MILLISECONDS);
        }
        tCExecution.getSession().setDriver(driver);
        tCExecution.getSession().setAppiumDriver(appiumDriver);
        /**
         * If Gui application, maximize window Get IP of Node in case of
         * remote Server. Maximize does not work for chrome browser We also
         * get the Real UserAgent from the browser.
         */
        if (tCExecution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI) && !caps.getPlatform().equals(Platform.ANDROID)) {
            if (!caps.getBrowserName().equals(BrowserType.CHROME)) {
                driver.manage().window().maximize();
            }
            getIPOfNode(tCExecution);
            /**
             * If screenSize is defined, set the size of the screen.
             */
            String targetScreensize = getScreenSizeToUse(tCExecution.getTestCaseObj().getScreenSize(), tCExecution.getScreenSize());
            LOG.debug("Selenium resolution : " + targetScreensize);
            if ((!StringUtil.isNullOrEmpty(targetScreensize)) && targetScreensize.contains("*")) {
                Integer screenWidth = Integer.valueOf(targetScreensize.split("\\*")[0]);
                Integer screenLength = Integer.valueOf(targetScreensize.split("\\*")[1]);
                setScreenSize(driver, screenWidth, screenLength);
                LOG.debug("Selenium resolution Activated : " + screenWidth + "*" + screenLength);
            }
            tCExecution.setScreenSize(getScreenSize(driver));
            tCExecution.setRobotDecli(tCExecution.getRobotDecli().replace("%SCREENSIZE%", tCExecution.getScreenSize()));
            String userAgent = (String) ((JavascriptExecutor) driver).executeScript("return navigator.userAgent;");
            tCExecution.setUserAgent(userAgent);
        }
        tCExecution.getSession().setStarted(true);
    } catch (CerberusException exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        throw new CerberusException(exception.getMessageError());
    } catch (MalformedURLException exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_URL_MALFORMED);
        mes.setDescription(mes.getDescription().replace("%URL%", tCExecution.getSession().getHost() + ":" + tCExecution.getSession().getPort()));
        throw new CerberusException(mes);
    } catch (UnreachableBrowserException exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_SELENIUM_COULDNOTCONNECT);
        mes.setDescription(mes.getDescription().replace("%SSIP%", tCExecution.getSeleniumIP()));
        mes.setDescription(mes.getDescription().replace("%SSPORT%", tCExecution.getSeleniumPort()));
        mes.setDescription(mes.getDescription().replace("%ERROR%", exception.toString()));
        throw new CerberusException(mes);
    } catch (Exception exception) {
        LOG.error(logPrefix + exception.toString(), exception);
        MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.EXECUTION_FA_SELENIUM);
        mes.setDescription(mes.getDescription().replace("%MES%", exception.toString()));
        throw new CerberusException(mes);
    }
}
Also used : WebDriver(org.openqa.selenium.WebDriver) RemoteWebDriver(org.openqa.selenium.remote.RemoteWebDriver) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) Factory(org.openqa.selenium.remote.http.HttpClient.Factory) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) AndroidDriver(io.appium.java_client.android.AndroidDriver) URL(java.net.URL) HttpCommandExecutor(org.openqa.selenium.remote.HttpCommandExecutor) IOSDriver(io.appium.java_client.ios.IOSDriver) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) HttpHost(org.apache.http.HttpHost) CerberusException(org.cerberus.exception.CerberusException) AppiumDriver(io.appium.java_client.AppiumDriver) RemoteWebDriver(org.openqa.selenium.remote.RemoteWebDriver) DesiredCapabilities(org.openqa.selenium.remote.DesiredCapabilities) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Point(org.openqa.selenium.Point) JSONException(org.json.JSONException) CerberusException(org.cerberus.exception.CerberusException) UnreachableBrowserException(org.openqa.selenium.remote.UnreachableBrowserException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) AuthScope(org.apache.http.auth.AuthScope) Session(org.cerberus.engine.entity.Session)

Example 55 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project alliance by codice.

the class FtpDestinationSink method writeFile.

@Override
public void writeFile(InputStream fileData, long size, String name, String contentType, List<Metacard> metacards) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + fileLocation.host_name + ":" + port + "/" + fileLocation.path_name + "/" + name;
    LOGGER.debug("Writing ordered file to URL: {}", urlPath);
    try {
        HttpPut putMethod = new HttpPut(urlPath);
        putMethod.addHeader(HTTP.CONTENT_TYPE, contentType);
        HttpEntity httpEntity = new InputStreamEntity(fileData, size);
        putMethod.setEntity(httpEntity);
        if (StringUtils.isNotEmpty(fileLocation.user_name) && fileLocation.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(fileLocation.host_name, port), new UsernamePasswordCredentials(fileLocation.user_name, fileLocation.password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClients.createDefault();
        }
        httpClient.execute(putMethod);
        fileData.close();
        putMethod.releaseConnection();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpPut(org.apache.http.client.methods.HttpPut) InputStreamEntity(org.apache.http.entity.InputStreamEntity) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)192 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)162 CredentialsProvider (org.apache.http.client.CredentialsProvider)147 AuthScope (org.apache.http.auth.AuthScope)104 HttpHost (org.apache.http.HttpHost)76 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)53 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)41 HttpResponse (org.apache.http.HttpResponse)38 IOException (java.io.IOException)35 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)31 HttpGet (org.apache.http.client.methods.HttpGet)30 HttpClient (org.apache.http.client.HttpClient)29 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)29 AuthCache (org.apache.http.client.AuthCache)28 BasicScheme (org.apache.http.impl.auth.BasicScheme)27 RequestConfig (org.apache.http.client.config.RequestConfig)25 HttpPost (org.apache.http.client.methods.HttpPost)20 Credentials (org.apache.http.auth.Credentials)19 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)19 Test (org.junit.Test)16