Java 类org.apache.commons.httpclient.methods.DeleteMethod 实例源码

项目:kekoa    文件:HttpClient.java   
/**
 * 处理http deletemethod请求
 */

public Response delete(String url, PostParameter[] params, String token)
        throws WeiboException {
    if (0 != params.length) {
        String encodedParams = HttpClient.encodeParameters(params);
        if (-1 == url.indexOf("?")) {
            url += "?" + encodedParams;
        } else {
            url += "&" + encodedParams;
        }
    }
    DeleteMethod deleteMethod = new DeleteMethod(url);
    return httpRequest(deleteMethod, token);

}
项目:incubator-zeppelin-druid    文件:ZeppelinRestApiTest.java   
@Test
public void testDeleteParagraph() throws IOException {
  Note note = ZeppelinServer.notebook.createNote();

  Paragraph p = note.addParagraph();
  p.setTitle("title1");
  p.setText("text1");

  note.persist();

  DeleteMethod delete = httpDelete("/notebook/" + note.getId() + "/paragraph/" + p.getId());
  assertThat("Test delete method: ", delete, isAllowed());
  delete.releaseConnection();

  Note retrNote = ZeppelinServer.notebook.getNote(note.getId());
  Paragraph retrParagrah = retrNote.getParagraph(p.getId());
  assertNull("paragraph should be deleted", retrParagrah);

  ZeppelinServer.notebook.removeNote(note.getId());
}
项目:Zoo    文件:HttpUtil.java   
/**
 * Factory method to create a {@link HttpMethod}-object according to the 
 * given String <code>httpMethod</codde>
 * 
 * @param httpMethodString the name of the {@link HttpMethod} to create
 * @param url
 * 
 * @return an object of type {@link GetMethod}, {@link PutMethod}, 
 * {@link PostMethod} or {@link DeleteMethod}
 * @throws IllegalArgumentException if <code>httpMethod</code> is none of
 * <code>GET</code>, <code>PUT</code>, <code>POST</POST> or <code>DELETE</code>
 */
public static HttpMethod createHttpMethod(String httpMethodString, String url) {

    if ("GET".equals(httpMethodString)) {
        return new GetMethod(url);
    }
    else if ("PUT".equals(httpMethodString)) {
        return new PutMethod(url);
    }
    else if ("POST".equals(httpMethodString)) {
        return new PostMethod(url);
    }
    else if ("DELETE".equals(httpMethodString)) {
        return new DeleteMethod(url);
    }
    else {
        throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown");
    }
}
项目:Java-sdk    文件:HttpUtils.java   
/**
 * 处理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);
}
项目:zeppelin    文件:ZeppelinRestApiTest.java   
@Test
public void testDeleteParagraph() throws IOException {
  Note note = ZeppelinServer.notebook.createNote(anonymous);

  Paragraph p = note.addNewParagraph(AuthenticationInfo.ANONYMOUS);
  p.setTitle("title1");
  p.setText("text1");

  note.persist(anonymous);

  DeleteMethod delete = httpDelete("/notebook/" + note.getId() + "/paragraph/" + p.getId());
  assertThat("Test delete method: ", delete, isAllowed());
  delete.releaseConnection();

  Note retrNote = ZeppelinServer.notebook.getNote(note.getId());
  Paragraph retrParagrah = retrNote.getParagraph(p.getId());
  assertNull("paragraph should be deleted", retrParagrah);

  ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
}
项目:zeppelin    文件:InterpreterRestApiTest.java   
@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();
}
项目:openhab-hdl    文件:HttpUtil.java   
/**
 * Factory method to create a {@link HttpMethod}-object according to the 
 * given String <code>httpMethod</codde>
 * 
 * @param httpMethodString the name of the {@link HttpMethod} to create
 * @param url
 * 
 * @return an object of type {@link GetMethod}, {@link PutMethod}, 
 * {@link PostMethod} or {@link DeleteMethod}
 * @throws IllegalArgumentException if <code>httpMethod</code> is none of
 * <code>GET</code>, <code>PUT</code>, <code>POST</POST> or <code>DELETE</code>
 */
public static HttpMethod createHttpMethod(String httpMethodString, String url) {

    if ("GET".equals(httpMethodString)) {
        return new GetMethod(url);
    }
    else if ("PUT".equals(httpMethodString)) {
        return new PutMethod(url);
    }
    else if ("POST".equals(httpMethodString)) {
        return new PostMethod(url);
    }
    else if ("DELETE".equals(httpMethodString)) {
        return new DeleteMethod(url);
    }
    else {
        throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown");
    }
}
项目:WordsDetection    文件:HttpClient.java   
/**
 * 处理http deletemethod请求
 */

public Response delete(String url, PostParameter[] params, String token) throws WeiboException {
    if (0 != params.length) {
        String encodedParams = HttpClient.encodeParameters(params);
        if (-1 == url.indexOf("?")) {
            url += "?" + encodedParams;
        }
        else {
            url += "&" + encodedParams;
        }
    }
    DeleteMethod deleteMethod = new DeleteMethod(url);
    return httpRequest(deleteMethod, token);

}
项目:olat    文件:CourseITCase.java   
@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());
    }
}
项目:olat    文件:UserAuthenticationMgmtITCase.java   
@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);
}
项目:olat    文件:CatalogITCase.java   
@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()));
    }
}
项目:olat    文件:CatalogITCase.java   
@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);
}
项目:olat    文件:CourseITCase.java   
@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());
    }
}
项目:olat    文件:UserAuthenticationMgmtITCase.java   
@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);
}
项目:olat    文件:CatalogITCase.java   
@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()));
    }
}
项目:olat    文件:CatalogITCase.java   
@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);
}
项目:community-edition-old    文件:RemoteConnectorRequestImpl.java   
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");
}
项目:OLE-INST    文件:TransferUtil.java   
@Deprecated
public String getDeleteResponseFromDocStore(String operation, String uuid, BoundwithForm transferForm)
        throws IOException {
    String restfulUrl = ConfigContext.getCurrentContextConfig().getProperty("docstore.restful.url");
    restfulUrl = restfulUrl.concat("/") + uuid;
    HttpClient httpClient = new HttpClient();
    DeleteMethod deleteMethod = new DeleteMethod(restfulUrl);
    NameValuePair nvp1 = new NameValuePair("identifierType", "UUID");
    NameValuePair nvp2 = new NameValuePair("operation", operation);

    NameValuePair category = new NameValuePair("docCategory", transferForm.getDocCategory());
    NameValuePair type = new NameValuePair("docType", transferForm.getDocType());
    NameValuePair format = new NameValuePair("docFormat", transferForm.getDocFormat());
    deleteMethod.setQueryString(new NameValuePair[]{nvp1, nvp2, category, type, format});
    int statusCode = httpClient.executeMethod(deleteMethod);
    if (LOG.isDebugEnabled()){
        LOG.debug("statusCode-->" + statusCode);
    }
    InputStream inputStream = deleteMethod.getResponseBodyAsStream();
    return IOUtils.toString(inputStream);
}
项目:OLE-INST    文件:OleDocstoreHelperServiceImpl.java   
public String deleteDocstoreRecord(String docType, String uuid) throws IOException {
    String docstoreRestfulURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
            OLEConstants.OLE_DOCSTORE_RESTFUL_URL);
    docstoreRestfulURL = docstoreRestfulURL.concat("/") + uuid;
    HttpClient httpClient = new HttpClient();
    DeleteMethod deleteMethod = new DeleteMethod(docstoreRestfulURL);
    NameValuePair nvp1 = new NameValuePair(OLEConstants.IDENTIFIER_TYPE, OLEConstants.UUID);
    NameValuePair nvp2 = new NameValuePair(OLEConstants.OPERATION, OLEConstants.DELETE);
    NameValuePair category = new NameValuePair(OLEConstants.DOC_CATEGORY, OLEConstants.BIB_CATEGORY_WORK);
    NameValuePair type = new NameValuePair(OLEConstants.DOC_TYPE, docType);
    NameValuePair format = new NameValuePair(OLEConstants.DOC_FORMAT, OLEConstants.BIB_FORMAT_OLEML);
    deleteMethod.setQueryString(new NameValuePair[]{nvp1, nvp2, category, type, format});
    int statusCode = httpClient.executeMethod(deleteMethod);
    InputStream inputStream = deleteMethod.getResponseBodyAsStream();
    return IOUtils.toString(inputStream);
}
项目:OLE-INST    文件:DocstoreHelperService.java   
public Response performRestFulOperation(String docCategory, String docType, String docFormat, String ids) throws Exception {

        String restfulUrl = ConfigContext.getCurrentContextConfig().getProperty("docstore.restful.url");
        restfulUrl = restfulUrl.concat("/") + ids;
        HttpClient httpClient = new HttpClient();
        DeleteMethod deleteMethod = new DeleteMethod(restfulUrl);
        NameValuePair nvp1 = new NameValuePair("identifierType", "UUID");
        NameValuePair nvp2 = new NameValuePair("operation", "delete");
        // NameValuePair nvp3 = new NameValuePair("id", ids);
        NameValuePair category = new NameValuePair("docCategory", docCategory);
        NameValuePair type = new NameValuePair("docType", docType);
        NameValuePair format = new NameValuePair("docFormat", docFormat);
        deleteMethod.setQueryString(new NameValuePair[]{nvp1, nvp2, category, type, format});
        int statusCode = httpClient.executeMethod(deleteMethod);
        LOG.info("statusCode-->" + statusCode);
        InputStream inputStream = deleteMethod.getResponseBodyAsStream();
        String responseXML = IOUtils.toString(inputStream, "UTF-8");
        LOG.info("Response-->" + responseXML);
        return new ResponseHandler().toObject(responseXML);
    }
项目:class-guard    文件:CommonsClientHttpRequestFactory.java   
/**
 * Create a Commons HttpMethodBase object for the given HTTP method
 * and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) {
    switch (httpMethod) {
        case GET:
            return new GetMethod(uri);
        case DELETE:
            return new DeleteMethod(uri);
        case HEAD:
            return new HeadMethod(uri);
        case OPTIONS:
            return new OptionsMethod(uri);
        case POST:
            return new PostMethod(uri);
        case PUT:
            return new PutMethod(uri);
        case TRACE:
            return new TraceMethod(uri);
        case PATCH:
            throw new IllegalArgumentException(
                    "HTTP method PATCH not available before Apache HttpComponents HttpClient 4.2");
        default:
            throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
    }
}
项目:wso2-axis2    文件:HTTPSender.java   
/**
 * Used to send a request via HTTP Delete Method
 *
 * @param msgContext        - The MessageContext of the message
 * @param url               - The target URL
 * @param soapActiionString - The soapAction string of the request
 * @throws AxisFault - Thrown in case an exception occurs
 */
private void sendViaDelete(MessageContext msgContext, URL url, String soapActiionString)
        throws AxisFault {

    DeleteMethod deleteMethod = new DeleteMethod();
    HttpClient httpClient = getHttpClient(msgContext);
    populateCommonProperties(msgContext, url, deleteMethod, httpClient, soapActiionString);

    try {
        executeMethod(httpClient, msgContext, url, deleteMethod);
        handleResponse(msgContext, deleteMethod);
    } catch (IOException e) {
        log.info("Unable to sendViaDelete to url[" + url + "]", e);
        throw AxisFault.makeFault(e);
    } finally {
        cleanup(msgContext, deleteMethod);
    }
}
项目:pinot    文件:SchemaUtils.java   
/**
 * 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;
  }
}
项目:cloudstack    文件:BigSwitchBcfApi.java   
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");
    }
}
项目:pi    文件:OpsWebsiteAccessor.java   
public static void deleteUserIfExist(String username) throws IOException {
    // send a delete request for the pi-robustness user
    GetMethod getUser = new GetMethod(String.format(getUserUri(username), getOpsWebsiteUrl()));
    getUser.setRequestHeader("accept", MediaType.APPLICATION_JSON);

    HttpClient httpClient = logInClient();

    int getReturnCode = httpClient.executeMethod(getUser);

    if (getReturnCode == 200) {
        // user exists, so delete it
        LOG.debug(String.format("Deleting user " + username, getOpsWebsiteUrl()));
        DeleteMethod deleteUser = new DeleteMethod(String.format(getUserUri(username), getOpsWebsiteUrl()));
        httpClient.executeMethod(deleteUser);
    } else if (getReturnCode == 404) {
        LOG.debug("User " + username + " already deleted.");
    }
}
项目:gooddata-agent    文件:GdcRESTApiWrapper.java   
/**
 * GDC logout - remove active session, if any exists
 *
 * @throws HttpMethodException
 */
public void logout() throws HttpMethodException {
    if (userLogin == null)
        return;
    l.debug("Logging out.");
    DeleteMethod logoutDelete = createDeleteMethod(getServerUrl() + userLogin.getString("state"));
    try {
        String resp = executeMethodOk(logoutDelete, false); // do not re-login on SC_UNAUTHORIZED
        userLogin = null;
        profile = null;
        l.debug("Successfully logged out.");
    } finally {
        logoutDelete.releaseConnection();
    }
    this.client = new HttpClient();
    NetUtil.configureHttpProxy( client );
}
项目:sinaWeiboAutoReply    文件:HttpClient.java   
/**
 * 处理http deletemethod请求
 */

public Response delete(String url, PostParameter[] params)
        throws WeiboException {
    if (0 != params.length) {
        String encodedParams = HttpClient.encodeParameters(params);
        if (-1 == url.indexOf("?")) {
            url += "?" + encodedParams;
        } else {
            url += "&" + encodedParams;
        }
    }
    DeleteMethod deleteMethod = new DeleteMethod(url);
    return httpRequest(deleteMethod);

}
项目:alfresco-repository    文件:RemoteConnectorRequestImpl.java   
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");
}
项目:oscm    文件:ResponseHandlerFactory.java   
/**
 * 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;
}
项目:alfresco-remote-api    文件:PublicApiHttpClient.java   
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);
}
项目:alfresco-remote-api    文件:PublicApiHttpClient.java   
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);
}
项目:alfresco-remote-api    文件:PublicApiHttpClient.java   
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);
}
项目:alfresco-remote-api    文件:PublicApiHttpClient.java   
@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;
}
项目:ditb    文件:Client.java   
/**
 * Send a DELETE request
 * @param cluster the cluster definition
 * @param path the path or URI
 * @return a Response object with response detail
 * @throws IOException
 */
public Response delete(Cluster cluster, String path) throws IOException {
  DeleteMethod method = new DeleteMethod();
  try {
    int code = execute(cluster, method, null, path);
    Header[] headers = method.getResponseHeaders();
    byte[] content = method.getResponseBody();
    return new Response(code, headers, content);
  } finally {
    method.releaseConnection();
  }
}
项目:scribe    文件:HTTPClient.java   
private static void deleteAccount() throws HttpException, IOException, Exception {
  System.out.println("Sent HTTP DELETE request to delete Account");
  String accountId = null;
  DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
  Document doc = docBuilder.parse(new File(testFolder + "Account.xml"));
  NodeList nodeList = doc.getElementsByTagName("Id");
  if (nodeList != null) {
    for (int i = 0; i <= nodeList.getLength(); i++) {
      Node accountIdNode = nodeList.item(i);
      if (accountIdNode != null) {
        System.out.println("Account Id " + accountIdNode.getTextContent());
        accountId = accountIdNode.getTextContent();
      }
    }
  }

  URL url = null;
  try {
    url = new URL(cadURL + "/object/account/" + accountId + "?_type=xml&agent=sfdcten~~ag1");
  } catch (MalformedURLException mue) {
    System.err.println(mue);
  }

  DeleteMethod delete = new DeleteMethod(url.toString());
  HttpClient httpclient = new HttpClient();
  try {
    System.out.println("URI: " + delete.getURI());
    int result = httpclient.executeMethod(delete);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: " + delete.getResponseBodyAsString());
  } finally {
    delete.releaseConnection();
  }
}
项目:product-ei    文件:ESBJAVA4852URITemplateWithCompleteURLTestCase.java   
@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");

}
项目:incubator-zeppelin-druid    文件: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;
}
项目:incubator-zeppelin-druid    文件:ZeppelinRestApiTest.java   
@Test
public void testSettingsCRUD() throws IOException {
  // Call Create Setting REST API
  String jsonRequest = "{\"name\":\"md2\",\"group\":\"md\",\"properties\":{\"propname\":\"propvalue\"},\"" +
      "interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\",\"name\":\"md\"}]}";
  PostMethod post = httpPost("/interpreter/setting/", jsonRequest);
  LOG.info("testSettingCRUD create response\n" + post.getResponseBodyAsString());
  assertThat("test create method:", post, isCreated());

  Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {
  }.getType());
  Map<String, Object> body = (Map<String, Object>) resp.get("body");
  //extract id from body string {id=2AWMQDNX7, name=md2, group=md,
  String newSettingId =  body.toString().split(",")[0].split("=")[1];
  post.releaseConnection();

  // Call Update Setting REST API
  jsonRequest = "{\"name\":\"md2\",\"group\":\"md\",\"properties\":{\"propname\":\"Otherpropvalue\"},\"" +
      "interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\",\"name\":\"md\"}]}";
  PutMethod put = httpPut("/interpreter/setting/" + newSettingId, jsonRequest);
  LOG.info("testSettingCRUD update response\n" + put.getResponseBodyAsString());
  assertThat("test update method:", put, isAllowed());
  put.releaseConnection();

  // Call Delete Setting REST API
  DeleteMethod delete = httpDelete("/interpreter/setting/" + newSettingId);
  LOG.info("testSettingCRUD delete response\n" + delete.getResponseBodyAsString());
  assertThat("Test delete method:", delete, isAllowed());
  delete.releaseConnection();
}
项目:incubator-zeppelin-druid    文件:ZeppelinRestApiTest.java   
private void testDeleteNotebook(String notebookId) throws IOException {

    DeleteMethod delete = httpDelete(("/notebook/" + notebookId));
    LOG.info("testDeleteNotebook delete response\n" + delete.getResponseBodyAsString());
    assertThat("Test delete method:", delete, isAllowed());
    delete.releaseConnection();
    // make sure note is deleted
    if (!notebookId.isEmpty()) {
      Note deletedNote = ZeppelinServer.notebook.getNote(notebookId);
      assertNull("Deleted note should be null", deletedNote);
    }
  }
项目:LCIndex-HBase-0.94.16    文件:Client.java   
/**
 * Send a DELETE request
 * @param cluster the cluster definition
 * @param path the path or URI
 * @return a Response object with response detail
 * @throws IOException
 */
public Response delete(Cluster cluster, String path) throws IOException {
  DeleteMethod method = new DeleteMethod();
  try {
    int code = execute(cluster, method, null, path);
    Header[] headers = method.getResponseHeaders();
    byte[] content = method.getResponseBody();
    return new Response(code, headers, content);
  } finally {
    method.releaseConnection();
  }
}