List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK
int SC_OK
To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.
Click Source Link
From source file:com.zimbra.cs.account.auth.HostedAuth.java
/** * zmprov md test.com zimbraAuthMech 'custom:hosted http://auth.customer.com:80' * //from www . jav a 2 s . c o m * This custom auth module takes arguments in the following form: * {URL} [GET|POST - default is GET] [encryption method - defautl is plain] [auth protocol - default is imap] * e.g.: http://auth.customer.com:80 GET **/ public void authenticate(Account acct, String password, Map<String, Object> context, List<String> args) throws Exception { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpMethod method = null; String targetURL = args.get(0); /* if (args.size()>2) { authMethod = args.get(2); } if (args.size()>3) { authMethod = args.get(3); }*/ if (args.size() > 1) { if (args.get(1).equalsIgnoreCase("GET")) method = new GetMethod(targetURL); else method = new PostMethod(targetURL); } else method = new GetMethod(targetURL); if (context.get(AuthContext.AC_ORIGINATING_CLIENT_IP) != null) method.addRequestHeader(HEADER_CLIENT_IP, context.get(AuthContext.AC_ORIGINATING_CLIENT_IP).toString()); if (context.get(AuthContext.AC_REMOTE_IP) != null) method.addRequestHeader(HEADER_X_ZIMBRA_REMOTE_ADDR, context.get(AuthContext.AC_REMOTE_IP).toString()); method.addRequestHeader(HEADER_AUTH_USER, acct.getName()); method.addRequestHeader(HEADER_AUTH_PASSWORD, password); AuthContext.Protocol proto = (AuthContext.Protocol) context.get(AuthContext.AC_PROTOCOL); if (proto != null) method.addRequestHeader(HEADER_AUTH_PROTOCOL, proto.toString()); if (context.get(AuthContext.AC_USER_AGENT) != null) method.addRequestHeader(HEADER_AUTH_USER_AGENT, context.get(AuthContext.AC_USER_AGENT).toString()); try { HttpClientUtil.executeMethod(client, method); } catch (HttpException ex) { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), acct.getName(), "HTTP request to remote authentication server failed", ex); } catch (IOException ex) { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), acct.getName(), "HTTP request to remote authentication server failed", ex); } finally { if (method != null) method.releaseConnection(); } int status = method.getStatusCode(); if (status != HttpStatus.SC_OK) { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), "HTTP request to remote authentication server failed. Remote response code: " + Integer.toString(status)); } String responseMessage; if (method.getResponseHeader(HEADER_AUTH_STATUS) != null) { responseMessage = method.getResponseHeader(HEADER_AUTH_STATUS).getValue(); } else { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), "Empty response from remote authentication server."); } if (responseMessage.equalsIgnoreCase(AUTH_STATUS_OK)) { return; } else { throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), responseMessage); } }
From source file:davmail.caldav.TestCaldav.java
public void testGetUserRoot() throws IOException { GetMethod method = new GetMethod("/users/" + session.getEmail() + '/'); httpClient.executeMethod(method);/*from w ww . j a va2s .com*/ assertEquals(HttpStatus.SC_OK, method.getStatusCode()); }
From source file:fr.openwide.talendalfresco.rest.client.AlfrescoRestClient.java
public void execute(ClientCommand clientCommand) throws RestClientException { int statusCode = -1; HttpMethodBase method = null;//from w w w . j a va 2 s. co m try { // building method (and body entity if any) method = clientCommand.createMethod(); // setting server URL method.setURI(new URI(restCommandUrlPrefix + clientCommand.getName(), false)); method.getParams().setContentCharset(this.restEncoding); // building params (adding ticket) List<NameValuePair> params = clientCommand.getParams(); params.add(new NameValuePair(TICKET_PARAM, ticket)); method.setQueryString(params.toArray(EMPTY_NAME_VALUE_PAIR)); // Execute the method. statusCode = client.executeMethod(method); // checking HTTP status if (statusCode != HttpStatus.SC_OK) { throw new RestClientException("Bad HTTP Status : " + statusCode); } // parsing response XMLEventReader xmlReader = null; try { xmlReader = XmlHelper.createXMLEventReader(method.getResponseBodyAsStream(), this.restEncoding); clientCommand.handleResponse(xmlReader); if (!RestConstants.CODE_OK.equals(clientCommand.getResultCode())) { //String msg = "Business error in command " + clientCommand.toString(); //logger.error(msg, e); throw new RestClientException(clientCommand.getResultMessage(), new RestClientException(clientCommand.getResultError())); } } catch (XMLStreamException e) { String msg = "XML parsing error on response body : "; try { msg += new String(method.getResponseBody()); } catch (IOException ioex) { msg += "[unreadable]"; } ; //logger.error(msg, e); throw new RestClientException(msg, e); } catch (IOException e) { String msg = "IO Error when parsing XML response body : "; //logger.error(msg, e); throw new RestClientException(msg, e); } finally { if (xmlReader != null) { try { xmlReader.close(); } catch (Throwable t) { } } } } catch (RestClientException rcex) { throw rcex; } catch (URIException e) { throw new RestClientException("URI error while executing command " + clientCommand, e); } catch (HttpException e) { throw new RestClientException("HTTP error while executing command " + clientCommand, e); } catch (IOException e) { throw new RestClientException("IO error while executing command " + clientCommand, e); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:gobblin.kafka.schemareg.LiKafkaSchemaRegistry.java
/** * Get the latest schema of a topic./*from w w w . j av a 2s .c om*/ * * @param topic topic name * @return the latest schema * @throws SchemaRegistryException if failed to retrieve schema. */ @Override public Schema getLatestSchema(String topic) throws SchemaRegistryException { String schemaUrl = this.url + GET_RESOURCE_BY_TYPE + topic; LOG.debug("Fetching from URL : " + schemaUrl); GetMethod get = new GetMethod(schemaUrl); int statusCode; String schemaString; HttpClient httpClient = this.borrowClient(); try { statusCode = httpClient.executeMethod(get); schemaString = get.getResponseBodyAsString(); } catch (HttpException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { get.releaseConnection(); this.httpClientPool.returnObject(httpClient); } if (statusCode != HttpStatus.SC_OK) { throw new SchemaRegistryException(String .format("Latest schema for topic %s cannot be retrieved. Status code = %d", topic, statusCode)); } Schema schema; try { schema = new Schema.Parser().parse(schemaString); } catch (Throwable t) { throw new SchemaRegistryException( String.format("Latest schema for topic %s cannot be retrieved", topic), t); } return schema; }
From source file:com.interaction.example.odata.embedded.LinkIdITCase.java
@Test public void testEntryCount() { try {/* w ww.java2s .c om*/ method = new GetMethod(baseUri + AIRPORTS); client.executeMethod(method); assertEquals(200, method.getStatusCode()); if (method.getStatusCode() == HttpStatus.SC_OK) { // read as string for debugging String response = method.getResponseBodyAsString(); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<Feed> feedEntry = parser.parse(new StringReader(response)); Feed feed = feedEntry.getRoot(); List<Entry> entries = feed.getEntries(); assertEquals(6, entries.size()); } } catch (IOException e) { fail(e.getMessage()); } finally { method.releaseConnection(); } }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static List<Notification> getNotifications(String serverId, String mirthVersion, Map<String, String> extensionVersions, String[] protocols, String[] cipherSuites) throws Exception { CloseableHttpClient client = null;/*from ww w . ja va2s. com*/ HttpPost post = new HttpPost(); CloseableHttpResponse response = null; List<Notification> allNotifications = new ArrayList<Notification>(); try { ObjectMapper mapper = new ObjectMapper(); String extensionVersionsJson = mapper.writeValueAsString(extensionVersions); NameValuePair[] params = { new BasicNameValuePair("op", NOTIFICATION_GET), new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("extensionVersions", extensionVersionsJson) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_NOTIFICATION_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { HttpEntity responseEntity = response.getEntity(); Charset responseCharset = null; try { responseCharset = ContentType.getOrDefault(responseEntity).getCharset(); } catch (Exception e) { responseCharset = ContentType.TEXT_PLAIN.getCharset(); } String responseContent = IOUtils.toString(responseEntity.getContent(), responseCharset).trim(); JsonNode rootNode = mapper.readTree(responseContent); for (JsonNode childNode : rootNode) { Notification notification = new Notification(); notification.setId(childNode.get("id").asInt()); notification.setName(childNode.get("name").asText()); notification.setDate(childNode.get("date").asText()); notification.setContent(childNode.get("content").asText()); allNotifications.add(notification); } } else { throw new ClientException("Status code: " + statusCode); } } catch (Exception e) { throw e; } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return allNotifications; }
From source file:de.pdark.dsmp.ProxyDownload.java
/** * Do the download.// w ww. j a v a 2s . c o m * * @throws IOException * @throws DownloadFailed */ public void download() throws IOException, DownloadFailed { if (!config.isAllowed(url)) { throw new DownloadFailed( "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in DSMP config"); } // If there is a status file in the cache, return it instead of trying it again // As usual with caches, this one is a key area which will always cause // trouble. // TODO There should be a simple way to get rid of the cached statuses // TODO Maybe retry a download after a certain time? File statusFile = new File(dest.getAbsolutePath() + ".status"); if (statusFile.exists()) { try { FileReader r = new FileReader(statusFile); char[] buffer = new char[(int) statusFile.length()]; int len = r.read(buffer); r.close(); String status = new String(buffer, 0, len); throw new DownloadFailed(status); } catch (IOException e) { log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e); } } mkdirs(); HttpClient client = new HttpClient(); String msg = ""; if (config.useProxy(url)) { Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()); AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM); HostConfiguration hc = new HostConfiguration(); hc.setProxy(config.getProxyHost(), config.getProxyPort()); client.setHostConfiguration(hc); client.getState().setProxyCredentials(scope, defaultcreds); msg = "via proxy "; } log.info("Downloading " + msg + "to " + dest.getAbsolutePath()); GetMethod get = new GetMethod(url.toString()); get.setFollowRedirects(true); try { int status = client.executeMethod(get); log.info("Download status: " + status); if (0 == 1 && log.isDebugEnabled()) { Header[] header = get.getResponseHeaders(); for (Header aHeader : header) log.debug(aHeader.toString().trim()); } log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; " + valueOf(get.getResponseHeader("Content-Type"))); if (status != HttpStatus.SC_OK) { // Remember "File not found" if (status == HttpStatus.SC_NOT_FOUND) { try { FileWriter w = new FileWriter(statusFile); w.write(get.getStatusLine().toString()); w.close(); } catch (IOException e) { log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e); } } throw new DownloadFailed(get); } File dl = new File(dest.getAbsolutePath() + ".new"); OutputStream out = new BufferedOutputStream(new FileOutputStream(dl)); IOUtils.copy(get.getResponseBodyAsStream(), out); out.close(); File bak = new File(dest.getAbsolutePath() + ".bak"); if (bak.exists()) bak.delete(); if (dest.exists()) dest.renameTo(bak); dl.renameTo(dest); } finally { get.releaseConnection(); } }
From source file:com.cerema.cloud2.lib.resources.files.UploadRemoteFileOperation.java
public boolean isSuccess(int status) { return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT)); }
From source file:com.cloud.utils.rest.RESTValidationStrategy.java
/** * Logs against the REST server. The cookie is stored in the <code>_authcookie<code> variable. * <p>/*from www .j a va2 s . c o m*/ * The method returns false if the login failed or the connection could not be made. * */ protected void login(final String protocol, final HttpClient client) throws CloudstackRESTException { String url; if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) { throw new CloudstackRESTException("Hostname/credentials are null or empty"); } try { url = new URL(protocol, host, loginUrl).toString(); } catch (final MalformedURLException e) { s_logger.error("Unable to build Nicira API URL", e); throw new CloudstackRESTException("Unable to build Nicira API URL", e); } final PostMethod pm = new PostMethod(url); pm.addParameter("username", user); pm.addParameter("password", password); try { client.executeMethod(pm); } catch (final HttpException e) { throw new CloudstackRESTException("REST Service API login failed ", e); } catch (final IOException e) { throw new CloudstackRESTException("REST Service API login failed ", e); } finally { pm.releaseConnection(); } if (pm.getStatusCode() != HttpStatus.SC_OK) { s_logger.error("REST Service API login failed : " + pm.getStatusText()); throw new CloudstackRESTException("REST Service API login failed " + pm.getStatusText()); } // Extract the version for later use if (pm.getResponseHeader("Server") != null) { serverVersion = pm.getResponseHeader("Server").getValue(); s_logger.debug("Server reports version " + serverVersion); } // Success; the cookie required for login is kept in _client }
From source file:grafix.basedados.Download.java
public int baixaArquivo() { // Create an instance of HttpClient. HttpClient client = new HttpClient(); int retorno = 0; // Create a method instance. if (this.usaProxy) { client.getHostConfiguration().setProxy(this.servidorProxy, this.portaProxy); client.getState().setProxyCredentials(new AuthScope(this.servidorProxy, this.portaProxy), new UsernamePasswordCredentials(this.usuarioProxy, this.senhaProxy)); client.getParams().setAuthenticationPreemptive(true); }/*w w w .j a va2s . com*/ URI url2; String ff = null; try { url2 = new URI(this.getUrl(), false); ff = url2.toString(); } catch (URIException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } GetMethod method = new GetMethod(ff); byte[] arquivo = null; long totalBytesRead = 0; long loopBytesRead = 0; // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); byte[] buffer = new byte[4096]; int progresso = 0; try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusCode() + " " + method.getStatusLine()); retorno = method.getStatusCode(); } else { long contentLength = method.getResponseContentLength(); File file = new File(this.getArquivo()); FileOutputStream os = new FileOutputStream(file); InputStream stream = method.getResponseBodyAsStream(); while ((loopBytesRead = stream.read(buffer)) != -1) { for (int i = 0; i < loopBytesRead; i++) { os.write(buffer[i]); } totalBytesRead += loopBytesRead; progresso = (int) ((float) totalBytesRead / contentLength * 100); if (progresso >= 0 || progresso <= 100) { // System.out.println("download " + progresso + " %"); if (this.mostraProgresso) formAtualizacao.definirPercentualProgresso(progresso); } } os.flush(); os.close(); stream.close(); } } catch (HttpException e) { retorno = 2; System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { retorno = 3; System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } if (this.mostraProgresso) formAtualizacao.definirPercentualProgresso(0); return retorno; }