Example usage for org.apache.commons.httpclient UsernamePasswordCredentials getUserName

List of usage examples for org.apache.commons.httpclient UsernamePasswordCredentials getUserName

Introduction

In this page you can find the example usage for org.apache.commons.httpclient UsernamePasswordCredentials getUserName.

Prototype

public String getUserName() 

Source Link

Usage

From source file:com.gargoylesoftware.htmlunit.DefaultCredentialsProviderTest.java

/**
 * Test that successive calls to {@link DefaultCredentialsProvider#addCredentials(String, String)}
 * overwrite values previously set.//from  w ww  . ja  v a 2s .co m
 * @throws Exception if the test fails
 */
@Test
public void overwrite() throws Exception {
    final DefaultCredentialsProvider provider = new DefaultCredentialsProvider();
    provider.addCredentials("username", "password");

    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) provider
            .getCredentials(new BasicScheme(), "host", 80, false);
    assertEquals("username", credentials.getUserName());
    assertEquals("password", credentials.getPassword());

    provider.addCredentials("username", "new password");
    credentials = (UsernamePasswordCredentials) provider.getCredentials(new BasicScheme(), "host", 80, false);
    assertEquals("username", credentials.getUserName());
    assertEquals("new password", credentials.getPassword());

    provider.addCredentials("new username", "other password");
    credentials = (UsernamePasswordCredentials) provider.getCredentials(new BasicScheme(), "host", 80, false);
    assertEquals("new username", credentials.getUserName());
    assertEquals("other password", credentials.getPassword());
}

From source file:it.eng.spagobi.commons.filters.ProfileFilter.java

private void authenticate(UsernamePasswordCredentials credentials) throws Throwable {
    logger.debug("IN: userId = " + credentials.getUserName());
    try {//from   www  . j  av  a 2  s.c  o  m
        ISecurityServiceSupplier supplier = SecurityServiceSupplierFactory.createISecurityServiceSupplier();
        SpagoBIUserProfile profile = supplier.checkAuthentication(credentials.getUserName(),
                credentials.getPassword());
        if (profile == null) {
            logger.error("Authentication failed for user " + credentials.getUserName());
            throw new SecurityException("Authentication failed");
        }
    } catch (Throwable t) {
        logger.error("Error while authenticating userId = " + credentials.getUserName(), t);
        throw t;
    } finally {
        logger.debug("OUT");
    }

}

From source file:com.idega.slide.authentication.AuthenticationBusinessBean.java

public boolean isRootUser(HttpServletRequest request) {
    // HttpServletRequest request = iwc.getRequest();
    LoginBusinessBean loginBusiness = getLoginBusiness();
    String[] usernameAndPassword = loginBusiness.getLoginNameAndPasswordFromBasicAuthenticationRequest(request);
    UsernamePasswordCredentials tmpCredential = getRootUserCredentials();
    return tmpCredential.getUserName().equals(usernameAndPassword[0])
            && tmpCredential.getPassword().equals(usernameAndPassword[1]);
}

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int logout() {
    log.finest("Logout");
    try {/*from w ww.j  a  v  a2  s.  c o m*/
        log.finest("URI:" + url.toURI().toString());
    } catch (URISyntaxException ex) {
        log.finest("Logout URISyntaxException " + ex.getMessage());
    }

    String logoutUrl = this.url.toString() + contextRoot + JAZZ_LOGOUT_URL;
    log.finest("Attempting to log out with this url: " + logoutUrl);
    HttpMethodBase authenticationMethod = new PostMethod(this.url.toString() + contextRoot + JAZZ_LOGOUT_URL);
    authenticationMethod.setFollowRedirects(false);
    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) super.getState()
            .getCredentials(new AuthScope(host, port));
    if (null != credentials && !(credentials.getUserName().isEmpty() && credentials.getPassword().isEmpty())) {

        log.finest(String.format("Adding authorizationheadder for logout for user: %s",
                credentials.getUserName()));
        authenticationMethod.addRequestHeader("Authorization:",
                "Base " + credentials.getUserName() + ":" + credentials.getPassword());
    }
    String body = "";
    String status = "";
    int responseCode = 0;
    ;
    try {
        responseCode = executeMethod(authenticationMethod);
        body = authenticationMethod.getResponseBodyAsString();
        status = authenticationMethod.getStatusText();
        log.finest(String.format("Response code %s, Status text %s", responseCode, status));
    } catch (Exception e) {
        log.log(Level.SEVERE, "Failed to log out!", e);
        log.log(Level.SEVERE, body);
    }
    return responseCode;
}

From source file:fedora.common.http.WebClient.java

/**
 * Get an HTTP resource with the response as an InputStream, given a URL. If
 * FOLLOW_REDIRECTS is true, up to MAX_REDIRECTS redirects will be followed.
 * Note that if credentials are provided, for security reasons they will
 * only be provided to the FIRST url in a chain of redirects. Note that if
 * the HTTP response has no body, the InputStream will be empty. The success
 * of a request can be checked with getResponseCode(). Usually you'll want
 * to see a 200. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
 * for other codes./*from   w  ww  .  ja  v a2 s .com*/
 * 
 * @param url
 *        A URL that we want to do an HTTP GET upon
 * @param failIfNotOK
 *        boolean value indicating if an exception should be thrown if we do
 *        NOT receive an HTTP 200 response (OK)
 * @return HttpInputStream the HTTP response
 * @throws IOException
 */
public HttpInputStream get(String url, boolean failIfNotOK, UsernamePasswordCredentials creds)
        throws IOException {

    HttpClient client;
    GetMethod getMethod = new GetMethod(url);
    if (USER_AGENT != null) {
        getMethod.setRequestHeader("User-Agent", USER_AGENT);
    }
    if (creds != null && creds.getUserName() != null && creds.getUserName().length() > 0) {
        client = getHttpClient(url, creds);
        getMethod.setDoAuthentication(true);
    } else {
        client = getHttpClient(url);
    }

    HttpInputStream in = new HttpInputStream(client, getMethod, url);
    int status = in.getStatusCode();
    if (failIfNotOK) {
        if (status != 200) {
            //if (followRedirects && in.getStatusCode() == 302){
            if (FOLLOW_REDIRECTS && 300 <= status && status <= 399) {
                int count = 1;
                while (300 <= status && status <= 399 && count <= MAX_REDIRECTS) {
                    if (in.getResponseHeader("location") == null) {
                        throw new IOException("Redirect HTTP response provided no location header.");
                    }
                    url = in.getResponseHeader("location").getValue();
                    in.close();
                    getMethod = new GetMethod(url);
                    if (USER_AGENT != null) {
                        getMethod.setRequestHeader("User-Agent", USER_AGENT);
                    }
                    in = new HttpInputStream(client, getMethod, url);
                    status = in.getStatusCode();
                    count++;
                }
                if (300 <= status && status <= 399) {
                    in.close();
                    throw new IOException("Too many redirects");
                } else if (status != 200) {
                    in.close();
                    throw new IOException(
                            "Request failed [" + in.getStatusCode() + " " + in.getStatusText() + "]");
                }
                // redirect was successful!
            } else {
                try {
                    throw new IOException(
                            "Request failed [" + in.getStatusCode() + " " + in.getStatusText() + "]");
                } finally {
                    try {
                        in.close();
                    } catch (Exception e) {
                        System.err.println("Can't close InputStream: " + e.getMessage());
                    }
                }
            }
        }
    }
    return in;
}

From source file:com.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.java

private CustomConfiguration getCustomConfiguration(UsernamePasswordCredentials credentials) {
    AppConfigurationEntry[] defaultConfiguration = new AppConfigurationEntry[1];
    Map options = new HashMap();
    options.put("principal", credentials.getUserName());
    options.put("client", "true");
    options.put("debug", "false");
    defaultConfiguration[0] = new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
    return new CustomConfiguration(defaultConfiguration);
}

From source file:com.gist.twitter.TwitterClient.java

/**
 * Divides the ids among the credentials, and starts up a thread
 * for each set of credentials with a TwitterProcessor that
 * connects to twitter, and reconnects on exceptions, and
 * processes the stream.  After processForMillis, interrupt the
 * threads and return.//  w w w. jav  a  2  s .c om
 */
private void processForATime() {
    Collection<String> followIds = filterParameterFetcher.getFollowIds();
    Collection<Set<String>> followIdSets = createSets(followIds, maxFollowIdsPerCredentials);

    Collection<String> trackKeywords = filterParameterFetcher.getTrackKeywords();
    Collection<Set<String>> trackKeywordSets = createSets(trackKeywords, maxTrackKeywordsPerCredentials);

    Collection<Thread> threads = new ArrayList<Thread>();

    Iterator<UsernamePasswordCredentials> credentialsIterator = credentials.iterator();

    for (Set<String> ids : followIdSets) {
        for (Collection<String> keywords : trackKeywordSets) {
            if (credentialsIterator.hasNext()) {
                UsernamePasswordCredentials upc = credentialsIterator.next();
                Thread t = new Thread(new TwitterProcessor(upc, ids, keywords), "Twitter download as "
                        + upc.getUserName() + " (" + threadCount.getAndIncrement() + ")");
                threads.add(t);
                t.start();
            } else {
                logger.warning("Out of credentials, ignoring some ids/keywords.");
            }
        }
    }

    try {
        Thread.sleep(processForMillis);
    } catch (InterruptedException ex) {
        // Won't happen, ignore.
    }

    for (Thread t : threads) {
        t.interrupt();
    }

    // It doesn't matter so much whether the threads exit in a
    // timely manner.  We'll just get some IOExceptions or
    // something and retry.  This just makes the logs a little
    // nicer since we won't usually start a thread until the old
    // one has exited.
    for (Thread t : threads) {
        try {
            t.join(1000L);
        } catch (InterruptedException ex) {
            // Won't happen.
        }
    }
}

From source file:com.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.java

/**
 * Init GSSContext for negotiation./*  w w  w . j  ava 2  s . co m*/
 *
 * @param server servername only (e.g: radar.it.su.se)
 */
protected void init(String server, UsernamePasswordCredentials credentials) throws GSSException {
    LOG.info("init " + server);

    // Create a callback handler
    Configuration.setConfiguration(null);
    CallbackHandler callbackHandler = new CustomNegotiateCallbackHandler(credentials.getUserName(),
            credentials.getPassword());
    PrivilegedExceptionAction action = new MyAction(server);
    LoginContext con = null;

    try {
        CustomConfiguration cc = getCustomConfiguration(credentials);

        // Create a LoginContext with a callback handler
        con = new LoginContext("com.sun.security.jgss.login", null, callbackHandler, cc);

        Configuration.setConfiguration(cc);
        // Perform authentication
        con.login();
    } catch (LoginException e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    } catch (Exception e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    }

    // Perform action as authenticated user
    Subject subject = con.getSubject();
    //LOG.trace("Subject is :"+ subject.toString());

    LOG.info("Authenticated principal:**** " + subject.getPrincipals());

    try {
        Subject.doAs(subject, action);
    } catch (PrivilegedActionException e) {
        e.printStackTrace();

    } catch (Exception e) {
        e.printStackTrace();

    }

}

From source file:hr.fer.zemris.vhdllab.platform.remoting.HttpClientRequestExecutor.java

@SuppressWarnings("null")
@Override/*from   ww  w  . j  a v  a 2s .  co m*/
protected void executePostMethod(HttpInvokerClientConfiguration config, HttpClient httpClient,
        PostMethod postMethod) throws IOException {
    AuthScope scope = new AuthScope(config.getCodebaseUrl(), AuthScope.ANY_PORT);
    super.executePostMethod(config, httpClient, postMethod);
    switch (postMethod.getStatusCode()) {
    case HttpStatus.SC_UNAUTHORIZED:
        UsernamePasswordCredentials credentials;
        if (Environment.isDevelopment() && !showRetryMessage) {
            credentials = new UsernamePasswordCredentials("test", "test");
            //              credentials = new UsernamePasswordCredentials("admin", "admin");
            showRetryMessage = true;
        } else {
            CommandManager manager = Application.instance().getActiveWindow().getCommandManager();
            LoginCommand command = (LoginCommand) manager.getCommand("loginCommand");
            command.execute();
            credentials = command.getCredentials();
        }
        if (credentials == null) {
            System.exit(1);
        }
        ApplicationContextHolder.getContext().setUserId(credentials.getUserName());
        showRetryMessage = true;
        getHttpClient().getState().setCredentials(scope, credentials);
        executePostMethod(config, httpClient, postMethod);
        break;
    }
}

From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 * It does the Kerberos authentication when it has to be done through 
 * username and password. It looks in the default Kerberos domain defined 
 * in the Kerberos config file (krb5.ini or krb5.conf) if there is a valid 
 * user with those credentials. If so, it gets his/her Kerberos ticket.
 * /*from w ww  . j  a  v  a  2 s.c  o m*/
 * @param userCred username and password credentials
 *
 * @return the method result in HTTP error format
 */
public int authUsernamePassword(Credential userCred) {

    int result = HttpServletResponse.SC_UNAUTHORIZED;

    Krb5LoginModule login = null;
    userSubject = new Subject();

    logger.debug("authUsernamePassword: using username and password");

    try {

        //Create config objects and pass the credentials      
        Map state = new HashMap();
        UsernamePasswordCredentials usrpwdCred = new UsernamePasswordCredentials(userCred.getUsername(),
                userCred.getPassword());
        state.put("javax.security.auth.login.name", usrpwdCred.getUserName());
        state.put("javax.security.auth.login.password", usrpwdCred.getPassword().toCharArray());
        state.put("java.security.krb5.conf", krbini);

        if (logger.isDebugEnabled()) {
            logger.debug("Username: " + usrpwdCred.getUserName());
        }

        Map option = new HashMap();
        String isDebug = "false";
        if (logger.isDebugEnabled()) {
            isDebug = "true";
        }
        option.put("debug", isDebug);
        option.put("tryFirstPass", "true");
        option.put("useTicketCache", "false");
        option.put("doNotPrompt", "false");
        option.put("storePass", "false");
        option.put("forwardable", "true");

        login = new Krb5LoginModule();
        login.initialize(userSubject, new NegotiateCallbackHandler(), state, option);

        if (login.login()) {
            login.commit();
            logger.debug("Login commit");
            if (id == null) {
                username = usrpwdCred.getUserName();
                id = username;
            }
            logger.debug("username is ... " + id);
            result = HttpServletResponse.SC_OK;
        }
    } catch (LoginException e) {
        logger.error("LoginException while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_UNAUTHORIZED;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Exception while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return result;

}