List of usage examples for org.apache.commons.httpclient HttpState setCredentials
public void setCredentials(AuthScope paramAuthScope, Credentials paramCredentials)
From source file:BasicAuthenticationForJSPPage.java
public static void main(String args[]) throws Exception { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "My Browser"); HostConfiguration host = client.getHostConfiguration(); host.setHost(new URI("http://localhost:8080", true)); Credentials credentials = new UsernamePasswordCredentials("tomcat", "tomcat"); AuthScope authScope = new AuthScope(host.getHost(), host.getPort()); HttpState state = client.getState(); state.setCredentials(authScope, credentials); GetMethod method = new GetMethod("/commons/chapter01/protected.jsp"); try {//w w w. j av a2 s . co m client.executeMethod(host, method); System.err.println(method.getStatusLine()); System.err.println(method.getResponseBodyAsString()); } catch (Exception e) { System.err.println(e); } finally { method.releaseConnection(); } }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpAuthenticationRequestFilter.java
public static void initRequestCredentials(SubmitContext context, String username, Settings settings, String password, String domain) { HttpClient httpClient = (HttpClient) context.getProperty(BaseHttpRequestTransport.HTTP_CLIENT); HttpMethod httpMethod = (HttpMethod) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD); if (StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)) { httpClient.getParams().setAuthenticationPreemptive(false); httpMethod.setDoAuthentication(false); } else {/* w w w . j a va2s. c o m*/ // set preemptive authentication if (settings.getBoolean(HttpSettings.AUTHENTICATE_PREEMPTIVELY)) { httpClient.getParams().setAuthenticationPreemptive(true); HttpState state = (HttpState) context.getProperty(SubmitContext.HTTP_STATE_PROPERTY); if (state != null) { Credentials defaultcreds = new UsernamePasswordCredentials(username, password == null ? "" : password); state.setCredentials(AuthScope.ANY, defaultcreds); } } else { httpClient.getParams().setAuthenticationPreemptive(false); } httpMethod.getParams().setParameter(CredentialsProvider.PROVIDER, new UPDCredentialsProvider(username, password, domain)); httpMethod.setDoAuthentication(true); } }
From source file:com.liferay.portal.search.solr.server.BasicAuthSolrServer.java
public BasicAuthSolrServer(AuthScope authScope, String username, String password, String url) throws MalformedURLException { _username = username;/* w w w.j a v a 2 s .co m*/ _password = password; _multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpClient httpClient = new HttpClient(_multiThreadedHttpConnectionManager); if ((_username != null) && (_password != null)) { if (authScope == null) { authScope = AuthScope.ANY; } HttpState httpState = httpClient.getState(); httpState.setCredentials(authScope, new UsernamePasswordCredentials(_username, _password)); HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setAuthenticationPreemptive(true); } _server = new CommonsHttpSolrServer(url, httpClient); }
From source file:com.rallydev.integration.build.rest.RallyRestServiceTest.java
public void testRallyRestServiceBuildSuccessWithProxyAndAuth() throws Exception { MockControl httpStateMockControl1;/*from www. ja v a2s. c om*/ HttpState httpStateMock1; httpStateMockControl1 = MockClassControl.createControl(HttpState.class); httpStateMock1 = (HttpState) httpStateMockControl1.getMock(); httpStateMock1.setCredentials(new AuthScope("host", -1, null), new UsernamePasswordCredentials("user", "password")); httpStateMock1.setProxyCredentials(new AuthScope("proxyserver.mycompany.com", 3128, null), new UsernamePasswordCredentials("user@rallydev.com", "password")); httpStateMockControl1.replay(); String xml = readFile(BUILD_SUCCESS_FILE); httpClientMockControl.expectAndReturn(httpClientMock.getHostConfiguration(), hostConfigurationMock); hostConfigurationMock.setProxy("proxyserver.mycompany.com", 3128); httpClientMockControl.expectAndReturn(httpClientMock.getState(), httpStateMock1); httpClientMockControl.expectAndReturn(httpClientMock.executeMethod(postMethodMock), HttpStatus.SC_OK); postMethodMockControl.expectAndReturn(postMethodMock.getResponseBodyAsStream(), readFileAsStream(BUILD_SUCCESS_RESPONSE_FILE)); postMethodMock.releaseConnection(); httpClientMockControl.replay(); postMethodMockControl.replay(); hostConfigurationMockControl.replay(); rallyRestService.setProxyInfo("proxyserver.mycompany.com", 3128, "user@rallydev.com", "password"); String response = rallyRestService.doCreate(xml, httpClientMock, postMethodMock); assertEquals(readFile(BUILD_SUCCESS_RESPONSE_FILE), response); httpStateMockControl.verify(); hostConfigurationMockControl.verify(); verify(); }
From source file:com.liferay.lotus.repository.LotusNotesRepository.java
@Override public int getExtRepositoryObjectsCount( ExtRepositoryObjectType<? extends ExtRepositoryObject> extRepositoryObjectType, String extRepositoryFolderKey) throws SystemException { try {/*from w w w .ja v a2 s. c om*/ HttpClient httpClient = new HttpClient(); HttpState state = httpClient.getState(); state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("Mate matet_000", "liferay")); GetMethod getMethod = new GetMethod("http://172.16.22.196/log.nsf/api/data/documents"); getMethod.setDoAuthentication(true); httpClient.executeMethod(getMethod); String response = getMethod.getResponseBodyAsString(); JSONArray jsonArray = JSONFactoryUtil.createJSONArray(response); return jsonArray.length(); } catch (JSONException e) { throw new SystemException(e); } catch (HttpException e) { throw new SystemException(e); } catch (IOException e) { throw new SystemException(e); } }
From source file:com.liferay.lotus.repository.LotusNotesRepository.java
@Override public <T extends ExtRepositoryObject> List<T> getExtRepositoryObjects( ExtRepositoryObjectType<T> extRepositoryObjectType, String extRepositoryFolderKey) throws SystemException { try {//w ww. j ava 2s . com if (extRepositoryObjectType == ExtRepositoryObjectType.FOLDER) { return Collections.emptyList(); } HttpClient httpClient = new HttpClient(); HttpState state = httpClient.getState(); state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("Mate matet_000", "liferay")); GetMethod getMethod = new GetMethod("http://172.16.22.196/log.nsf/api/data/documents"); getMethod.setDoAuthentication(true); httpClient.executeMethod(getMethod); String response = getMethod.getResponseBodyAsString(); JSONArray jsonArray = JSONFactoryUtil.createJSONArray(response); List<LotusNotesFileEntry> items = new ArrayList<LotusNotesFileEntry>(); for (int i = 0; i < jsonArray.length(); i++) { items.add(new LotusNotesFileEntry(jsonArray.getJSONObject(i))); } return (List<T>) items; } catch (JSONException e) { throw new SystemException(e); } catch (HttpException e) { throw new SystemException(e); } catch (IOException e) { throw new SystemException(e); } }
From source file:com.zimbra.cs.dav.client.WebDavClient.java
public void setCredential(String user, String pass) { mUsername = user;/*w w w. j a v a 2 s. co m*/ mPassword = pass; HttpState state = new HttpState(); Credentials cred = new UsernamePasswordCredentials(mUsername, mPassword); state.setCredentials(AuthScope.ANY, cred); mClient.setState(state); ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthPolicy.BASIC); mClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); mClient.getParams().setAuthenticationPreemptive(true); }
From source file:be.fedict.trust.Credentials.java
/** * Initializes the Commons HTTPClient state using the credentials stores in * this credential store./*from ww w. j a v a 2 s . co m*/ * * @param httpState */ public void init(HttpState httpState) { for (Credential credential : this.credentials) { AuthScope authScope = new AuthScope(credential.getHost(), credential.getPort(), credential.getRealm(), credential.getScheme()); UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( credential.getUsername(), credential.getPassword()); httpState.setCredentials(authScope, usernamePasswordCredentials); } }
From source file:com.rometools.fetcher.impl.HttpClientFeedFetcher.java
@Override public SyndFeed retrieveFeed(final String userAgent, final URL feedUrl) throws IllegalArgumentException, IOException, FeedException, FetcherException { if (feedUrl == null) { throw new IllegalArgumentException("null is not a valid URL"); }//w ww. jav a2 s . co m final HttpClient client = new HttpClient(httpClientParams); if (credentialSupplier != null) { final HttpClientParams params = client.getParams(); params.setAuthenticationPreemptive(true); final String host = feedUrl.getHost(); final Credentials credentials = credentialSupplier.getCredentials(null, host); if (credentials != null) { final AuthScope authScope = new AuthScope(host, -1); final HttpState state = client.getState(); state.setCredentials(authScope, credentials); } } System.setProperty("httpclient.useragent", userAgent); final String urlStr = feedUrl.toString(); final HttpMethod method = new GetMethod(urlStr); if (customRequestHeaders == null) { method.addRequestHeader("Accept-Encoding", "gzip"); method.addRequestHeader("User-Agent", userAgent); } else { for (final Map.Entry<String, String> entry : customRequestHeaders.entrySet()) { method.addRequestHeader(entry.getKey(), entry.getValue()); } if (!customRequestHeaders.containsKey("Accept-Encoding")) { method.addRequestHeader("Accept-Encoding", "gzip"); } if (!customRequestHeaders.containsKey("User-Agent")) { method.addRequestHeader("User-Agent", userAgent); } } method.setFollowRedirects(true); if (httpClientMethodCallback != null) { synchronized (httpClientMethodCallback) { httpClientMethodCallback.afterHttpClientMethodCreate(method); } } final FeedFetcherCache cache = getFeedInfoCache(); if (cache != null) { // retrieve feed try { if (isUsingDeltaEncoding()) { method.setRequestHeader("A-IM", "feed"); } // try to get the feed info from the cache SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl); if (syndFeedInfo != null) { method.setRequestHeader("If-None-Match", syndFeedInfo.getETag()); final Object lastModifiedHeader = syndFeedInfo.getLastModified(); if (lastModifiedHeader instanceof String) { method.setRequestHeader("If-Modified-Since", (String) lastModifiedHeader); } } final int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode); syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode); cache.setFeedInfo(feedUrl, syndFeedInfo); // the feed may have been modified to pick up cached values // (eg - for delta encoding) feed = syndFeedInfo.getSyndFeed(); return feed; } finally { method.releaseConnection(); } } else { // cache is not in use try { final int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); return getFeed(null, urlStr, method, statusCode); } finally { method.releaseConnection(); } } }
From source file:com.zimbra.cs.zimlet.ProxyServlet.java
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException { ZimbraLog.clearContext();/*from ww w .j ava 2 s . c o m*/ boolean isAdmin = isAdminRequest(req); AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true); if (authToken == null) { String zAuthToken = req.getParameter(QP_ZAUTHTOKEN); if (zAuthToken != null) { try { authToken = AuthProvider.getAuthToken(zAuthToken); if (authToken.isExpired()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired"); return; } if (!authToken.isRegistered()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid"); return; } if (isAdmin && !authToken.isAdmin()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied"); return; } } catch (AuthTokenException e) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken"); return; } } } if (authToken == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie"); return; } // get the posted body before the server read and parse them. byte[] body = copyPostedData(req); // sanity check String target = req.getParameter(TARGET_PARAM); if (target == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // check for permission URL url = new URL(target); if (!isAdmin && !checkPermissionOnTarget(url, authToken)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // determine whether to return the target inline or store it as an upload String uploadParam = req.getParameter(UPLOAD_PARAM); boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true")); HttpMethod method = null; try { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); String reqMethod = req.getMethod(); if (reqMethod.equalsIgnoreCase("GET")) { method = new GetMethod(target); } else if (reqMethod.equalsIgnoreCase("POST")) { PostMethod post = new PostMethod(target); if (body != null) post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = post; } else if (reqMethod.equalsIgnoreCase("PUT")) { PutMethod put = new PutMethod(target); if (body != null) put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = put; } else if (reqMethod.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(target); } else { ZimbraLog.zimlet.info("unsupported request method: " + reqMethod); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // handle basic auth String auth, user, pass; auth = req.getParameter(AUTH_PARAM); user = req.getParameter(USER_PARAM); pass = req.getParameter(PASS_PARAM); if (auth != null && user != null && pass != null) { if (!auth.equals(AUTH_BASIC)) { ZimbraLog.zimlet.info("unsupported auth type: " + auth); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); client.setState(state); method.setDoAuthentication(true); } Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String hdr = (String) headers.nextElement(); ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr)); if (canProxyHeader(hdr)) { ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr)); if (hdr.equalsIgnoreCase("x-host")) method.getParams().setVirtualHost(req.getHeader(hdr)); else method.addRequestHeader(hdr, req.getHeader(hdr)); } } try { if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) { method.setFollowRedirects(true); } HttpClientUtil.executeMethod(client, method); } catch (HttpException ex) { ZimbraLog.zimlet.info("exception while proxying " + target, ex); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode(); // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line Header ctHeader = method.getResponseHeader("Content-Type"); String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue(); InputStream targetResponseBody = method.getResponseBodyAsStream(); if (asUpload) { String filename = req.getParameter(FILENAME_PARAM); if (filename == null || filename.equals("")) filename = new ContentType(contentType).getParameter("name"); if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null) filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()) .getParameter("filename"); if (filename == null || filename.equals("")) filename = "unknown"; List<Upload> uploads = null; if (targetResponseBody != null) { try { Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId()); uploads = Arrays.asList(up); } catch (ServiceException e) { if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED)) status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE; else status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } resp.setStatus(status); FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null); } else { resp.setStatus(status); resp.setContentType(contentType); for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName())) resp.addHeader(h.getName(), h.getValue()); if (targetResponseBody != null) ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true); } } finally { if (method != null) method.releaseConnection(); } }