List of usage examples for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED
int SC_UNAUTHORIZED
To view the source code for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.
Click Source Link
From source file:org.pentaho.pac.server.common.ThreadSafeHttpClient.java
/** * Execute the <param>method</param>, and return the server's response as a string * @param method the HttpMethod specifying the server URL and parameters to be * passed to the server./*from w ww.j a v a 2 s . com*/ * @return a string containing the server's response * * @throws ProxyException if the attempt to communicate with the server fails, * if the attempt to read the response from the server fails, if the response * stream is unable to be converted into a String. */ private String executeMethod(HttpMethod method) throws ProxyException { InputStream responseStrm = null; try { int httpStatus = CLIENT.executeMethod(method); if (httpStatus != HttpStatus.SC_OK) { // If the response comes as unauthorized access we will throw a proxy exception explaining the reason and // what needs to be done to correct it if (httpStatus == HttpStatus.SC_UNAUTHORIZED) { throw new ProxyException( Messages.getErrorString("ThreadSafeHttpClient.ERROR_0003_AUTHORIZATION_FAILED")); } String status = method.getStatusLine().toString(); String uri = method.getURI().toString(); String errorMsg = Messages.getErrorString("ThreadSafeHttpClient.ERROR_0001_CLIENT_REQUEST_FAILED", //$NON-NLS-1$ uri, status); logger.error(errorMsg); throw new ProxyException(status); // TODO } responseStrm = method.getResponseBodyAsStream(); // trim() is necessary because some jsp's put \n\r at the beginning of // the returned text, and the xml processor chokes on \n\r at the beginning. String response = IOUtils.toString(responseStrm).trim(); return response; } catch (Exception e) { throw new ProxyException(e); } finally { method.releaseConnection(); } }
From source file:org.pentaho.platform.util.client.PublisherUtil.java
/** * Publishes a list of files and a datasource to the server with basic authentication to the server * /* w ww . j a v a2 s. com*/ * @param publishURL * The URL of the Pentaho server * @param publishPath * The path in the solution to place the files * @param publishFiles * Array of File objects to post to the server * @param dataSource * The datasource to publish to the server * @param publishPassword * The publishing password for the server * @param serverUserid * The userid to authenticate to the server * @param serverPassword * The password to authenticate with the server * @param overwrite * Whether the server should overwrite the file if it exists already * @param mkdirs * Whether the server should create any missing folders on the publish path * @return Server response as a string */ public static int publish(final String publishURL, final String publishPath, final File[] publishFiles, final String publishPassword, final String serverUserid, final String serverPassword, final boolean overwrite, final boolean mkdirs) { int status = -1; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "warn"); //$NON-NLS-1$ //$NON-NLS-2$ System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "warn"); //$NON-NLS-1$ //$NON-NLS-2$ String fullURL = null; try { fullURL = publishURL + "?publishPath=" + URLEncoder.encode(publishPath, "UTF-8"); } catch (UnsupportedEncodingException e) { fullURL = publishURL + "?publishPath=" + publishPath; } if (publishPassword == null) { throw new IllegalArgumentException( Messages.getInstance().getErrorString("PUBLISHERUTIL.ERROR_0001_PUBLISH_PASSWORD_REQUIRED")); //$NON-NLS-1$ } fullURL += "&publishKey=" + PublisherUtil.getPasswordKey(publishPassword); //$NON-NLS-1$ fullURL += "&overwrite=" + overwrite; //$NON-NLS-1$ fullURL += "&mkdirs=" + mkdirs; //$NON-NLS-1$ PostMethod filePost = new PostMethod(fullURL); Part[] parts = new Part[publishFiles.length]; for (int i = 0; i < publishFiles.length; i++) { try { File file = publishFiles[i]; FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String reportNameEncoded = (URLEncoder.encode(file.getName(), "UTF-8")); ByteArrayPartSource source = new ByteArrayPartSource(reportNameEncoded, out.toByteArray()); parts[i] = new FilePart(reportNameEncoded, source, FilePart.DEFAULT_CONTENT_TYPE, "UTF-8"); } catch (Exception e) { PublisherUtil.logger.error(null, e); } } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); try { // If server userid/password was supplied, use basic authentication to // authenticate with the server. if ((serverUserid != null) && (serverUserid.length() > 0) && (serverPassword != null) && (serverPassword.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(serverUserid, serverPassword); client.getState().setCredentials(AuthScope.ANY, creds); client.getParams().setAuthenticationPreemptive(true); } status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { String postResult = filePost.getResponseBodyAsString(); if (postResult != null) { try { return Integer.parseInt(postResult.trim()); } catch (NumberFormatException e) { PublisherUtil.logger.error(null, e); return PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } } else if (status == HttpStatus.SC_UNAUTHORIZED) { return PublisherUtil.FILE_ADD_INVALID_USER_CREDENTIALS; } } catch (HttpException e) { PublisherUtil.logger.error(null, e); } catch (IOException e) { PublisherUtil.logger.error(null, e); } // return Messages.getString("REPOSITORYFILEPUBLISHER.USER_PUBLISHER_FAILED"); //$NON-NLS-1$ return PublisherUtil.FILE_ADD_FAILED; }
From source file:org.pentaho.pms.schema.security.SecurityService.java
/** * Contact the server and get back the content as XML * /*from w w w. j a v a 2s . c om*/ * @return the requested security reference information * @throws Exception * in case something goes awry */ public Node getContentFromServer(String urlToUse) throws PentahoMetadataException { String result = null; int status = -1; URL tempURL; try { // verify the URL is syntactically correct; we will use these pieces later in this method tempURL = new URL(urlToUse); } catch (MalformedURLException e) { String msg = Messages.getString("SecurityService.ERROR_0002_INVALID_URL", urlToUse, e.getMessage()); //$NON-NLS-1$ log.logError(msg, e); throw new PentahoMetadataException(msg, e); } HttpClient client = new HttpClient(); log.logDebug(Messages.getString("SecurityService.INFO_CONNECTING_TO_URL", urlToUse)); //$NON-NLS-1$ // Assume we are using a proxy if proxyHostName is set? // TODO: Mod ui to include check for enable or disable proxy; rather than rely on proxyhostname (post v1) if ((proxyHostname != null) && (proxyHostname.trim().length() > 0)) { int port = (proxyPort == null) || (proxyPort.trim().length() == 0) ? client.getHostConfiguration().getPort() : Integer.parseInt(proxyPort); // TODO: Where to set nonProxyHosts? client.getHostConfiguration().setProxy(proxyHostname, port); // TODO: Credentials for proxy will be added if demand shows for it (post v1) // if (username != null && username.length() > 0) { // client.getState().setProxyCredentials(AuthScope.ANY, // new UsernamePasswordCredentials(username, password != null ? password : new String())); // } } // If server userid/password was supplied, use basic authentication to // authenticate with the server. if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) { Credentials creds = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(tempURL.getHost(), tempURL.getPort()), creds); client.getParams().setAuthenticationPreemptive(true); } // Get a stream for the specified URL GetMethod getMethod = new GetMethod(urlToUse); try { status = client.executeMethod(getMethod); if (status == HttpStatus.SC_OK) { log.logDetailed(Messages.getString("SecurityService.INFO_START_READING_WEBSERVER_REPLY")); //$NON-NLS-1$ result = getMethod.getResponseBodyAsString(); log.logBasic(Messages.getString("SecurityService.INFO_FINISHED_READING_RESPONSE", //$NON-NLS-1$ Integer.toString(result.length()))); } else if (status == HttpStatus.SC_UNAUTHORIZED) { String msg = Messages.getString("SecurityService.ERROR_0009_UNAUTHORIZED_ACCESS_TO_URL", urlToUse); //$NON-NLS-1$ log.logError(msg); throw new PentahoMetadataException(msg); } } catch (HttpException e) { String msg = Messages.getString("SecurityService.ERROR_0003_CANT_SAVE_IO_ERROR", e.getMessage()); //$NON-NLS-1$ log.logError(msg); log.logError(Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } catch (IOException e) { String msg = Messages.getString("SecurityService.ERROR_0004_ERROR_RETRIEVING_FILE_FROM_HTTP", //$NON-NLS-1$ e.getMessage()); // log.logError(toString(), msg); // log.logError(toString(), Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } if (result != null) { // Get the result back... Document doc; try { doc = XMLHandler.loadXMLString(result); } catch (KettleXMLException e) { String msg = Messages.getString("SecurityService.ERROR_0008_ERROR_PARSING_XML", e.getMessage()); //$NON-NLS-1$ log.logError(msg); log.logError(Const.getStackTracker(e)); throw new PentahoMetadataException(msg, e); } if (serviceURL.endsWith("ServiceAction")) { Node envelope = XMLHandler.getSubNode(doc, "SOAP-ENV:Envelope"); //$NON-NLS-1$ if (envelope != null) { Node body = XMLHandler.getSubNode(envelope, "SOAP-ENV:Body"); //$NON-NLS-1$ if (body != null) { Node response = XMLHandler.getSubNode(body, "ExecuteActivityResponse"); //$NON-NLS-1$ if (response != null) { Node content = XMLHandler.getSubNode(response, "content"); //$NON-NLS-1$ return content; } } } } else { return doc.getFirstChild(); } } return null; }
From source file:org.picketlink.test.authentication.web.BasicAuthenticationSchemeTestCase.java
@Test @OperateOnDeployment("default") public void testSuccessfulAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); WebResponse response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); String authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate"); assertNotNull(authenticateHeader);//from ww w .java 2 s . c om assertTrue(authenticateHeader.contains("Basic realm=\"Test Realm\"")); prepareAuthenticationRequest(request, DEFAULT_USERNAME, DEFAULT_USER_PASSWD); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); request.setUrl(getContextPath()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Index Page", response.getContentAsString()); request.setUrl(getProtectedResourceURL()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); }
From source file:org.picketlink.test.authentication.web.BasicAuthenticationSchemeTestCase.java
@Test @OperateOnDeployment("default") public void testUnsuccessfulAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); WebResponse response = client.loadWebResponse(request); prepareAuthenticationRequest(request, DEFAULT_USERNAME, "bad_passwd"); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); }
From source file:org.picketlink.test.authentication.web.BasicAuthenticationSchemeTestCase.java
@Test @OperateOnDeployment("force-reauthentication") public void testReAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); WebResponse response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); String authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate"); assertNotNull(authenticateHeader);/*from w ww .ja v a 2s. co m*/ assertTrue(authenticateHeader.contains("Basic realm=\"Test Realm\"")); prepareAuthenticationRequest(request, DEFAULT_USERNAME, DEFAULT_USER_PASSWD); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); request.setUrl(getContextPath()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Index Page", response.getContentAsString()); prepareAuthenticationRequest(request, "john", "bad_passwd"); request.setUrl(getProtectedResourceURL()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); }
From source file:org.picketlink.test.authentication.web.BasicAuthenticationSchemeTestCase.java
@Test @OperateOnDeployment("stateless-reauthentication") public void testStatelessAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); WebResponse response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); String authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate"); assertNotNull(authenticateHeader);/*from ww w . j a v a2 s. c o m*/ assertTrue(authenticateHeader.contains("Basic realm=\"Test Realm\"")); prepareAuthenticationRequest(request, DEFAULT_USERNAME, DEFAULT_USER_PASSWD); response = client.loadWebResponse(request); assertNull(client.getCookieManager().getCookie(SESSION_HEADER_NAME.toUpperCase())); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); request = new WebRequestSettings(getProtectedResourceURL()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); assertNull(client.getCookieManager().getCookie(SESSION_HEADER_NAME.toUpperCase())); }
From source file:org.picketlink.test.authentication.web.BasicAuthenticationSchemeTestCase.java
@Test @OperateOnDeployment("default") public void testStatefulAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); WebResponse response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); String authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate"); assertNotNull(authenticateHeader);//w w w . ja v a 2 s .c om assertTrue(authenticateHeader.contains("Basic realm=\"Test Realm\"")); prepareAuthenticationRequest(request, DEFAULT_USERNAME, DEFAULT_USER_PASSWD); response = client.loadWebResponse(request); assertNotNull(client.getCookieManager().getCookie(SESSION_HEADER_NAME.toUpperCase())); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); request = new WebRequestSettings(getProtectedResourceURL()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); assertNotNull(client.getCookieManager().getCookie(SESSION_HEADER_NAME.toUpperCase())); }
From source file:org.picketlink.test.authentication.web.DigestAuthenticationSchemeTestCase.java
@Test public void testSuccessfulAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); WebResponse response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); String authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate"); assertNotNull(authenticateHeader);/*from ww w .j ava 2 s .c o m*/ assertTrue(authenticateHeader.contains("Digest realm=\"Test Realm\"")); prepareAuthenticationRequest(request, response, "john", "passwd"); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); request.setUrl(getContextPath()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Index Page", response.getContentAsString()); request.setUrl(getProtectedResourceURL()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); }
From source file:org.picketlink.test.authentication.web.DigestAuthenticationSchemeTestCase.java
@Test public void testUnsuccessfulAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); WebResponse response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); prepareAuthenticationRequest(request, response, "john", "bad_passwd"); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); }