下面列出了怎么用org.apache.commons.httpclient.methods.DeleteMethod的API类实例代码及写法,或者点击链接到github查看源代码。
@Test(groups = { "wso2.esb" }, description = "Sending complete URL to API and for dispatching")
public void testCompleteURLWithHTTPMethod() throws Exception {
logReader.start();
DeleteMethod delete = new DeleteMethod(getApiInvocationURL(
"myApi1/order/21441/item/17440079" + "?message_id=41ec2ec4-e629-4e04-9fdf-c32e97b35bd1"));
HttpClient httpClient = new HttpClient();
try {
httpClient.executeMethod(delete);
Assert.assertEquals(delete.getStatusLine().getStatusCode(), 202, "Response code mismatched");
} finally {
delete.releaseConnection();
}
Assert.assertTrue(logReader.checkForLog("order API INVOKED", DEFAULT_TIMEOUT),
"Request Not Dispatched to API when HTTP method having full url");
logReader.stop();
}
protected static HttpMethodBase buildHttpClientMethod(String url, String method)
{
if ("GET".equals(method))
{
return new GetMethod(url);
}
if ("POST".equals(method))
{
return new PostMethod(url);
}
if ("PUT".equals(method))
{
return new PutMethod(url);
}
if ("DELETE".equals(method))
{
return new DeleteMethod(url);
}
if (TestingMethod.METHOD_NAME.equals(method))
{
return new TestingMethod(url);
}
throw new UnsupportedOperationException("Method '"+method+"' not supported");
}
@Override
protected ServerStatus _doIt() {
try {
/* unmap route from application */
URI targetURI = URIUtil.toURI(target.getUrl());
DeleteMethod unmapRouteMethod = new DeleteMethod(targetURI.resolve("/v2/apps/" + app.getGuid() + "/routes/" + route.getGuid()).toString()); //$NON-NLS-1$//$NON-NLS-2$
ServerStatus confStatus = HttpUtil.configureHttpMethod(unmapRouteMethod, target.getCloud());
if (!confStatus.isOK())
return confStatus;
return HttpUtil.executeMethod(unmapRouteMethod);
} catch (Exception e) {
String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
logger.error(msg, e);
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
}
@Override
protected ServerStatus _doIt() {
try {
URI targetURI = URIUtil.toURI(target.getUrl());
/* delete the route */
URI routeURI = targetURI.resolve("/v2/routes/" + route.getGuid()); //$NON-NLS-1$
DeleteMethod deleteRouteMethod = new DeleteMethod(routeURI.toString());
ServerStatus confStatus = HttpUtil.configureHttpMethod(deleteRouteMethod, target.getCloud());
if (!confStatus.isOK())
return confStatus;
deleteRouteMethod.setQueryString("recursive=true"); //$NON-NLS-1$
ServerStatus status = HttpUtil.executeMethod(deleteRouteMethod);
return status;
} catch (Exception e) {
String msg = NLS.bind("An error occured when performing operation {0}", commandName);
logger.error(msg, e);
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
}
private static HttpMethodBase getMethod(HttpMethod method, String address) {
String addr = address;
if (method.equals(HttpMethod.Delete)) {
return new DeleteMethod(addr);
}
if (method.equals(HttpMethod.Post)) {
return new PostMethod(addr);
}
if (method.equals(HttpMethod.Get)) {
return new GetMethod(addr);
}
if (method.equals(HttpMethod.Put)) {
return new PutMethod(addr);
}
Assert.assertUnreachable("method doesn't exist");
return null;
}
/**
* 处理delete请求
* @param url
* @param headers
* @return
*/
public static JSONObject doDelete(String url, Map<String, String> headers){
HttpClient httpClient = new HttpClient();
DeleteMethod deleteMethod = new DeleteMethod(url);
//设置header
setHeaders(deleteMethod,headers);
String responseStr = "";
try {
httpClient.executeMethod(deleteMethod);
responseStr = deleteMethod.getResponseBodyAsString();
} catch (Exception e) {
log.error(e);
responseStr="{status:0}";
}
return JSONObject.parseObject(responseStr);
}
@Test
public void testDeleteParagraph() throws IOException {
Note note = null;
try {
note = TestUtils.getInstance(Notebook.class).createNote("note1_testDeleteParagraph", anonymous);
Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
p.setTitle("title1");
p.setText("text1");
TestUtils.getInstance(Notebook.class).saveNote(note, anonymous);
DeleteMethod delete = httpDelete("/notebook/" + note.getId() + "/paragraph/" + p.getId());
assertThat("Test delete method: ", delete, isAllowed());
delete.releaseConnection();
Note retrNote = TestUtils.getInstance(Notebook.class).getNote(note.getId());
Paragraph retrParagrah = retrNote.getParagraph(p.getId());
assertNull("paragraph should be deleted", retrParagrah);
} finally {
//cleanup
if (null != note) {
TestUtils.getInstance(Notebook.class).removeNote(note, anonymous);
}
}
}
@Test
public void testAddDeleteRepository() throws IOException {
// Call create repository API
String repoId = "securecentral";
String jsonRequest = "{\"id\":\"" + repoId +
"\",\"url\":\"https://repo1.maven.org/maven2\",\"snapshot\":\"false\"}";
PostMethod post = httpPost("/interpreter/repository/", jsonRequest);
assertThat("Test create method:", post, isAllowed());
post.releaseConnection();
// Call delete repository API
DeleteMethod delete = httpDelete("/interpreter/repository/" + repoId);
assertThat("Test delete method:", delete, isAllowed());
delete.releaseConnection();
}
@Test
public void testDeleteCourses() throws IOException {
final ICourse course = CoursesWebService.createEmptyCourse(admin, "courseToDel", "course to delete", null);
DBFactory.getInstance().intermediateCommit();
final HttpClient c = loginWithCookie("administrator", "olat");
final DeleteMethod method = createDelete("/repo/courses/" + course.getResourceableId(), MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
assertEquals(code, 200);
final List<String> courseType = new ArrayList<String>();
courseType.add(CourseModule.getCourseTypeName());
final Roles roles = new Roles(true, true, true, true, false, true, false);
final List<RepositoryEntry> repoEntries = RepositoryServiceImpl.getInstance().genericANDQueryWithRolesRestriction("*", "*", "*", courseType, roles, "");
assertNotNull(repoEntries);
for (final RepositoryEntry entry : repoEntries) {
assertNotSame(entry.getOlatResource().getResourceableId(), course.getResourceableId());
}
}
@Test
public void testDeleteAuthentications() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
// create an authentication token
final Identity adminIdent = baseSecurity.findIdentityByName("administrator");
final Authentication authentication = baseSecurity.createAndPersistAuthentication(adminIdent, "REST-A-2", "administrator", "credentials");
assertTrue(authentication != null && authentication.getKey() != null && authentication.getKey().longValue() > 0);
DBFactory.getInstance().intermediateCommit();
// delete an authentication token
final String request = "/users/administrator/auth/" + authentication.getKey().toString();
final DeleteMethod method = createDelete(request, MediaType.APPLICATION_XML, true);
final int code = c.executeMethod(method);
assertEquals(code, 200);
method.releaseConnection();
final Authentication refAuth = baseSecurity.findAuthentication(adminIdent, "REST-A-2");
assertNull(refAuth);
}
@Test
public void testDeleteCatalogEntry() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build();
final DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
assertEquals(200, code);
method.releaseConnection();
final List<CatalogEntry> entries = catalogService.getChildrenOf(root1);
for (final CatalogEntry entry : entries) {
assertFalse(entry.getKey().equals(entry2.getKey()));
}
}
@Test
public void testRemoveOwner() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getUser().getKey().toString())
.build();
final DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
method.releaseConnection();
assertEquals(200, code);
final CatalogEntry entry = catalogService.loadCatalogEntry(entry1.getKey());
final List<Identity> identities = securityManager.getIdentitiesOfSecurityGroup(entry.getOwnerGroup());
boolean found = false;
for (final Identity identity : identities) {
if (identity.getKey().equals(id1.getKey())) {
found = true;
}
}
assertFalse(found);
}
@Test
public void testDeleteCourses() throws IOException {
final ICourse course = CoursesWebService.createEmptyCourse(admin, "courseToDel", "course to delete", null);
DBFactory.getInstance().intermediateCommit();
final HttpClient c = loginWithCookie("administrator", "olat");
final DeleteMethod method = createDelete("/repo/courses/" + course.getResourceableId(), MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
assertEquals(code, 200);
final List<String> courseType = new ArrayList<String>();
courseType.add(CourseModule.getCourseTypeName());
final Roles roles = new Roles(true, true, true, true, false, true, false);
final List<RepositoryEntry> repoEntries = RepositoryServiceImpl.getInstance().genericANDQueryWithRolesRestriction("*", "*", "*", courseType, roles, "");
assertNotNull(repoEntries);
for (final RepositoryEntry entry : repoEntries) {
assertNotSame(entry.getOlatResource().getResourceableId(), course.getResourceableId());
}
}
@Test
public void testDeleteAuthentications() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
// create an authentication token
final Identity adminIdent = baseSecurity.findIdentityByName("administrator");
final Authentication authentication = baseSecurity.createAndPersistAuthentication(adminIdent, "REST-A-2", "administrator", "credentials");
assertTrue(authentication != null && authentication.getKey() != null && authentication.getKey().longValue() > 0);
DBFactory.getInstance().intermediateCommit();
// delete an authentication token
final String request = "/users/administrator/auth/" + authentication.getKey().toString();
final DeleteMethod method = createDelete(request, MediaType.APPLICATION_XML, true);
final int code = c.executeMethod(method);
assertEquals(code, 200);
method.releaseConnection();
final Authentication refAuth = baseSecurity.findAuthentication(adminIdent, "REST-A-2");
assertNull(refAuth);
}
@Test
public void testDeleteCatalogEntry() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build();
final DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
assertEquals(200, code);
method.releaseConnection();
final List<CatalogEntry> entries = catalogService.getChildrenOf(root1);
for (final CatalogEntry entry : entries) {
assertFalse(entry.getKey().equals(entry2.getKey()));
}
}
@Test
public void testRemoveOwner() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).path("owners").path(id1.getUser().getKey().toString())
.build();
final DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true);
final int code = c.executeMethod(method);
method.releaseConnection();
assertEquals(200, code);
final CatalogEntry entry = catalogService.loadCatalogEntry(entry1.getKey());
final List<Identity> identities = securityManager.getIdentitiesOfSecurityGroup(entry.getOwnerGroup());
boolean found = false;
for (final Identity identity : identities) {
if (identity.getKey().equals(id1.getKey())) {
found = true;
}
}
assertFalse(found);
}
/**
* Given host, port and schema name, send a http DELETE request to delete the {@link Schema}.
*
* @return <code>true</code> on success.
* <P><code>false</code> on failure.
*/
public static boolean deleteSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
Preconditions.checkNotNull(host);
Preconditions.checkNotNull(schemaName);
try {
URL url = new URL("http", host, port, "/schemas/" + schemaName);
DeleteMethod httpDelete = new DeleteMethod(url.toString());
try {
int responseCode = HTTP_CLIENT.executeMethod(httpDelete);
if (responseCode >= 400) {
String response = httpDelete.getResponseBodyAsString();
LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
return false;
}
return true;
} finally {
httpDelete.releaseConnection();
}
} catch (Exception e) {
LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host, port, e);
return false;
}
}
protected HttpMethod createMethod(final String type, final String uri, final int port) throws BigSwitchBcfApiException {
String url;
try {
url = new URL(S_PROTOCOL, host, port, uri).toString();
} catch (MalformedURLException e) {
S_LOGGER.error("Unable to build Big Switch API URL", e);
throw new BigSwitchBcfApiException("Unable to build Big Switch API URL", e);
}
if ("post".equalsIgnoreCase(type)) {
return new PostMethod(url);
} else if ("get".equalsIgnoreCase(type)) {
return new GetMethod(url);
} else if ("delete".equalsIgnoreCase(type)) {
return new DeleteMethod(url);
} else if ("put".equalsIgnoreCase(type)) {
return new PutMethod(url);
} else {
throw new BigSwitchBcfApiException("Requesting unknown method type");
}
}
protected static DeleteMethod httpDelete(String path, String user, String pwd) throws IOException {
LOG.info("Connecting to {}", URL + path);
HttpClient httpClient = new HttpClient();
DeleteMethod deleteMethod = new DeleteMethod(URL + path);
deleteMethod.addRequestHeader("Origin", URL);
if (userAndPasswordAreNotBlank(user, pwd)) {
deleteMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
}
httpClient.executeMethod(deleteMethod);
LOG.info("{} - {}", deleteMethod.getStatusCode(), deleteMethod.getStatusText());
return deleteMethod;
}
/**
* 删除指定dashboard
* 目前业务特点无需抛出异常
*
* @param dashboardId
* @throws MonitorException
*/
private void delDashboard(String dashboardId) throws MonitorException {
// format url
String url = String
.format("%s/%s/%s", grafanaApiUrl, GrafanaDashboardServiceImpl.GRAFANA_DEL_DASHBOARD_URI, dashboardId);
DeleteMethod method = new DeleteMethod(url);
try {
doHttpAPI(method);
} catch (MonitorException e) {
log.warn(String.format("delete dashboard fail, dashboard id: %s", dashboardId), e);
}
}
/**
* Execute a delete method on the given path with httpClient.
*
* @param httpClient Http client instance
* @param path Path to be deleted
* @return http status
* @throws IOException on error
*/
public static int executeDeleteMethod(HttpClient httpClient, String path) throws IOException {
DeleteMethod deleteMethod = new DeleteMethod(path);
deleteMethod.setFollowRedirects(false);
int status = executeHttpMethod(httpClient, deleteMethod);
// do not throw error if already deleted
if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) {
throw DavGatewayHttpClientFacade.buildHttpResponseException(deleteMethod);
}
return status;
}
public HttpResponse delete(final RequestContext rq, Binding cmisBinding, String version, String cmisOperation) throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), cmisBinding, version, cmisOperation, null);
String url = endpoint.getUrl();
DeleteMethod req = new DeleteMethod(url.toString());
return submitRequest(req, rq);
}
public HttpResponse delete(final Class<?> c, final RequestContext rq, final Object entityId, final Object relationshipEntityId) throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null);
String url = endpoint.getUrl();
DeleteMethod req = new DeleteMethod(url);
return submitRequest(req, rq);
}
public HttpResponse delete(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
final String relationCollectionName, final Object relationshipEntityId, final Map<String, String> params) throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
relationshipEntityId, params);
String url = endpoint.getUrl();
DeleteMethod req = new DeleteMethod(url);
return submitRequest(req, rq);
}
@Override
public DeleteMethod getHttpMethod() throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(getRequestContext().getNetworkId(),
getScope(), getApiName(), getVersion(), getEntityCollectionName(),
getEntityId(), getRelationCollectionName(), getRelationshipEntityId(), getParams());
String url = endpoint.getUrl();
DeleteMethod req = new DeleteMethod(url);
setRequestHeaderIfAny(req);
return req;
}
@Test(groups = {"wso2.esb"}, description = "Sending complete URL to API and for dispatching")
public void testCompleteURLWithHTTPMethod() throws Exception {
DeleteMethod delete = new DeleteMethod(getApiInvocationURL("myApi1/order/21441/item/17440079" +
"?message_id=41ec2ec4-e629-4e04-9fdf-c32e97b35bd1"));
HttpClient httpClient = new HttpClient();
LogViewerClient logViewerClient = new LogViewerClient(contextUrls.getBackEndUrl(), getSessionCookie());
logViewerClient.clearLogs();
try {
httpClient.executeMethod(delete);
Assert.assertEquals(delete.getStatusLine().getStatusCode(), 202, "Response code mismatched");
} finally {
delete.releaseConnection();
}
LogEvent[] logEvents = logViewerClient.getAllRemoteSystemLogs();
boolean isLogMessageFound = false;
for (LogEvent log : logEvents) {
if (log != null && log.getMessage().contains("order API INVOKED")) {
isLogMessageFound = true;
break;
}
}
Assert.assertTrue(isLogMessageFound, "Request Not Dispatched to API when HTTP method having full url");
}
/**
* Checks the method being received and created a
* suitable ResponseHandler for this method.
*
* @param method Method to handle
* @return The handler for this response
* @throws MethodNotAllowedException If no method could be choose this exception is thrown
*/
public static ResponseHandler createResponseHandler(HttpMethod method) throws MethodNotAllowedException {
if (!AllowedMethodHandler.methodAllowed(method)) {
throw new MethodNotAllowedException("The method " + method.getName() + " is not in the AllowedHeaderHandler's list of allowed methods.", AllowedMethodHandler.getAllowHeader());
}
ResponseHandler handler = null;
if (method.getName().equals("OPTIONS")) {
handler = new OptionsResponseHandler((OptionsMethod) method);
} else if (method.getName().equals("GET")) {
handler = new GetResponseHandler((GetMethod) method);
} else if (method.getName().equals("HEAD")) {
handler = new HeadResponseHandler((HeadMethod) method);
} else if (method.getName().equals("POST")) {
handler = new PostResponseHandler((PostMethod) method);
} else if (method.getName().equals("PUT")) {
handler = new PutResponseHandler((PutMethod) method);
} else if (method.getName().equals("DELETE")) {
handler = new DeleteResponseHandler((DeleteMethod) method);
} else if (method.getName().equals("TRACE")) {
handler = new TraceResponseHandler((TraceMethod) method);
} else {
throw new MethodNotAllowedException("The method " + method.getName() + " was allowed by the AllowedMethodHandler, not by the factory.", handledMethods);
}
return handler;
}
protected static DeleteMethod httpDelete(String path, String user, String pwd)
throws IOException {
LOG.info("Connecting to {}", URL + path);
HttpClient httpClient = new HttpClient();
DeleteMethod deleteMethod = new DeleteMethod(URL + path);
deleteMethod.addRequestHeader("Origin", URL);
if (userAndPasswordAreNotBlank(user, pwd)) {
deleteMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
}
httpClient.executeMethod(deleteMethod);
LOG.info("{} - {}", deleteMethod.getStatusCode(), deleteMethod.getStatusText());
return deleteMethod;
}
private void deleteNoteForUser(String noteId, String user, String pwd) throws IOException {
DeleteMethod delete = httpDelete(("/notebook/" + noteId), user, pwd);
assertThat("Test delete method:", delete, isAllowed());
delete.releaseConnection();
// make sure note is deleted
if (!noteId.isEmpty()) {
Note deletedNote = TestUtils.getInstance(Notebook.class).getNote(noteId);
assertNull("Deleted note should be null", deletedNote);
}
}
private void testDeleteNote(String noteId) throws IOException {
DeleteMethod delete = httpDelete(("/notebook/" + noteId));
LOG.info("testDeleteNote delete response\n" + delete.getResponseBodyAsString());
assertThat("Test delete method:", delete, isAllowed());
delete.releaseConnection();
// make sure note is deleted
if (!noteId.isEmpty()) {
Note deletedNote = TestUtils.getInstance(Notebook.class).getNote(noteId);
assertNull("Deleted note should be null", deletedNote);
}
}