Search in sources :

Example 66 with PostMethod

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

the class TestDeployZimlet method adminUpload.

public String adminUpload(String authToken, String fileName, String filePath) throws Exception {
    PostMethod post = new PostMethod(ADMIN_UPLOAD_URL);
    FilePart part = new FilePart(fileName, new FilePartSource(new File(filePath)));
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie(localServer.getServiceHostname(), ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams()));
    int statusCode = HttpClientUtil.executeMethod(client, post);
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = post.getResponseBodyAsString();
    assertNotNull("Response should not be empty", resp);
    ZimbraLog.test.debug("Upload response " + resp);
    String[] responseParts = resp.split(",", 3);
    String aid = null;
    if (responseParts.length == 3) {
        aid = responseParts[2].trim();
        if (aid.startsWith("'") || aid.startsWith("\"")) {
            aid = aid.substring(1);
        }
        if (aid.endsWith("'") || aid.endsWith("\"")) {
            aid = aid.substring(0, aid.length() - 1);
        }
    }
    return aid;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) FilePartSource(org.apache.commons.httpclient.methods.multipart.FilePartSource) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) File(java.io.File)

Example 67 with PostMethod

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

the class TestWaitSetRequest method sendReq.

private Object sendReq(String requestBody, String requestCommand) throws HttpException, IOException, ServiceException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(TestUtil.getSoapUrl() + requestCommand);
    post.setRequestEntity(new StringRequestEntity(requestBody, "application/soap+xml", "UTF-8"));
    int respCode = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals(200, respCode);
    Element envelope = W3cDomUtil.parseXML(post.getResponseBodyAsStream());
    SoapProtocol proto = SoapProtocol.determineProtocol(envelope);
    Element doc = proto.getBodyElement(envelope);
    return JaxbUtil.elementToJaxb(doc);
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) Element(com.zimbra.common.soap.Element) SoapProtocol(com.zimbra.common.soap.SoapProtocol)

Example 68 with PostMethod

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

the class TestZimbraHttpConnectionManager method testSoTimeoutViaHttpPostMethod.

// @Test
public void testSoTimeoutViaHttpPostMethod() throws Exception {
    int serverPort = 7778;
    String resourceToPost = "/opt/zimbra/unittest/rights-unittest.xml";
    // delay 10 seconds in server
    long delayInServer = 100000;
    // 3000;  // 3 seconds, 0 for infinite wait
    int soTimeout = 60000;
    String qp = "?" + SimpleHttpServer.DelayWhen.BEFORE_WRITING_RESPONSE_HEADERS.name() + "=" + delayInServer;
    String uri = "http://localhost:" + serverPort + resourceToPost + qp;
    // start a http server for testing
    SimpleHttpServer.start(serverPort);
    // post the exported content to the target server
    HttpClient httpClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod method = new PostMethod(uri);
    // infinite wait because it can take a long time to import a large mailbox
    method.getParams().setSoTimeout(soTimeout);
    File file = new File(resourceToPost);
    FileInputStream fis = null;
    long startTime = System.currentTimeMillis();
    long endTime;
    try {
        fis = new FileInputStream(file);
        InputStreamRequestEntity isre = new InputStreamRequestEntity(fis, file.length(), MimeConstants.CT_APPLICATION_OCTET_STREAM);
        method.setRequestEntity(isre);
        int respCode = httpClient.executeMethod(method);
        dumpResponse(respCode, method, "");
        // nope, it should have timed out
        Assert.fail();
    } catch (java.net.SocketTimeoutException e) {
        e.printStackTrace();
        // good, just what we want
        endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("Client timed out after " + elapsedTime + " msecs");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    } finally {
        method.releaseConnection();
    }
    // shutdown the server
    SimpleHttpServer.shutdown();
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) java.net(java.net) ServiceException(com.zimbra.common.service.ServiceException)

Example 69 with PostMethod

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

the class TestAuth method clearCookie.

@Test
public void clearCookie() throws Exception {
    // 2 seconds
    int authTokenLifetimeMSecs = 2000;
    int waitMSecs = authTokenLifetimeMSecs + 1000;
    Account acct = provUtil.createGlobalAdmin(genAcctNameLocalPart(), domain);
    // set the account's auth token lifetime to a short period
    acct.setAdminAuthTokenLifetime(String.valueOf(authTokenLifetimeMSecs) + "ms");
    // String authToken = getAuthToken(acct.getName(), true);
    SoapTransport transport = authAdmin(acct.getName());
    // wait till the auto token expire
    Thread.sleep(waitMSecs);
    // make sure the auth token is indeed expired
    boolean caughtAuthExpired = false;
    try {
        NoOpRequest noOpReq = new NoOpRequest();
        NoOpResponse noOpResp = invokeJaxb(transport, noOpReq);
    } catch (ServiceException e) {
        if (AccountServiceException.AUTH_EXPIRED.equals(e.getCode())) {
            caughtAuthExpired = true;
        }
    }
    assertTrue(caughtAuthExpired);
    List<CookieSpec> cookiesToClear = Lists.newArrayList(new CookieSpec(ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN));
    ClearCookieRequest req = new ClearCookieRequest(cookiesToClear);
    /*
         * test the regular path when auto token control is not set
         * (auth token in soap header)
         */
    caughtAuthExpired = false;
    try {
        invokeJaxb(transport, req);
    } catch (ServiceException e) {
        if (AccountServiceException.AUTH_EXPIRED.equals(e.getCode())) {
            caughtAuthExpired = true;
        }
    }
    assertTrue(caughtAuthExpired);
    /*
         * test the regular path when auto token control is not set
         * (auth token in cookie)
         */
    String authToken = transport.getAuthToken().getValue();
    SoapTransport authTokenInCookieTransport = new AuthTokenInCookieTransport(authToken, true);
    caughtAuthExpired = false;
    try {
        invokeJaxb(authTokenInCookieTransport, req);
    } catch (ServiceException e) {
        if (AccountServiceException.AUTH_EXPIRED.equals(e.getCode())) {
            caughtAuthExpired = true;
        }
    }
    assertTrue(caughtAuthExpired);
    /*
         * test the path when auth token control voidOnExpired is true
         */
    // debug listener to verify the cookie is cleared
    SoapDebugListener verifyCookieClearedListener = new SoapDebugListener(Level.ALL) {

        @Override
        public void receiveSoapMessage(PostMethod postMethod, Element envelope) {
            super.receiveSoapMessage(postMethod, envelope);
            // verify cookies are cleared
            Header[] headers = postMethod.getResponseHeaders();
            boolean cookieCleared = false;
            for (Header header : headers) {
                if (header.toString().trim().equals("Set-Cookie: ZM_ADMIN_AUTH_TOKEN=;Path=/;Expires=Thu, 01-Jan-1970 00:00:00 GMT")) {
                    cookieCleared = true;
                }
            // System.out.println(header.toString().trim()); // trim the ending crlf
            }
            assertTrue(cookieCleared);
        }
    };
    authTokenInCookieTransport = new AuthTokenInCookieTransport(authToken, true, true, verifyCookieClearedListener);
    // should NOT get AUTH_EXPIRED
    ClearCookieResponse resp = invokeJaxb(authTokenInCookieTransport, req);
    provUtil.deleteAccount(acct);
}
Also used : Account(com.zimbra.cs.account.Account) NoOpRequest(com.zimbra.soap.admin.message.NoOpRequest) PostMethod(org.apache.commons.httpclient.methods.PostMethod) Element(com.zimbra.common.soap.Element) AccountServiceException(com.zimbra.cs.account.AccountServiceException) ServiceException(com.zimbra.common.service.ServiceException) Header(org.apache.commons.httpclient.Header) NoOpResponse(com.zimbra.soap.admin.message.NoOpResponse) ClearCookieRequest(com.zimbra.soap.admin.message.ClearCookieRequest) ClearCookieResponse(com.zimbra.soap.admin.message.ClearCookieResponse) CookieSpec(com.zimbra.soap.admin.type.CookieSpec) SoapTransport(com.zimbra.common.soap.SoapTransport) Test(org.junit.Test)

Example 70 with PostMethod

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

the class TestFileUpload method testAdminUploadWithCsrfInHeader.

@Test
public void testAdminUploadWithCsrfInHeader() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams()));
    post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken);
    int statusCode = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = post.getResponseBodyAsString();
    Assert.assertNotNull("Response should not be empty", resp);
    Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HeaderElement(org.apache.commons.httpclient.HeaderElement) Element(com.zimbra.common.soap.Element) HttpState(org.apache.commons.httpclient.HttpState) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ServiceException(com.zimbra.common.service.ServiceException) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport) Test(org.junit.Test)

Aggregations

PostMethod (org.apache.commons.httpclient.methods.PostMethod)203 HttpClient (org.apache.commons.httpclient.HttpClient)114 Test (org.junit.Test)55 IOException (java.io.IOException)32 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)28 Part (org.apache.commons.httpclient.methods.multipart.Part)25 NameValuePair (org.apache.commons.httpclient.NameValuePair)24 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)23 Map (java.util.Map)21 GetMethod (org.apache.commons.httpclient.methods.GetMethod)21 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)21 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)21 HttpMethod (org.apache.commons.httpclient.HttpMethod)17 Header (org.apache.commons.httpclient.Header)16 Note (org.apache.zeppelin.notebook.Note)13 HttpException (org.apache.commons.httpclient.HttpException)12 File (java.io.File)11 InputStream (java.io.InputStream)11 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)11 JSONParser (org.json.simple.parser.JSONParser)11