Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

In this page you can find the example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials.

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:org.jugvale.peoplemanagement.client.service.RESTPersonService.java

private void createClient() {
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            credentials);/*  w ww.  j  a v a  2 s. c  om*/
    client = new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(httpClient)).build();
}

From source file:pl.psnc.synat.wrdz.zmd.download.adapters.HttpDownloadAdapter.java

/**
 * Constructs new HTTP adapter using provided information.
 * //from w  w  w .j  ava 2s. co  m
 * @param connectionInfo
 *            connection information for SFTP protocol.
 * @param cacheHome
 *            cache root folder.
 */
public HttpDownloadAdapter(ConnectionInformation connectionInfo, String cacheHome) {
    super(connectionInfo, cacheHome);
    authScope = new AuthScope(connectionInfo.getHost(),
            connectionInfo.getPort() == null ? -1 : connectionInfo.getPort());
    String password = connectionInfo.getPassword();
    if (password != null && !password.isEmpty()) {
        usernamePasswordCredentials = new UsernamePasswordCredentials(connectionInfo.getUsername(), password);
    } else {
        usernamePasswordCredentials = null;
    }
}

From source file:org.dthume.couchdb.maven.AbstractOnlineCouchMojo.java

/**
 * @return the server configuration for this execution
 *//* w  w  w . j  a va2 s .c o m*/
protected final Server getServer() {
    final ServerImpl server = new ServerImpl(host, port);
    if (!StringUtils.isBlank(username)) {
        final Credentials creds = new UsernamePasswordCredentials(username, password);
        server.setCredentials(AuthScope.ANY, creds);
    }
    return server;
}

From source file:org.eclipse.microprofile.health.tck.SimpleHttp.java

protected Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

    StringBuilder content = new StringBuilder();
    int code;/*from w w  w  . ja  v a  2s  .c o  m*/

    try {

        HttpClientBuilder builder = HttpClientBuilder.create();
        if (!followRedirects) {
            builder.disableRedirectHandling();
        }

        if (useAuth) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
            provider.setCredentials(AuthScope.ANY, credentials);
            builder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = builder.build();

        HttpResponse response = client.execute(new HttpGet(theUrl));
        code = response.getStatusLine().getStatusCode();

        if (response.getEntity() != null) {

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

            String line;

            while ((line = bufferedReader.readLine()) != null) {
                content.append(line + "\n");
            }
            bufferedReader.close();
        }

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

    return new Response(code, content.toString());
}

From source file:com.squeezecontrol.image.HttpFetchingImageStore.java

public HttpFetchingImageStore(String baseUrl, String username, String password) {
    this.baseUrl = baseUrl;

    HttpParams params = new BasicHttpParams();

    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, schemeRegistry);
    mClient = new DefaultHttpClient(mgr, params);
    if (username != null && !"".equals(username)) {
        Credentials defaultcreds = new UsernamePasswordCredentials("dag", "test");
        mClient.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
    }/*w ww.j  av  a2s  .  c  o  m*/
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;//from  ww  w . j  a v a  2 s  .co  m
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:org.apache.sling.launchpad.SmokeIT.java

private CloseableHttpClient newClient() {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin");
    credsProvider.setCredentials(new AuthScope("localhost", LAUNCHPAD_PORT), creds);

    return HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:org.sonar.plugins.buildstability.ci.teamcity.TeamCityServer.java

@Override
public void doLogin(DefaultHttpClient client) throws IOException {
    Credentials credentials = new UsernamePasswordCredentials(getUsername(), getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
}

From source file:com.serena.rlc.provider.schedule.client.ScheduleWaiter.java

@Override
public void run() {
    logger.debug("ScheduleWaiter is sleeping for " + waitTime + " milliseconds, until " + endDate);
    try {/*from w ww .java 2s.  co m*/
        Thread.sleep(waitTime);
    } catch (InterruptedException ex) {
        logger.error("ScheduleWaiter was interrupted: " + ex.getLocalizedMessage());
    } catch (CancellationException ex) {
        logger.error("ScheduleWaiter thread has been cancelled: ", ex.getLocalizedMessage());
    }
    synchronized (executionId) {
        logger.debug("ScheduleWaiter has finished sleeping at " + new Date());

        try {
            String uri = callbackUrl + executionId + "/COMPLETED";
            logger.info("Start executing RLC PUT request to url=\"{}\"", uri);
            DefaultHttpClient rlcParams = new DefaultHttpClient();
            HttpPut put = new HttpPut(uri);
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(callbackUsername,
                    callbackPassword);
            put.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
            //put.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //put.addHeader("Accept", "application/json");
            logger.info(credentials.toString());
            HttpResponse response = rlcParams.execute(put);
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.error("HTTP Status Code: " + response.getStatusLine().getStatusCode());
            }
        } catch (IOException ex) {
            logger.error(ex.getLocalizedMessage());
        }

        executionId.notify();
    }

}