List of usage examples for org.apache.commons.httpclient.methods DeleteMethod addRequestHeader
@Override public void addRequestHeader(String headerName, String headerValue)
From source file:com.owncloud.android.lib.resources.notifications.UnregisterAccountDeviceForNotificationsOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; DeleteMethod delete = null; try {/*from w w w .j a va 2s. c o m*/ // Post Method delete = new DeleteMethod(client.getBaseUri() + OCS_ROUTE); delete.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); status = client.executeMethod(delete); String response = delete.getResponseBodyAsString(); if (isSuccess(status)) { result = new RemoteOperationResult(true, status, delete.getResponseHeaders()); Log_OC.d(TAG, "Successful response: " + response); } else { result = new RemoteOperationResult(false, status, delete.getResponseHeaders()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Exception while registering device for notifications", e); } finally { if (delete != null) { delete.releaseConnection(); } } return result; }
From source file:com.owncloud.android.lib.resources.files.UnlockFileOperation.java
/** * @param client Client object//from w ww . j a va2 s . c o m */ @Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result; DeleteMethod deleteMethod = null; try { // remote request deleteMethod = new DeleteMethod(client.getBaseUri() + LOCK_FILE_URL + localId); deleteMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); deleteMethod.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED); deleteMethod.addRequestHeader(TOKEN, token); int status = client.executeMethod(deleteMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); result = new RemoteOperationResult(status == HttpStatus.SC_OK, deleteMethod); client.exhaustResponse(deleteMethod.getResponseBodyAsStream()); } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Unlock file with id " + localId + " failed: " + result.getLogMessage(), result.getException()); } finally { if (deleteMethod != null) deleteMethod.releaseConnection(); } return result; }
From source file:com.owncloud.android.lib.resources.users.DeletePublicKeyOperation.java
/** * @param client Client object//from ww w.ja v a 2s .com */ @Override protected RemoteOperationResult run(OwnCloudClient client) { DeleteMethod postMethod = null; RemoteOperationResult result; try { // remote request postMethod = new DeleteMethod(client.getBaseUri() + PUBLIC_KEY_URL); postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); result = new RemoteOperationResult(status == HttpStatus.SC_OK, postMethod); client.exhaustResponse(postMethod.getResponseBodyAsStream()); } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Deletion of public key failed: " + result.getLogMessage(), result.getException()); } finally { if (postMethod != null) postMethod.releaseConnection(); } return result; }
From source file:com.zimbra.cs.store.triton.TritonBlobStoreManager.java
@Override public boolean deleteFromStore(String locator, Mailbox mbox) throws IOException { HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); DeleteMethod delete = new DeleteMethod(blobApiUrl + locator); delete.addRequestHeader(TritonHeaders.HASH_TYPE, hashType.toString()); try {/*w w w.j a v a 2 s . c om*/ ZimbraLog.store.info("deleting %s", delete.getURI()); int statusCode = HttpClientUtil.executeMethod(client, delete); if (statusCode == HttpStatus.SC_OK) { return true; } else { throw new IOException("unexpected return code during blob DELETE: " + delete.getStatusText()); } } finally { delete.releaseConnection(); } }
From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java
/** * delete a single resource/*from w ww .ja va 2 s . co m*/ * * @param repoPath * path in registry * @throws HttpException * @throws IOException * @throws RegistryExtException * @throws OAuthSystemException * @throws OAuthProblemException */ public void deleteResource(String repoPath) throws HttpException, IOException, RegistryExtException, OAuthSystemException, OAuthProblemException { Map<String, Object> session = ActionContext.getContext().getSession(); int statusCode = 200; String accessToken = (String) session.get(Constants.SESSION_TOKEN); String requestURL = composeURL(FILEOPPREFIX, repoPath); if (logger.isDebugEnabled()) { logger.debug("Deletion request URL=" + requestURL); } HttpClient httpclient = new HttpClient(); DeleteMethod delete = new DeleteMethod(requestURL); delete.addRequestHeader("Authorization", "Bearer " + accessToken); try { httpclient.executeMethod(delete); statusCode = delete.getStatusLine().getStatusCode(); /* handle token expiration */ if (statusCode == 401) { logger.info(String.format("Access token %s expired, going to refresh it", accessToken)); refreshToken(session); // use refreshed access token accessToken = (String) session.get(Constants.SESSION_TOKEN); delete.addRequestHeader("Authorization", "Bearer " + accessToken); // re-send the request httpclient.executeMethod(delete); statusCode = delete.getStatusLine().getStatusCode(); } if (statusCode != 204) { throw new RegistryExtException( "Failed in delete resource : HTTP error code : " + delete.getStatusLine().getStatusCode()); } } finally { if (delete != null) delete.releaseConnection(); } }
From source file:com.zimbra.qa.unittest.TestCalDav.java
private void attendeeDeleteFromCalendar(boolean suppressReply) throws Exception { Account dav1 = users[1].create();/*w w w . j av a 2 s . co m*/ users[2].create(); String url = getSchedulingInboxUrl(dav1, dav1); ReportMethod method = new ReportMethod(url); addBasicAuthHeaderForUser(method, dav1); ZMailbox organizer = users[2].getZMailbox(); users[1].getZMailbox(); // Force creation of mailbox - shouldn't be needed String subject = String.format("%s %s", NAME_PREFIX, suppressReply ? "testInvite which shouldNOT be replied to" : "testInvite to be auto-declined"); Date startDate = new Date(System.currentTimeMillis() + Constants.MILLIS_PER_DAY); Date endDate = new Date(startDate.getTime() + Constants.MILLIS_PER_HOUR); TestUtil.createAppointment(organizer, subject, dav1.getName(), startDate, endDate); // Wait for appointment to arrive String href = waitForNewSchedulingRequestByUID(dav1, ""); assertNotNull("href for inbox invitation", href); String uid = href.substring(href.lastIndexOf('/') + 1); uid = uid.substring(0, uid.indexOf(',') - 1); String calFolderUrl = getFolderUrl(dav1, "Calendar"); String delurl = waitForItemInCalendarCollectionByUID(calFolderUrl, dav1, uid, true, 5000); StringBuilder sb = getLocalServerRoot().append(delurl); DeleteMethod delMethod = new DeleteMethod(sb.toString()); addBasicAuthHeaderForUser(delMethod, dav1); if (suppressReply) { delMethod.addRequestHeader(DavProtocol.HEADER_SCHEDULE_REPLY, "F"); } HttpClient client = new HttpClient(); HttpMethodExecutor.execute(client, delMethod, HttpStatus.SC_NO_CONTENT); List<ZMessage> msgs; if (suppressReply) { // timeout may be a bit short but don't want long time wastes in test suite. msgs = TestUtil.waitForMessages(organizer, "is:invite is:unread inid:2 after:\"-1month\"", 0, 2000); if (msgs != null) { assertEquals("Should be no DECLINE reply msg", 0, msgs.size()); } } else { msgs = TestUtil.waitForMessages(organizer, "is:invite is:unread inid:2 after:\"-1month\"", 1, 10000); assertNotNull("inbox DECLINE reply msgs", msgs); assertEquals("Should be 1 DECLINE reply msg", 1, msgs.size()); assertNotNull("inbox DECLINE reply msg invite", msgs.get(0).getInvite()); } }
From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java
@Override public final boolean deleteObject(final ScribeCommandObject cADCommandObject, final String idToBeDeleted) throws Exception { logger.debug("----Inside deleteObject"); DeleteMethod deleteMethod = null; try {//w ww . ja v a2 s.co m String serviceURL = null; String serviceProtocol = null; String userId = null; String password = null; String sessionId = null; String crmPort = "80"; /* Check if CrmUserId is present in request */ if (cADCommandObject.getCrmUserId() != null) { /* Get agent from session manager */ final ScribeCacheObject agent = zDCRMSessionManager .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId()); /* Get CRM information from agent */ serviceURL = agent.getScribeMetaObject().getCrmServiceURL(); serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol(); userId = agent.getScribeMetaObject().getCrmUserId(); password = agent.getScribeMetaObject().getCrmPassword(); sessionId = agent.getScribeMetaObject().getCrmSessionId(); crmPort = agent.getScribeMetaObject().getCrmPort(); } /* Check if id is available in request */ if (idToBeDeleted == null) { /* Inform user about invalid request */ throw new ScribeException( ScribeResponseCodes._1008 + "CRM object id for deletion purpose is not present in request"); } /* Create Zen desk URL */ final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType() + "s/" + idToBeDeleted.trim() + ".xml"; logger.debug("----Inside deleteObject zenDeskURL: " + zenDeskURL); /* Instantiate delete method */ deleteMethod = new DeleteMethod(zenDeskURL); /* Set request content type */ deleteMethod.addRequestHeader("Content-Type", "application/xml"); deleteMethod.addRequestHeader("accept", "application/xml"); /* Cookie is required to be set for session management */ deleteMethod.addRequestHeader("Cookie", sessionId); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)), new UsernamePasswordCredentials(userId, password)); /* Execute method */ int result = httpclient.executeMethod(deleteMethod); logger.debug("----Inside deleteObject response code: " + result + " & body: " + deleteMethod.getResponseBodyAsString()); /* Check if object is updated */ if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) { /* Return the original object */ return true; } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED || result == HttpStatus.SC_NOT_ACCEPTABLE) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : " + ZDCRMMessageFormatUtils.getErrorFromResponse(deleteMethod.getResponseBodyAsStream())); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM"); } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct"); } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (deleteMethod != null) { deleteMethod.releaseConnection(); } } return false; }
From source file:org.apache.zeppelin.rest.AbstractTestRestApi.java
protected static DeleteMethod httpDelete(String path) throws IOException { LOG.info("Connecting to {}", url + path); HttpClient httpClient = new HttpClient(); DeleteMethod deleteMethod = new DeleteMethod(url + path); deleteMethod.addRequestHeader("Origin", url); httpClient.executeMethod(deleteMethod); LOG.info("{} - {}", deleteMethod.getStatusCode(), deleteMethod.getStatusText()); return deleteMethod; }
From source file:org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTransport.java
public static ServiceResult doDELETE(String urlString, String authForTest, String testID, String fromTestID) throws Exception { ServiceResult pr = new ServiceResult(); pr.failureReason = ""; pr.method = "DELETE"; pr.fullURL = urlString;/*www. j a va2 s . co m*/ pr.fromTestID = fromTestID; if (Tools.isEmpty(urlString)) { pr.error = "url was empty. Check the result for fromTestID: " + fromTestID + ". currentTest: " + testID; return pr; } HttpClient client = new HttpClient(); DeleteMethod deleteMethod = new DeleteMethod(urlString); deleteMethod.setRequestHeader("Accept", "multipart/mixed"); deleteMethod.addRequestHeader("Accept", "application/xml"); deleteMethod.setRequestHeader("Authorization", "Basic " + authForTest); deleteMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID); int statusCode1 = 0; String res = ""; try { statusCode1 = client.executeMethod(deleteMethod); pr.responseCode = statusCode1; //System.out.println("statusCode: "+statusCode1+" statusLine ==>" + deleteMethod.getStatusLine()); pr.responseMessage = deleteMethod.getStatusText(); res = deleteMethod.getResponseBodyAsString(); deleteMethod.releaseConnection(); } catch (Throwable t) { pr.error = t.toString(); } pr.result = res; pr.responseCode = statusCode1; return pr; }
From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java
/** * Deletes an object using its digest string. * * @param objectID//from w w w . jav a 2 s . c om */ protected void removeBinary(String objectID) { String url = PROTOCOL_PREFIX + this.bucketName + "." + this.hostBase; log.debug(url); DeleteMethod deleteMethod = new DeleteMethod(url); String contentMD5 = ""; // date to be provided to the cloud server Date currentDate = new Date(); String cloudDateString = StringGenerator.getCloudFormattedDateString(currentDate); String stringToSign = StringGenerator.getStringToSign(HTTPMethod.DELETE, contentMD5, DEFAULT_CONTENT_TYPE, this.bucketName, objectID, currentDate); try { deleteMethod.addRequestHeader("Authorization", StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret)); deleteMethod.addRequestHeader("x-amz-date", cloudDateString); deleteMethod.setPath("/" + objectID); HttpClient client = new HttpClient(); int returnCode = client.executeMethod(deleteMethod); log.debug(deleteMethod.getResponseBodyAsString()); // only for logging if (returnCode == HttpStatus.SC_NO_CONTENT) { log.info("Object " + objectID + " deleted"); } else if (returnCode == HttpStatus.SC_NOT_FOUND) { log.debug("Object " + objectID + " does not exist"); } else { String connectionMsg = "Scality connection problem. Object could not be verified"; log.debug(connectionMsg); throw new RuntimeException(connectionMsg); } deleteMethod.releaseConnection(); } catch (SignatureException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }