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:edu.unc.lib.dl.cdr.sword.server.managers.MediaResourceManagerImpl.java
@Override public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> accept, AuthCredentials auth, SwordConfiguration config) throws SwordError, SwordServerException, SwordAuthException { log.debug("Retrieving media resource representation for " + uri); DatastreamPID targetPID = (DatastreamPID) extractPID(uri, SwordConfigurationImpl.EDIT_MEDIA_PATH + "/"); Datastream datastream = Datastream.getDatastream(targetPID.getDatastream()); if (datastream == null) datastream = virtualDatastreamMap.get(targetPID.getDatastream()); if (datastream == null) throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404, "Media representations other than those of datastreams are not currently supported"); HttpClient client = new HttpClient(); UsernamePasswordCredentials cred = new UsernamePasswordCredentials(accessClient.getUsername(), accessClient.getPassword()); client.getState().setCredentials(new AuthScope(null, 443), cred); client.getState().setCredentials(new AuthScope(null, 80), cred); GetMethod method = new GetMethod(fedoraPath + "/objects/" + targetPID.getPid() + "/datastreams/" + datastream.getName() + "/content"); InputStream inputStream = null; String mimeType = null;/* w ww . ja v a 2 s .c o m*/ String lastModified = null; try { method.setDoAuthentication(true); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { StringBuffer query = new StringBuffer(); query.append("select $mimeType $lastModified from <%1$s>") .append(" where <%2$s> <%3$s> $mimeType and <%2$s> <%4$s> $lastModified").append(";"); String formatted = String.format(query.toString(), tripleStoreQueryService.getResourceIndexModelUri(), targetPID.getURI() + "/" + datastream.getName(), ContentModelHelper.FedoraProperty.mimeType.getURI().toString(), ContentModelHelper.FedoraProperty.lastModifiedDate.getURI().toString()); List<List<String>> datastreamResults = tripleStoreQueryService.queryResourceIndex(formatted); if (datastreamResults.size() > 0) { mimeType = datastreamResults.get(0).get(0); lastModified = datastreamResults.get(0).get(1); } inputStream = new MethodAwareInputStream(method); } else if (method.getStatusCode() >= 500) { throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, method.getStatusCode(), "Failed to retrieve " + targetPID.getPid() + ": " + method.getStatusLine().toString()); } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404, "Object " + targetPID.getPid() + " could not be found."); } } catch (HttpException e) { throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, "An exception occurred while attempting to retrieve " + targetPID.getPid()); } catch (IOException e) { throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, "An exception occurred while attempting to retrieve " + targetPID.getPid()); } // For the ACL virtual datastream, transform RELS-EXT into accessControl tag if ("ACL".equals(targetPID.getDatastream())) { try { log.debug("Converting response XML to ACL format"); SAXBuilder saxBuilder = new SAXBuilder(); Document relsExt = saxBuilder.build(inputStream); XMLOutputter outputter = new XMLOutputter(); Element accessElement = AccessControlTransformationUtil.rdfToACL(relsExt.getRootElement()); inputStream.close(); inputStream = new ByteArrayInputStream(outputter.outputString(accessElement).getBytes()); } catch (Exception e) { log.debug("Failed to parse response from " + targetPID.getDatastreamURI() + " into ACL format", e); throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, "An exception occurred while attempting to retrieve " + targetPID.getPid()); } } MediaResource resource = new MediaResource(inputStream, mimeType, null, true); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date lastModifiedDate; try { lastModifiedDate = formatter.parse(lastModified); resource.setLastModified(lastModifiedDate); } catch (ParseException e) { log.error("Unable to set last modified date for " + uri, e); } return resource; }
From source file:com.bdaum.juploadr.uploadapi.locrrest.upload.LocrUpload.java
@Override public boolean execute() throws ProtocolException, CommunicationException { HttpClient httpClient = HttpClientFactory.getHttpClient(getSession().getAccount()); // checkAuthorization(client); this.monitor.uploadStarted(new UploadEvent(image, 0, true, false)); PostMethod post = new PostMethod(POSTURL); List<Part> parts = getParts(); MultipartRequestEntity entity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams());/*from w w w. j a v a 2 s . c om*/ post.setRequestEntity(entity); try { int status = httpClient.executeMethod(post); if (status == HttpStatus.SC_OK) { // deal with the response try { String response = post.getResponseBodyAsString(); post.releaseConnection(); boolean success = parseResponse(response); if (success) { image.setState(UploadImage.STATE_UPLOADED); ImageUploadResponse resp = new ImageUploadResponse( ((LocrUploadResponseHandler) handler).getPhotoID()); this.monitor.uploadFinished(new UploadCompleteEvent(resp, image)); } else { throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$ } } catch (IOException e) { // TODO: Is it safe to assume the upload failed here? this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$ + e.getMessage(), e); } } else { this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$ } } catch (ConnectException ce) { this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$ } catch (NoRouteToHostException route) { this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$ } catch (UnknownHostException uhe) { this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$ } catch (HttpException e) { this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$ } catch (IOException e) { this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$ + e, e); } return true; }
From source file:com.hp.alm.ali.idea.services.AttachmentService.java
public boolean updateAttachmentContent(String name, EntityRef parent, IndicatingInputStream is, long length, boolean silent) { Map<String, String> headers = Collections.singletonMap("Content-Type", "application/octet-stream"); MyResultInfo result = new MyResultInfo(); if (restService.put(new MyInputData(is, length, headers), result, "{0}s/{1}/attachments/{2}", parent.type, parent.id, EntityQuery.encode(name)) != HttpStatus.SC_OK) { if (!silent) { errorService.showException(new RestException(result)); }/* w w w . j ava 2s . co m*/ return false; } else { EntityList list = EntityList.create(result.getBodyAsStream(), true); if (!list.isEmpty()) { entityService.fireEntityLoaded(list.get(0), EntityListener.Event.GET); } return true; } }
From source file:com.hw13c.HttpClientPost.java
private void doRequest(File file, PostMethod method) { try {//from w ww . ja va 2 s. c om int returnCode = client.executeMethod(method); if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.err.println("The Post method is not implemented by this URI"); // still consume the response body method.getResponseBodyAsString(); } else if (returnCode == HttpStatus.SC_OK) { System.out.println("File post succeeded: " + file); // System.out.println(method.getResponseBodyAsString()); saveResponse(file, method); } else { System.err.println("File post failed: " + file); System.err.println("Got code: " + returnCode); System.err.println("response: " + method.getResponseBodyAsString()); } } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } }
From source file:com.owncloud.android.authenticator.ConnectionCheckerRunnable.java
private boolean tryConnection(String urlSt) { boolean retval = false; GetMethod get = null;/*from w ww . j a v a 2 s. co m*/ try { WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(urlSt)); get = new GetMethod(urlSt); int status = wc.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT); String response = get.getResponseBodyAsString(); switch (status) { case HttpStatus.SC_OK: { JSONObject json = new JSONObject(response); if (!json.getBoolean("installed")) { mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; break; } mOCVersion = new OwnCloudVersion(json.getString("version")); if (!mOCVersion.isVersionValid()) { mLatestResult = ResultType.BAD_OC_VERSION; break; } retval = true; break; } case HttpStatus.SC_NOT_FOUND: mLatestResult = ResultType.FILE_NOT_FOUND; break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; break; default: mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "Not handled status received from server: " + status); } } catch (JSONException e) { mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED; Log.e(TAG, "JSON exception while trying connection (instance not configured) ", e); } catch (SocketException e) { mLatestResult = ResultType.WRONG_CONNECTION; Log.e(TAG, "Socket exception while trying connection", e); } catch (SocketTimeoutException e) { mLatestResult = ResultType.TIMEOUT; Log.e(TAG, "Socket timeout exception while trying connection", e); } catch (MalformedURLException e) { mLatestResult = ResultType.INCORRECT_ADDRESS; Log.e(TAG, "Connect exception while trying connection", e); } catch (UnknownHostException e) { mLatestResult = ResultType.HOST_NOT_AVAILABLE; Log.e(TAG, "Unknown host exception while trying connection", e); } catch (SSLPeerUnverifiedException e) { // specially meaningful SSLException mLatestResult = ResultType.SSL_UNVERIFIED_SERVER; Log.e(TAG, "SSL Peer Unverified exception while trying connection", e); } catch (SSLException e) { mLatestResult = ResultType.SSL_INIT_ERROR; Log.e(TAG, "SSL exception while trying connection", e); } catch (ConnectTimeoutException e) { // timeout specific exception from org.apache.commons.httpclient mLatestResult = ResultType.TIMEOUT; Log.e(TAG, "Socket timeout exception while trying connection", e); } catch (HttpException e) { // other specific exceptions from org.apache.commons.httpclient mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "HTTP exception while trying connection", e); } catch (IOException e) { // UnkownsServiceException, and any other transport exceptions that could occur mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "I/O exception while trying connection", e); } catch (Exception e) { mLatestResult = ResultType.UNKNOWN_ERROR; Log.e(TAG, "Unexpected exception while trying connection", e); } finally { if (get != null) get.releaseConnection(); } return retval; }
From source file:com.datatorrent.demos.samplestream.YahooFinanceCSVInputOperator.java
@Override public void run() { while (true) { try {/*ww w . java2s . c o m*/ int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } else { InputStream istream; istream = method.getResponseBodyAsStream(); // Process response InputStreamReader isr = new InputStreamReader(istream); CSVReader reader = new CSVReader(isr); List<String[]> myEntries; myEntries = reader.readAll(); for (String[] stringArr : myEntries) { ArrayList<String> al = new ArrayList<String>(Arrays.asList(stringArr)); outputPort.emit(al); // send out one symbol at a time } } Thread.sleep(readIntervalMillis); } catch (InterruptedException ex) { logger.debug(ex.toString()); } catch (IOException ex) { logger.debug(ex.toString()); } } }
From source file:com.fluidops.iwb.wiki.WikiBot.java
/** * Execute a wikimedia query asking for the latest content of the * given wikipedia page. If {@link #expandTemplates} is set, the * templates within the content are automatically expanded * /*from w ww.j av a 2s . co m*/ * @param wikiPage * @return */ private String retrieveWikiContent(String wikiPage) throws IOException, Exception { PostMethod method = new PostMethod(wikimediaApiURL()); method.addRequestHeader("User-Agent", WIKIBOT_USER_AGENT); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); method.addParameter("action", "query"); method.addParameter("prop", "revisions"); method.addParameter("rvprop", "ids|content"); if (expandTemplates) method.addParameter("rvexpandtemplates", ""); method.addParameter("tlnamespace", "0"); method.addParameter("format", "xml"); method.addParameter("redirects", ""); method.addParameter("titles", wikiPage.replace(" ", "_")); try { int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_OK) { return parsePage(method.getResponseBodyAsStream()); } throw new IOException("Error while retrieving wiki page " + wikiPage + ": " + status + " (" + method.getStatusText() + ")"); } finally { method.releaseConnection(); } }
From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java
public SaxonDocument delete(String id) throws UnsupportedEncodingException, IOException, SaxonApiException, Exception { HttpClient client = new HttpClient(); HttpMethod method;/*from w w w . ja v a2 s .c o m*/ String urlStr = this.solrHost + "/update?stream.body=" + URLEncoder.encode("<delete><query>id:" + id + "</query></delete>") + "&commit=true"; Log.debug("The " + id + " item is going to be deleted"); // Create a method instance. method = new GetMethod(urlStr); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. int statusCode = client.executeMethod(method); SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString()); //Log.debug(solrResponse.getXMLDocumentString()); if (statusCode != HttpStatus.SC_OK) { Log.error("Method failed: " + method.getStatusLine()); String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()", XPathConstants.STRING); throw new Exception(errorMessage); } return solrResponse; }
From source file:mitm.common.security.ca.handlers.comodo.AutoAuthorize.java
private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException { if (statusCode != HttpStatus.SC_OK) { throw new IOException("Error Authorize. Message: " + httpMethod.getStatusLine()); }//from w w w. java2 s .c om InputStream input = httpMethod.getResponseBodyAsStream(); if (input == null) { throw new IOException("Response body is null."); } /* * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB. */ InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE); String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII); if (logger.isDebugEnabled()) { logger.debug("Response:\r\n" + response); } LineNumberReader lineReader = new LineNumberReader(new StringReader(response)); String statusParameter = lineReader.readLine(); errorCode = CustomClientStatusCode.fromCode(statusParameter); if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) { error = true; errorMessage = lineReader.readLine(); } else { error = false; } }
From source file:br.org.acessobrasil.silvinha.util.versoes.AtualizadorDeVersoes.java
public boolean baixarVersao() { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); NameValuePair param = new NameValuePair("param", "update"); method.setRequestBody(new NameValuePair[] { param }); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); JFrame down = new JFrame("Download"); File downFile = null;/*from ww w.j a v a2 s.co m*/ InputStream is = null; FileOutputStream fos = null; try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + method.getStatusLine()); } Header header = method.getResponseHeader("Content-Disposition"); String fileName = "silvinha.exe"; if (header != null) { fileName = header.getValue().split("=")[1]; } // Read the response body. is = method.getResponseBodyAsStream(); down.pack(); ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(down, TradAtualizadorDeVersoes.FAZ_DOWNLOAD_FILE + fileName, is); pmis.getProgressMonitor().setMinimum(0); pmis.getProgressMonitor().setMaximum((int) method.getResponseContentLength()); downFile = new File(fileName); fos = new FileOutputStream(downFile); int c; while (((c = pmis.read()) != -1) && (!pmis.getProgressMonitor().isCanceled())) { fos.write(c); } fos.flush(); fos.close(); String msgOK = TradAtualizadorDeVersoes.DOWNLOAD_EXITO + TradAtualizadorDeVersoes.DESEJA_ATUALIZAR_EXECUTAR + TradAtualizadorDeVersoes.ARQUIVO_DE_NOME + fileName + TradAtualizadorDeVersoes.LOCALIZADO_NA + TradAtualizadorDeVersoes.PASTA_INSTALACAO + TradAtualizadorDeVersoes.APLICACAO_DEVE_SER_ENCERRADA + TradAtualizadorDeVersoes.DESEJA_CONTINUAR_ATUALIZACAO; if (JOptionPane.showConfirmDialog(null, msgOK, TradAtualizadorDeVersoes.ATUALIZACAO_DO_PROGRAMA, JOptionPane.YES_NO_OPTION) == 0) { return true; } else { return false; } } catch (HttpException he) { log.error("Fatal protocol violation: " + he.getMessage(), he); return false; } catch (InterruptedIOException iioe) { method.abort(); String msg = GERAL.OP_CANCELADA_USUARIO + TradAtualizadorDeVersoes.DIRECIONADO_A_APLICACAO; JOptionPane.showMessageDialog(down, msg); try { if (fos != null) { fos.close(); } } catch (IOException ioe) { method.releaseConnection(); System.exit(0); } if (downFile != null && downFile.exists()) { downFile.delete(); } return false; // System.err.println("Fatal transport error: " + iioe.getMessage()); // iioe.printStackTrace(); } catch (IOException ioe) { log.error("Fatal transport error: " + ioe.getMessage(), ioe); return false; } finally { //Release the connection. method.releaseConnection(); } }