Search in sources :

Example 6 with DeleteMethod

use of org.apache.commons.httpclient.methods.DeleteMethod in project zeppelin by apache.

the class InterpreterRestApiTest method testAddDeleteRepository.

@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();
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) PostMethod(org.apache.commons.httpclient.methods.PostMethod) Test(org.junit.Test)

Example 7 with DeleteMethod

use of org.apache.commons.httpclient.methods.DeleteMethod in project zeppelin by apache.

the class AbstractTestRestApi method httpDelete.

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;
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) HttpClient(org.apache.commons.httpclient.HttpClient)

Example 8 with DeleteMethod

use of org.apache.commons.httpclient.methods.DeleteMethod in project pinot by linkedin.

the class SchemaUtils method deleteSchema.

/**
   * 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;
    }
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) URL(java.net.URL) IOException(java.io.IOException)

Example 9 with DeleteMethod

use of org.apache.commons.httpclient.methods.DeleteMethod in project zm-mailbox by Zimbra.

the class ProxyServlet method doProxy.

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }
    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);
    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));
    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }
        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }
        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode();
        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue();
        InputStream targetResponseBody = method.getResponseBodyAsStream();
        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()).getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";
            List<Upload> uploads = null;
            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }
            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName()))
                resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}
Also used : ContentType(com.zimbra.common.mime.ContentType) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) URL(java.net.URL) HttpException(org.apache.commons.httpclient.HttpException) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) Enumeration(java.util.Enumeration) InputStream(java.io.InputStream) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) ContentDisposition(com.zimbra.common.mime.ContentDisposition) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthToken(com.zimbra.cs.account.AuthToken) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 10 with DeleteMethod

use of org.apache.commons.httpclient.methods.DeleteMethod in project zm-mailbox by Zimbra.

the class TestCalDav method doDeleteMethod.

public HttpMethodExecutor doDeleteMethod(String url, Account authAcct, int expected) throws IOException {
    HttpClient client = new HttpClient();
    DeleteMethod deleteMethod = new DeleteMethod(url);
    addBasicAuthHeaderForUser(deleteMethod, authAcct);
    return HttpMethodExecutor.execute(client, deleteMethod, expected);
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) HttpClient(org.apache.commons.httpclient.HttpClient)

Aggregations

DeleteMethod (org.apache.commons.httpclient.methods.DeleteMethod)25 HttpClient (org.apache.commons.httpclient.HttpClient)9 IOException (java.io.IOException)8 HttpMethod (org.apache.commons.httpclient.HttpMethod)6 Test (org.junit.Test)6 HttpException (org.apache.commons.httpclient.HttpException)5 PostMethod (org.apache.commons.httpclient.methods.PostMethod)5 Note (org.apache.zeppelin.notebook.Note)5 GetMethod (org.apache.commons.httpclient.methods.GetMethod)4 PutMethod (org.apache.commons.httpclient.methods.PutMethod)4 Paragraph (org.apache.zeppelin.notebook.Paragraph)3 Account (com.zimbra.cs.account.Account)2 ElasticSearchConnector (com.zimbra.cs.index.elasticsearch.ElasticSearchConnector)2 URL (java.net.URL)2 Map (java.util.Map)2 Header (org.apache.commons.httpclient.Header)2 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)2 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)2 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1