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

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

Introduction

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

Prototype

public UsernamePasswordCredentials(String paramString1, String paramString2) 

Source Link

Usage

From source file:de.juwimm.cms.common.http.HttpClientWrapper.java

public void setHostConfiguration(HttpClient client, URL targetURL) {
    int port = targetURL.getPort();
    String host = targetURL.getHost();
    HostConfiguration config = hostMap.get(host + ":" + port);
    if (config == null) {
        config = new HostConfiguration();
        if (port == -1) {
            if (targetURL.getProtocol().equalsIgnoreCase("https")) {
                port = 443;/*from   www  . ja v a2s.  c o m*/
            } else {
                port = 80;
            }
        }
        config.setHost(host, port, targetURL.getProtocol());
    }
    // in the meantime HttpProxyUser and HttpProxyPasword might have changed
    // (DlgUsernamePassword) or now trying NTLM instead of BASE
    // authentication
    if (getHttpProxyHost() != null && getHttpProxyPort() != null && getHttpProxyHost().length() > 0
            && getHttpProxyPort().length() > 0) {
        client.getParams().setAuthenticationPreemptive(true);
        int proxyPort = new Integer(getHttpProxyPort()).intValue();
        config.setProxy(getHttpProxyHost(), proxyPort);
        if (getHttpProxyUser() != null && getHttpProxyUser().length() > 0) {
            Credentials proxyCred = null;
            if (isUseNTproxy()) {
                proxyCred = new NTCredentials(getHttpProxyUser(), getHttpProxyPassword(), getHttpProxyHost(),
                        "");
            } else {
                proxyCred = new UsernamePasswordCredentials(getHttpProxyUser(), getHttpProxyPassword());
            }
            client.getState().setProxyCredentials(AUTHSCOPE_ANY, proxyCred);

        }
    }
    hostMap.put(host + ":" + port, config);
    client.setHostConfiguration(config);

}

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private HttpClient getHttpClient() {
    HttpClient client = new HttpClient();

    client.getParams().setConnectionManagerTimeout(10 * 1000);
    client.getParams().setSoTimeout(60 * 1000);

    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxy = null;/*from ww w .j  a  v  a  2  s. co m*/
    if (jenkins != null) {
        proxy = jenkins.proxy;
    }
    if (proxy != null) {
        LOGGER.info("Jenkins proxy: " + proxy.name + ":" + proxy.port);
        client.getHostConfiguration().setProxy(proxy.name, proxy.port);
        String username = proxy.getUserName();
        String password = proxy.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.info("Using proxy authentication (user=" + username + ")");
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
        }
    }
    return client;
}

From source file:com.delmar.station.service.impl.WFDetailServiceImpl.java

public String updateDcmsFcrDate(EDIResponseInfo edirInfo, String trustFileCode) {

    String resultMessage = "success";
    Date date = new Date();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    String currentDate = sf.format(date);
    try {//from  w w  w .  j  ava 2  s . c o m
        date = sf.parse(edirInfo.getInDate());
        currentDate = sf.format(date);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    try {

        EDIResponseInfo resultEDIResponseInfo = ediResponseInfoService.getEDIRByTrustFileCode(trustFileCode);

        // Booking IDCargoProDcms????bookingID
        if (StringUtil.isNotEmpty(resultEDIResponseInfo.getCsReferenceNo())) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", resultEDIResponseInfo.getCsReferenceNo());
            params.put("fcrDate", currentDate);
            params.put("remark", edirInfo.getResponseDesc());
            HttpClient httpClient = null;
            httpClient.getParams().setAuthenticationPreemptive(true);

            // ?
            Credentials credentials = new UsernamePasswordCredentials("wsuserchina", "ws1sGreat");
            httpClient.getState().setCredentials(AuthScope.ANY, credentials);

            HttpMethod method = buildPostMethod(
                    "https://www.delmarcargo.com/cms/api/bookingservice/updateBookingFcrDate", params);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                throw new HttpException(method.getStatusText());
            }
            String xmlResult = method.getResponseBodyAsString();
            method.releaseConnection();

            //   
            StringReader xmlReader = new StringReader(xmlResult);
            // ?SAX ? InputSource ?? XML   
            InputSource xmlSource = new InputSource(xmlReader);
            // SAXBuilder  
            SAXReader builder = new SAXReader();
            // ?SAXDocument
            Document doc = builder.read(xmlSource);
            // 
            Element root = doc.getRootElement();
            // BODY 
            Element resultStatusCode = root.element("ServiceResponse").element("statusCode");

            // ????
            if ("200".equals(resultStatusCode.getText())) {
                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("1");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);

                ediResponseInfoService.updateTrustFileInfoFCRDate(currentDate, edirInfo.getTrustFileCode());
            } else if ("405".equals(resultStatusCode.getText())) {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();

                // add
                edirInfo.setEdiType("DCMS_FCRDATE");
                edirInfo.setEdiStatus("11");
                edirInfo.setCsReferenceNo(resultEDIResponseInfo.getCsReferenceNo());// set Booking Id
                edirInfo.setEdiAction("NEW");
                edirInfo.setEdiStatus("1");
                edirInfo.setBatchNo("0");
                edirInfo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setUpdateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                edirInfo.setBeUse(0);
                ediResponseInfoService.saveOrUpdate(edirInfo);
            } else {
                Element resultText = root.element("ServiceResponse").element("description");
                resultMessage = resultText.getText();
            }
        } else {
            resultMessage = "Booking IDCargoProDcms?";
        }
    } catch (Exception e) {
        e.printStackTrace();
        resultMessage = "Modify Dcms Fcr Date have Exception";
        return resultMessage;
    }

    return resultMessage;
}

From source file:net.sourceforge.eclipsetrader.yahoo.ItalianNewsProvider.java

private void update(URL feedUrl, Security security) {
    Calendar limit = Calendar.getInstance();
    limit.add(Calendar.DATE,/*from   www  .  ja  v a  2s.co  m*/
            -CorePlugin.getDefault().getPreferenceStore().getInt(CorePlugin.PREFS_NEWS_DATE_RANGE));

    boolean subscribersOnly = YahooPlugin.getDefault().getPreferenceStore()
            .getBoolean(YahooPlugin.PREFS_SHOW_SUBSCRIBERS_ONLY);
    log.debug(feedUrl);

    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(feedUrl.getHost(), IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        SyndFeed feed = fetcher.retrieveFeed(feedUrl, client);
        for (Iterator iter = feed.getEntries().iterator(); iter.hasNext();) {
            SyndEntry entry = (SyndEntry) iter.next();

            if (!subscribersOnly && entry.getTitle().indexOf("[$$]") != -1) //$NON-NLS-1$
                continue;

            NewsItem news = new NewsItem();
            news.setRecent(true);

            String title = entry.getTitle();
            if (title.endsWith(")")) //$NON-NLS-1$
            {
                int s = title.lastIndexOf('(');
                if (s != -1) {
                    news.setSource(title.substring(s + 1, title.length() - 1));
                    title = title.substring(0, s - 1).trim();
                }
            }
            news.setTitle(decode(title));

            news.setUrl(entry.getLink());

            Date entryDate = entry.getPublishedDate();
            if (entry.getUpdatedDate() != null)
                entryDate = entry.getUpdatedDate();
            if (entryDate != null) {
                Calendar date = Calendar.getInstance();
                date.setTime(entryDate);
                date.set(Calendar.SECOND, 0);
                date.set(Calendar.MILLISECOND, 0);
                news.setDate(date.getTime());
            }

            if (security != null)
                news.addSecurity(security);

            if (!news.getDate().before(limit.getTime()) && !isDuplicated(news)) {
                log.trace(news.getTitle() + " (" + news.getSource() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
                CorePlugin.getRepository().save(news);
                oldItems.add(news);
            }
        }
    } catch (Exception e) {
        CorePlugin.logException(e);
    }
}

From source file:easyshop.downloadhelper.HttpPageGetter.java

public HttpPage getAuthWebPage(String urlStr, HttpClient client, String userName, String password) {
    PageRef ref = new PageRef(urlStr);
    if (client != null) {
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(userName, password);
        client.getState().setCredentials(new AuthScope("taobao.com", 80, AuthScope.ANY_REALM), defaultcreds);
    }/*w w w  .ja va 2 s. c  o m*/
    return getHttpPage(ref, client);
}

From source file:com.mirth.connect.connectors.ws.WebServiceMessageDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires
 * authentication, then the WSDL is saved as a temp file and the URL for
 * that file is returned./*from ww  w.j  a v  a2  s. c  o  m*/
 * 
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(String wsdlUrl, String username, String password) throws Exception {
    URI uri = new URI(wsdlUrl);

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(wsdlUrl);

        int status = client.executeMethod(method);
        if ((status == HttpStatus.SC_UNAUTHORIZED) && (username != null) && (password != null)) {
            client.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            status = client.executeMethod(method);

            if (status == HttpStatus.SC_OK) {
                String wsdl = method.getResponseBodyAsString();
                File tempFile = File.createTempFile("WebServiceSender", ".wsdl");
                tempFile.deleteOnExit();

                FileUtils.writeStringToFile(tempFile, wsdl);

                return tempFile.toURI().toURL();
            }
        }
    }

    return uri.toURL();
}

From source file:com.ms.commons.test.classloader.util.SimpleAntxLoader.java

protected int readHttpResource(String svnUrl, String file, StringBuilder outContent) {

    if ((svnUrl != null) && svnUrl.startsWith("/") && (new File(svnUrl + "/" + file)).exists()) {
        try {//from  w w  w. j av  a 2 s.c  o  m
            outContent.append(FileUtils.readFileToString(new File(svnUrl + "/" + file)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return 200;
    }

    SvnUrl url = SvnUrl.parse(svnUrl + file);
    if (url == null) {
        return -1;
    }

    int cacheStatus = readCacheFile(svnUrl, file, outContent);
    if (cacheStatus == 200) {
        return cacheStatus;
    }

    this.preparePassword(url);

    Credentials credentials = new UsernamePasswordCredentials(url.getUserName(), this.password);
    AuthScope authScope = new AuthScope(url.getHost(), 80, AuthScope.ANY_REALM);

    HttpClient client = new HttpClient();
    client.getState().setCredentials(authScope, credentials);

    System.out.println("Read HTTP resource:" + url.getFullUrl());
    client.getParams().setConnectionManagerTimeout(30 * 1000);
    client.getParams().setSoTimeout(30 * 1000);

    HttpMethod httpMethod = new GetMethod(url.getFullUrl());

    int statusCode = 0;
    try {
        statusCode = client.executeMethod(httpMethod);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (statusCode == 200) {
        String content = null;
        try {
            content = httpMethod.getResponseBodyAsString();
            outContent.append(content);
        } catch (IOException e) {
            e.printStackTrace();
        }

        writeCacheFile(svnUrl, file, outContent.toString());
    }

    return statusCode;
}

From source file:com.legstar.http.client.CicsHttp.java

/**
 * Create a state with the given credentials. A state persists from
 * request to request./*from  w ww  .  ja v  a 2 s . co  m*/
 * @param host the host name
 * @param port the port number
 * @param userid the host user id
 * @param password the host password
 * @param realm the host realm
 * @return a new HTTP State
 */
protected HttpState createHttpState(final String host, final int port, final String userid,
        final String password, final String realm) {

    if (_log.isDebugEnabled()) {
        _log.debug("enter createHttpState");
    }

    HttpState httpState = new HttpState();

    /* If there are no credentials, assume the server might have
     * been setup without basic authentication. */
    if (password == null || password.length() == 0) {
        return httpState;
    }

    /* Username and password will be used as basic authentication
     *  credentials */
    UsernamePasswordCredentials upc = new UsernamePasswordCredentials(userid, password);
    httpState.setCredentials(new AuthScope(host, port, (realm == null || realm.length() == 0) ? null : realm,
            AuthScope.ANY_SCHEME), upc);
    return httpState;
}

From source file:com.novell.ldap.DsmlConnection.java

public void bind(String binddn, String password) throws LDAPException {
    if (isBound) {
        //first clear old credentials on server
        GetMethod get = new GetMethod(this.serverString + "?clearbind");
        try {/*from www .  ja va  2 s .c  o m*/
            con.executeMethod(get);

        } catch (HttpException e) {

        } catch (IOException e) {

        }
    }
    //set the credentials globaly
    this.isBound = false;
    con.getState().setCredentials(null, null, new UsernamePasswordCredentials(binddn, password));
    //try's to connect in order to bind...
    this.search("", LDAPConnection.SCOPE_BASE, "(objectClass=*)", new String[] { "1.1" }, false);
    this.isBound = true;
}

From source file:com.sittinglittleduck.DirBuster.Manager.java

private void setpUpHttpClient() {
    if (httpclient != null) {
        // add the proxy setting is required
        if (this.isUseProxy()) {
            httpclient.getHostConfiguration().setProxy(this.getProxyHost(), this.getProxyPort());
            if (this.isUseProxyAuth()) {
                httpclient.getState().setProxyCredentials(this.getProxyRealm(), this.getProxyHost(),
                        new UsernamePasswordCredentials(this.getProxyUsername(), this.getProxyPassword()));
            }//w w  w.j  a va2s .  c  o  m
        }

        httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(Config.connectionTimeout * 1000);
        httpclient.setState(initialState);
        httpclient.getParams().setParameter("http.useragent", Config.userAgent);

        /*
         * Code to deal with http auth
         *
         */

        if (useHTTPauth) {
            // Credentials creds = new Credentials();
            // creds.
            NTCredentials ntCreds = new NTCredentials(this.userName, this.password, "", this.realmDomain);
            httpclient.getState().setCredentials(AuthScope.ANY, ntCreds);
        }

        /*
         * Custom code to add ntlm auth
         */

        // NTCredentials ntCreds = new NTCredentials("username", "password", "", "");
        // httpclient.getState().setCredentials(AuthScope.ANY, ntCreds);
    }
}