List of usage examples for org.apache.commons.httpclient.auth AuthState getRealm
public String getRealm()
From source file:com.motorola.studio.android.common.utilities.HttpUtils.java
private InputStream getInputStreamForUrl(String url, IProgressMonitor monitor, boolean returnStream) throws IOException { SubMonitor subMonitor = SubMonitor.convert(monitor); subMonitor.beginTask(UtilitiesNLS.HttpUtils_MonitorTask_PreparingConnection, 300); StudioLogger.debug(HttpUtils.class, "Verifying proxy usage for opening http connection"); //$NON-NLS-1$ // Try to retrieve proxy configuration to use if necessary IProxyService proxyService = ProxyManager.getProxyManager(); IProxyData proxyData = null;/* w w w. j a va 2 s .c om*/ if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) { Authenticator.setDefault(new NetAuthenticator()); if (url.startsWith("https")) { proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE); StudioLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$ } else if (url.startsWith("http")) { proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE); StudioLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$ } else { StudioLogger.debug(HttpUtils.class, "Not using any proxy"); //$NON-NLS-1$ } } // Creates the http client and the method to be executed HttpClient client = null; client = new HttpClient(); // If there is proxy data, work with it if (proxyData != null) { if (proxyData.getHost() != null) { // Sets proxy host and port, if any client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort()); } if ((proxyData.getUserId() != null) && (proxyData.getUserId().trim().length() > 0)) { // Sets proxy user and password, if any Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(), proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$ client.getState().setProxyCredentials(AuthScope.ANY, cred); } } InputStream streamForUrl = null; getMethod = new GetMethod(url); getMethod.setFollowRedirects(true); // set a 30 seconds timeout HttpMethodParams params = getMethod.getParams(); params.setSoTimeout(15 * ONE_SECOND); getMethod.setParams(params); boolean trying = true; Credentials credentials = null; subMonitor.worked(100); subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_ContactingSite); do { StudioLogger.info(HttpUtils.class, "Attempting to make a connection"); //$NON-NLS-1$ // retry to connect to the site once, also set the timeout for 5 seconds HttpClientParams clientParams = client.getParams(); clientParams.setIntParameter(HttpClientParams.MAX_REDIRECTS, 1); clientParams.setSoTimeout(5 * ONE_SECOND); client.setParams(clientParams); client.executeMethod(getMethod); if (subMonitor.isCanceled()) { break; } else { AuthState authorizationState = getMethod.getHostAuthState(); String authenticationRealm = authorizationState.getRealm(); if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { StudioLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$ credentials = authenticationRealmCache.get(authenticationRealm); if (credentials == null) { StudioLogger.debug(HttpUtils.class, "Credentials not found; prompting user for login/password"); //$NON-NLS-1$ subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_WaitingAuthentication); LoginPasswordDialogCreator dialogCreator = new LoginPasswordDialogCreator(url); if (dialogCreator.openLoginPasswordDialog() == LoginPasswordDialogCreator.OK) { credentials = new UsernamePasswordCredentials(dialogCreator.getTypedLogin(), dialogCreator.getTypedPassword()); } else { // cancel pressed; stop trying trying = false; // set the monitor canceled to be able to stop process subMonitor.setCanceled(true); } } if (credentials != null) { AuthScope scope = new AuthScope(null, -1, authenticationRealm); client.getState().setCredentials(scope, credentials); } subMonitor.worked(100); } else if (getMethod.getStatusCode() == HttpStatus.SC_OK) { StudioLogger.debug(HttpUtils.class, "Http connection suceeded"); //$NON-NLS-1$ subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_RetrievingSiteContent); if ((authenticationRealm != null) && (credentials != null)) { authenticationRealmCache.put(authenticationRealm, credentials); } else { // no authentication was necessary, just work the monitor subMonitor.worked(100); } StudioLogger.info(HttpUtils.class, "Retrieving site content"); //$NON-NLS-1$ // if the stream should not be returned (ex: only testing the connection is // possible), then null will be returned if (returnStream) { streamForUrl = getMethod.getResponseBodyAsStream(); } // succeeded; stop trying trying = false; subMonitor.worked(100); } else { // unhandled return status code trying = false; subMonitor.worked(200); } } } while (trying); subMonitor.done(); return streamForUrl; }
From source file:com.esri.gpt.framework.http.HttpClientRequest.java
/** * Executes the HTTP request.//from ww w. j a v a 2 s. c o m * @throws IOException if an Exception occurs */ public void execute() throws IOException { // initialize this.executionLog.setLength(0); StringBuffer log = this.executionLog; ResponseInfo respInfo = this.getResponseInfo(); respInfo.reset(); InputStream responseStream = null; HttpMethodBase method = null; try { log.append("HTTP Client Request\n").append(this.getUrl()); // make the Apache HTTPClient HttpClient client = this.batchHttpClient; if (client == null) { client = new HttpClient(); boolean alwaysClose = Val.chkBool(Val.chkStr(ApplicationContext.getInstance().getConfiguration() .getCatalogConfiguration().getParameters().getValue("httpClient.alwaysClose")), false); if (alwaysClose) { client.setHttpConnectionManager(new SimpleHttpConnectionManager(true)); } } // setting timeout info client.getHttpConnectionManager().getParams().setConnectionTimeout(getConnectionTimeOutMs()); client.getHttpConnectionManager().getParams().setSoTimeout(getResponseTimeOutMs()); // setting retries int retries = this.getRetries(); // create the client and method, apply authentication and proxy settings method = this.createMethod(); //method.setFollowRedirects(true); if (retries > -1) { // TODO: not taking effect yet? DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, true); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler); } this.applyAuthAndProxySettings(client, this.getUrl()); // execute the method, determine basic information about the response respInfo.setResponseCode(client.executeMethod(method)); this.determineResponseInfo(method); // collect logging info if (LOGGER.isLoggable(Level.FINER)) { log.append("\n>>").append(method.getStatusLine()); log.append("\n--Request Header"); for (Header hdr : method.getRequestHeaders()) { log.append("\n ").append(hdr.getName() + ": " + hdr.getValue()); } log.append("\n--Response Header"); for (Header hdr : method.getResponseHeaders()) { log.append("\n ").append(hdr.getName() + ": " + hdr.getValue()); } //log.append(" responseCode=").append(this.getResponseInfo().getResponseCode()); //log.append(" responseContentType=").append(this.getResponseInfo().getContentType()); //log.append(" responseContentEncoding=").append(this.getResponseInfo().getContentEncoding()); //log.append(" responseContentLength=").append(this.getResponseInfo().getContentLength()); if (this.getContentProvider() != null) { String loggable = this.getContentProvider().getLoggableContent(); if (loggable != null) { log.append("\n--Request Content------------------------------------\n").append(loggable); } } } // throw an exception if an error is encountered if ((respInfo.getResponseCode() < 200) || (respInfo.getResponseCode() >= 300)) { String msg = "HTTP Request failed: " + method.getStatusLine(); if (respInfo.getResponseCode() == HttpStatus.SC_UNAUTHORIZED) { AuthState authState = method.getHostAuthState(); AuthScheme authScheme = authState.getAuthScheme(); HttpClient401Exception authException = new HttpClient401Exception(msg); authException.setUrl(this.getUrl()); authException.setRealm(authState.getRealm()); authException.setScheme(authScheme.getSchemeName()); if ((authException.getRealm() == null) || (authException.getRealm().length() == 0)) { authException.setRealm(authException.generateHostBasedRealm()); } throw authException; } else { throw new HttpClientException(respInfo.getResponseCode(), msg); } } // handle the response if (this.getContentHandler() != null) { if (getContentHandler().onBeforeReadResponse(this)) { responseStream = getResponseStream(method); if (responseStream != null) { this.getContentHandler().readResponse(this, responseStream); } } // log thre response content String loggable = this.getContentHandler().getLoggableContent(); long nBytesRead = this.getResponseInfo().getBytesRead(); long nCharsRead = this.getResponseInfo().getCharactersRead(); if ((nBytesRead >= 0) || (nCharsRead >= 0) || (loggable != null)) { log.append("\n--Response Content------------------------------------"); if (nBytesRead >= 0) log.append("\n(").append(nBytesRead).append(" bytes read)"); if (nCharsRead >= 0) log.append("\n(").append(nCharsRead).append(" characters read)"); if (loggable != null) log.append("\n").append(loggable); } } } finally { // cleanup try { if (responseStream != null) responseStream.close(); } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Unable to close HTTP response stream.", t); } try { if (method != null) method.releaseConnection(); } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Unable to release HttpMethod", t); } // log the request/response if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer(this.getExecutionLog().toString()); } } }
From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java
protected boolean doRequestedAuthentication(HttpClient client, HttpMethod method, RenderRequest request, RenderResponse response) {//from www.j av a 2 s.co m if (super.doRequestedAuthentication(client, method, request, response)) { // already handled return true; } // System.out.println("SSOWebContentPortlet.doRequestedAuthentication..."); if (method.getHostAuthState().getAuthScheme().getSchemeName().equals(BASIC_AUTH_SCHEME_NAME)) { // Basic authentication being requested String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // System.out.println("...providing basic authentication with userName: "+userName+", and password: "+password); method.setDoAuthentication(true); AuthState state = method.getHostAuthState(); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, state.getRealm(), state.getAuthScheme().getSchemeName()); client.getState().setCredentials(scope, new UsernamePasswordCredentials(userName, password)); // handled! return true; } else { log.warn("SSOWebContentPortlent.doAuthenticate() - unexpected authentication scheme: " + method.getHostAuthState().getAuthScheme().getSchemeName()); } // only know how to handle Basic authentication, in this context return false; }
From source file:org.eclipse.andmore.android.common.utilities.HttpUtils.java
private InputStream getInputStreamForUrl(String url, IProgressMonitor monitor, boolean returnStream) throws IOException { SubMonitor subMonitor = SubMonitor.convert(monitor); subMonitor.beginTask(UtilitiesNLS.HttpUtils_MonitorTask_PreparingConnection, 300); AndmoreLogger.debug(HttpUtils.class, "Verifying proxy usage for opening http connection"); //$NON-NLS-1$ // Try to retrieve proxy configuration to use if necessary IProxyService proxyService = ProxyManager.getProxyManager(); IProxyData proxyData = null;//from ww w . j ava2s .co m if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) { Authenticator.setDefault(new NetAuthenticator()); if (url.startsWith("https")) { proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE); AndmoreLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$ } else if (url.startsWith("http")) { proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE); AndmoreLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$ } else { AndmoreLogger.debug(HttpUtils.class, "Not using any proxy"); //$NON-NLS-1$ } } // Creates the http client and the method to be executed HttpClient client = null; client = new HttpClient(); // If there is proxy data, work with it if (proxyData != null) { if (proxyData.getHost() != null) { // Sets proxy host and port, if any client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort()); } if ((proxyData.getUserId() != null) && (proxyData.getUserId().trim().length() > 0)) { // Sets proxy user and password, if any Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(), proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$ client.getState().setProxyCredentials(AuthScope.ANY, cred); } } InputStream streamForUrl = null; getMethod = new GetMethod(url); getMethod.setFollowRedirects(true); // set a 30 seconds timeout HttpMethodParams params = getMethod.getParams(); params.setSoTimeout(15 * ONE_SECOND); getMethod.setParams(params); boolean trying = true; Credentials credentials = null; subMonitor.worked(100); subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_ContactingSite); do { AndmoreLogger.info(HttpUtils.class, "Attempting to make a connection"); //$NON-NLS-1$ // retry to connect to the site once, also set the timeout for 5 // seconds HttpClientParams clientParams = client.getParams(); clientParams.setIntParameter(HttpClientParams.MAX_REDIRECTS, 1); clientParams.setSoTimeout(5 * ONE_SECOND); client.setParams(clientParams); client.executeMethod(getMethod); if (subMonitor.isCanceled()) { break; } else { AuthState authorizationState = getMethod.getHostAuthState(); String authenticationRealm = authorizationState.getRealm(); if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { AndmoreLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$ credentials = authenticationRealmCache.get(authenticationRealm); if (credentials == null) { AndmoreLogger.debug(HttpUtils.class, "Credentials not found; prompting user for login/password"); //$NON-NLS-1$ subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_WaitingAuthentication); LoginPasswordDialogCreator dialogCreator = new LoginPasswordDialogCreator(url); if (dialogCreator.openLoginPasswordDialog() == LoginPasswordDialogCreator.OK) { credentials = new UsernamePasswordCredentials(dialogCreator.getTypedLogin(), dialogCreator.getTypedPassword()); } else { // cancel pressed; stop trying trying = false; // set the monitor canceled to be able to stop // process subMonitor.setCanceled(true); } } if (credentials != null) { AuthScope scope = new AuthScope(null, -1, authenticationRealm); client.getState().setCredentials(scope, credentials); } subMonitor.worked(100); } else if (getMethod.getStatusCode() == HttpStatus.SC_OK) { AndmoreLogger.debug(HttpUtils.class, "Http connection suceeded"); //$NON-NLS-1$ subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_RetrievingSiteContent); if ((authenticationRealm != null) && (credentials != null)) { authenticationRealmCache.put(authenticationRealm, credentials); } else { // no authentication was necessary, just work the // monitor subMonitor.worked(100); } AndmoreLogger.info(HttpUtils.class, "Retrieving site content"); //$NON-NLS-1$ // if the stream should not be returned (ex: only testing // the connection is // possible), then null will be returned if (returnStream) { streamForUrl = getMethod.getResponseBodyAsStream(); } // succeeded; stop trying trying = false; subMonitor.worked(100); } else { // unhandled return status code trying = false; subMonitor.worked(200); } } } while (trying); subMonitor.done(); return streamForUrl; }
From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java
private InputStream internalOpenStream(URI link, URI authLink, String authRealm, Map<Object, Object> properties) throws ConnectionException { /* Handle File Protocol at first */ if (URIUtils.FILE_SCHEME.equals(link.getScheme())) return loadFileProtocol(link); /* SSL Support */ if (URIUtils.HTTPS_SCHEME.equals(link.getScheme())) initSSLProtocol();/*from www . j a va 2s.c om*/ /* Feed Support */ if (URIUtils.FEED_SCHEME.equals(link.getScheme())) initFeedProtocol(); /* Init Client */ HttpClient client = initClient(properties); /* Init the connection */ HttpMethodBase method = null; InputStream inS = null; try { /* Create Method (GET or POST) */ method = initConnection(link, properties); /* Proxy if required */ setupProxy(link, client); /* Authentication if required */ setupAuthentication(authLink, authRealm, client, method); /* Open the connection */ inS = openConnection(client, method); /* Try to pipe the resulting stream into a GZipInputStream */ if (inS != null) inS = pipeStream(inS, method); } catch (IOException e) { abortAndRelease(method); throw new ConnectionException(Activator.getDefault().createErrorStatus(e.getMessage(), e)); } /* In case authentication required */ int statusCode = method.getStatusCode(); if (statusCode == HTTP_ERROR_AUTH_REQUIRED) { AuthState hostAuthState = method.getHostAuthState(); String realm = hostAuthState != null ? hostAuthState.getRealm() : null; abortAndRelease(method); throw new AuthenticationRequiredException(realm, Activator.getDefault() .createErrorStatus(Messages.DefaultProtocolHandler_ERROR_AUTHENTICATION_REQUIRED, null)); } /* In case sync authentication failed (Forbidden) */ else if (isSyncAuthenticationIssue(method, authLink)) { abortAndRelease(method); throw new AuthenticationRequiredException(null, Activator.getDefault() .createErrorStatus(Messages.DefaultProtocolHandler_GR_ERROR_BAD_AUTH, null)); } /* In case of Forbidden Status with Error Code (Google Reader) */ else if (statusCode == HTTP_ERROR_FORBIDDEN && method.getResponseHeader(HEADER_RESPONSE_ERROR) != null) handleForbidden(method); /* In case proxy-authentication required / failed */ else if (statusCode == HTTP_ERROR_PROXY_AUTH_REQUIRED) { abortAndRelease(method); throw new ProxyAuthenticationRequiredException(Activator.getDefault() .createErrorStatus(Messages.DefaultProtocolHandler_ERROR_PROXY_AUTHENTICATION_REQUIRED, null)); } /* If status code is 4xx, throw an IOException with the status code included */ else if (statusCode >= HTTP_ERRORS) { String error = getError(statusCode); abortAndRelease(method); if (error != null) throw new ConnectionException(Activator.getDefault() .createErrorStatus(NLS.bind(Messages.DefaultProtocolHandler_ERROR_HTTP_STATUS_MSG, String.valueOf(statusCode), error), null)); throw new ConnectionException(Activator.getDefault().createErrorStatus( NLS.bind(Messages.DefaultProtocolHandler_ERROR_HTTP_STATUS, String.valueOf(statusCode)), null)); } /* In case the Feed has not been modified since */ else if (statusCode == HTTP_STATUS_NOT_MODIFIED) { abortAndRelease(method); throw new NotModifiedException(Activator.getDefault() .createInfoStatus(Messages.DefaultProtocolHandler_INFO_NOT_MODIFIED_SINCE, null)); } /* In case response body is not available */ if (inS == null) { abortAndRelease(method); throw new ConnectionException(Activator.getDefault() .createErrorStatus(Messages.DefaultProtocolHandler_ERROR_STREAM_UNAVAILABLE, null)); } /* Check wether a Progress Monitor is provided to support early cancelation */ IProgressMonitor monitor = null; if (properties != null && properties.containsKey(IConnectionPropertyConstants.PROGRESS_MONITOR)) monitor = (IProgressMonitor) properties.get(IConnectionPropertyConstants.PROGRESS_MONITOR); /* Return a Stream that releases the connection once closed */ return new HttpConnectionInputStream(link, method, monitor, inS); }