Example usage for org.apache.commons.httpclient HttpState addCookie

List of usage examples for org.apache.commons.httpclient HttpState addCookie

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpState addCookie.

Prototype

public void addCookie(Cookie paramCookie) 

Source Link

Usage

From source file:CookieDemoApp.java

/**
 *
 * Usage:/*from  w ww  .  jav  a2 s .c  om*/
 *          java CookieDemoApp http://mywebserver:80/
 *
 *  @param args command line arguments
 *                 Argument 0 is a URL to a web server
 *
 *
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Usage: java CookieDemoApp <url>");
        System.err.println("<url> The url of a webpage");
        System.exit(1);
    }
    // Get target URL
    String strURL = args[0];
    System.out.println("Target URL: " + strURL);

    // Get initial state object
    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and 
    // re-created, using a persistence mechanism of choice,
    Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);
    // and then added to your HTTP state instance
    initialState.addCookie(mycookie);

    // Get HTTP client instance
    HttpClient httpclient = new HttpClient();
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    httpclient.setState(initialState);

    // RFC 2101 cookie management spec is used per default
    // to parse, validate, format & match cookies
    httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    // A different cookie management spec can be selected
    // when desired

    //httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE);
    // Netscape Cookie Draft spec is provided for completeness
    // You would hardly want to use this spec in real life situations
    //httppclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // Compatibility policy is provided in order to mimic cookie
    // management of popular web browsers that is in some areas 
    // not 100% standards compliant

    // Get HTTP GET method
    GetMethod httpget = new GetMethod(strURL);
    // Execute HTTP GET
    int result = httpclient.executeMethod(httpget);
    // Display status code
    System.out.println("Response status code: " + result);
    // Get all the cookies
    Cookie[] cookies = httpclient.getState().getCookies();
    // Display the cookies
    System.out.println("Present cookies: ");
    for (int i = 0; i < cookies.length; i++) {
        System.out.println(" - " + cookies[i].toExternalForm());
    }
    // Release current connection to the connection pool once you are done
    httpget.releaseConnection();
}

From source file:com.zimbra.common.httpclient.HttpClientUtil.java

public static HttpState newHttpState(ZAuthToken authToken, String host, boolean isAdmin) {
    HttpState state = new HttpState();
    if (authToken != null) {
        Map<String, String> cookieMap = authToken.cookieMap(isAdmin);
        if (cookieMap != null) {
            for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
                state.addCookie(new Cookie(host, ck.getKey(), ck.getValue(), "/", null, false));
            }//from  www.  j a v  a  2 s .co m
        }
    }
    return state;
}

From source file:fedora.server.security.servletfilters.pubcookie.ConnectPubcookie.java

private static final HttpMethodBase setup(HttpClient client, URL url, Map requestParameters,
        Cookie[] requestCookies) {/*from   ww w.  java  2  s.  c  om*/
    LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()");
    HttpMethodBase method = null;
    if (requestParameters == null) {
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " requestParameters == null");
        method = new GetMethod(url.toExternalForm());
        //GetMethod is superclass to ExpectContinueMethod, so we don't require method.setUseExpectHeader(false);
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " after getting method");
    } else {
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " requestParameters != null");
        method = new PostMethod(url.toExternalForm()); // "http://localhost:8080/"
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " after getting method");

        //XXX method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); //new way
        //XXX method.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, 10000);            
        //XXX method.getParams().setVersion(HttpVersion.HTTP_0_9); //or HttpVersion.HTTP_1_0 HttpVersion.HTTP_1_1

        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " after setting USE_EXPECT_CONTINUE");

        //PostMethod is subclass of ExpectContinueMethod, so we require here:            
        //((PostMethod)method).setUseExpectHeader(false);
        //client.setTimeout(30000); // increased from 10000 as temp fix; 2005-03-17 wdn5e
        //HttpClientParams httpClientParams = new HttpClientParams();
        //httpClientParams.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); //old way
        //httpClientParams.setIntParameter(HttpMethodParams.SO_TIMEOUT, 30000);

        LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()" + " A");

        Part[] parts = new Part[requestParameters.size()];
        Iterator iterator = requestParameters.keySet().iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            String fieldName = (String) iterator.next();
            String fieldValue = (String) requestParameters.get(fieldName);
            StringPart stringPart = new StringPart(fieldName, fieldValue);
            parts[i] = stringPart;
            LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()"
                    + " part[" + i + "]==" + fieldName + "=" + fieldValue);

            ((PostMethod) method).addParameter(fieldName, fieldValue); //old way
        }

        LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()" + " B");

        //XXX MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams());
        // ((PostMethod)method).setRequestEntity(multipartRequestEntity); //new way            
    }
    //method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    HttpState state = client.getState();
    for (Cookie cookie : requestCookies) {
        state.addCookie(cookie);
    }
    //method.setFollowRedirects(true); this is disallowed at runtime, so redirect won't be honored

    LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()" + " C");
    LogFactory.getLog(ConnectPubcookie.class)
            .debug(ConnectPubcookie.class.getName() + ".setup()" + " method==" + method);
    LogFactory.getLog(ConnectPubcookie.class)
            .debug(ConnectPubcookie.class.getName() + ".setup()" + " method==" + method.toString());
    return method;
}

From source file:com.twinsoft.convertigo.engine.util.CookiesUtils.java

public static void addCookie(HttpState httpState, String domain, String name, String value, String path,
        Date expires, boolean secure) {
    Cookie cookie = null;//  ww  w  .  ja va2  s . c o m
    try {
        Engine.logBeans.debug(String.format(
                "(CookiesUtils) Adding cookie: "
                        + "domain=%s, name=%s, value=%s, path=%s, expires=%s, secure=%s",
                domain, name, value, path, expires.toString(), Boolean.toString(secure)));

        cookie = new Cookie(domain, name, value, path, expires, secure);
        if (cookie != null) {
            Engine.logBeans.debug("(CookiesUtils) added cookie: " + cookie);
            httpState.addCookie(cookie);
        }
    } catch (Exception e) {
        Engine.logBeans.debug("(CookiesUtils) failed to parse cookie: " + cookie);
    }
}

From source file:com.zimbra.cs.util.SpamExtract.java

private static void extract(String authToken, Account account, Server server, String query, File outdir,
        boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException {
    String soapURL = getSoapURL(server, false);

    URL restURL = getServerURL(server, false);
    HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr
    HttpState state = new HttpState();
    GetMethod gm = new GetMethod();
    gm.setFollowRedirects(true);/*www.j a  va2s .co m*/
    Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1,
            false);
    state.addCookie(authCookie);
    hc.setState(state);
    hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(),
            Protocol.getProtocol(restURL.getProtocol()));
    gm.getParams().setSoTimeout(60000);

    if (verbose) {
        LOG.info("Mailbox requests to: " + restURL);
    }

    SoapHttpTransport transport = new SoapHttpTransport(soapURL);
    transport.setRetryCount(1);
    transport.setTimeout(0);
    transport.setAuthToken(authToken);

    int totalProcessed = 0;
    boolean haveMore = true;
    int offset = 0;
    while (haveMore) {
        Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST);
        searchReq.addElement(MailConstants.A_QUERY).setText(query);
        searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, MailItem.Type.MESSAGE.toString());
        searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset);
        searchReq.addAttribute(MailConstants.A_LIMIT, BATCH_SIZE);

        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchReq.prettyPrint());
            }
            Element searchResp = transport.invoke(searchReq, false, true, account.getId());
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchResp.prettyPrint());
            }

            StringBuilder deleteList = new StringBuilder();

            List<String> ids = new ArrayList<String>();
            for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) {
                offset++;
                Element e = iter.next();
                String mid = e.getAttribute(MailConstants.A_ID);
                if (mid == null) {
                    LOG.warn("null message id SOAP response");
                    continue;
                }

                LOG.debug("adding id %s", mid);
                ids.add(mid);
                if (ids.size() >= BATCH_SIZE || !iter.hasNext()) {
                    StringBuilder path = new StringBuilder("/service/user/" + account.getName()
                            + "/?fmt=tgz&list=" + StringUtils.join(ids, ","));
                    LOG.debug("sending request for path %s", path.toString());
                    List<String> extractedIds = extractMessages(hc, gm, path.toString(), outdir, raw);
                    if (ids.size() > extractedIds.size()) {
                        ids.removeAll(extractedIds);
                        LOG.warn("failed to extract %s", ids);
                    }
                    for (String id : extractedIds) {
                        deleteList.append(id).append(',');
                    }

                    ids.clear();
                }
                totalProcessed++;
            }

            haveMore = false;
            String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE);
            if (more != null && more.length() > 0) {
                try {
                    int m = Integer.parseInt(more);
                    if (m > 0) {
                        haveMore = true;
                        try {
                            Thread.sleep(SLEEP_TIME);
                        } catch (InterruptedException e) {
                        }
                    }
                } catch (NumberFormatException nfe) {
                    LOG.warn("more flag from server not a number: " + more, nfe);
                }
            }

            if (delete && deleteList.length() > 0) {
                deleteList.deleteCharAt(deleteList.length() - 1); // -1 removes trailing comma
                Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST);
                Element action = msgActionReq.addElement(MailConstants.E_ACTION);
                action.addAttribute(MailConstants.A_ID, deleteList.toString());
                action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE);

                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionReq.prettyPrint());
                }
                Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId());
                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionResp.prettyPrint());
                }
                offset = 0; //put offset back to 0 so we always get top N messages even after delete
            }
        } finally {
            gm.releaseConnection();
        }

    }
    LOG.info("Total messages processed: " + totalProcessed);
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method,
        HttpState state) throws IOException, ServiceException {
    // create an HTTP client with the same cookies
    javax.servlet.http.Cookie cookies[] = req.getCookies();
    String hostname = method.getURI().getHost();
    boolean hasZMAuth = hasZimbraAuthCookie(state);
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth)
                continue;
            state.addCookie(
                    new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false));
        }//  ww w .j  a  va 2 s .c  o  m
    }
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    if (state != null)
        client.setState(state);

    int hopcount = 0;
    for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) {
        String hname = (String) enm.nextElement(), hlc = hname.toLowerCase();
        if (hlc.equals("x-zimbra-hopcount"))
            try {
                hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0);
            } catch (NumberFormatException e) {
            }
        else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization"))
            method.addRequestHeader(hname, req.getHeader(hname));
    }
    if (hopcount >= MAX_PROXY_HOPCOUNT)
        throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req));
    method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1));
    if (method.getRequestHeader("X-Zimbra-Orig-Url") == null)
        method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString());
    String ua = req.getHeader("User-Agent");
    if (ua != null)
        method.setRequestHeader("User-Agent", ua);

    // dispatch the request and copy over the results
    int statusCode = -1;
    for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) {
        statusCode = HttpClientUtil.executeMethod(client, method);
    }
    if (statusCode == -1) {
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached");
        return;
    } else if (statusCode >= 300) {
        resp.sendError(statusCode, method.getStatusText());
        return;
    }

    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String hname = headers[i].getName(), hlc = hname.toLowerCase();
        if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-"))
            resp.addHeader(hname, headers[i].getValue());
    }
    InputStream responseStream = method.getResponseBodyAsStream();
    if (responseStream == null || resp.getOutputStream() == null)
        return;
    ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false);
}

From source file:com.zimbra.cs.service.UserServlet.java

private static Pair<Header[], HttpMethod> doHttpOp(ZAuthToken authToken, HttpMethod method)
        throws ServiceException {
    // create an HTTP client with the same cookies
    String url = "";
    String hostname = "";
    try {/* w  ww. ja  v a2  s  .  c  o m*/
        url = method.getURI().toString();
        hostname = method.getURI().getHost();
    } catch (IOException e) {
        log.warn("can't parse target URI", e);
    }

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Map<String, String> cookieMap = authToken.cookieMap(false);
    if (cookieMap != null) {
        HttpState state = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            state.addCookie(new org.apache.commons.httpclient.Cookie(hostname, ck.getKey(), ck.getValue(), "/",
                    null, false));
        }
        client.setState(state);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

    if (method instanceof PutMethod) {
        long contentLength = ((PutMethod) method).getRequestEntity().getContentLength();
        if (contentLength > 0) {
            int timeEstimate = Math.max(10000, (int) (contentLength / 100)); // 100kbps in millis
            // cannot set connection time using our ZimbrahttpConnectionManager,
            // see comments in ZimbrahttpConnectionManager.
            // actually, length of the content to Put should not be a factor for
            // establishing a connection, only read time out matter, which we set
            // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate);

            method.getParams().setSoTimeout(timeEstimate);
        }
    }

    try {
        int statusCode = HttpClientUtil.executeMethod(client, method);
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN)
            throw MailServiceException.NO_SUCH_ITEM(-1);
        else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NO_CONTENT)
            throw ServiceException.RESOURCE_UNREACHABLE(method.getStatusText(), null,
                    new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR),
                    new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode,
                            ServiceException.Argument.Type.NUM));

        List<Header> headers = new ArrayList<Header>(Arrays.asList(method.getResponseHeaders()));
        headers.add(new Header("X-Zimbra-Http-Status", "" + statusCode));
        return new Pair<Header[], HttpMethod>(headers.toArray(new Header[0]), method);
    } catch (HttpException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e);
    }
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@Test
public void testMissingCsrfAdminUpload() 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);/* w w w .  j a  va 2 s.c om*/
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    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()));
    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);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@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);//  w  ww .j  av  a 2 s.c o m
    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);
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK,
            statusCode);
    String resp = post.getResponseBodyAsString();
    assertNotNull("Response should not be empty", resp);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@Test
public void testAdminUploadWithCsrfInFormField() 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);/* www. j  a  v a 2  s . c  o m*/
    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()));
    Part csrfPart = new StringPart("csrfToken", csrfToken);
    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, csrfPart }, 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);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}