Example usage for org.apache.commons.httpclient HttpClient getHttpConnectionManager

List of usage examples for org.apache.commons.httpclient HttpClient getHttpConnectionManager

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getHttpConnectionManager.

Prototype

public HttpConnectionManager getHttpConnectionManager()

Source Link

Usage

From source file:org.obm.caldav.obmsync.service.impl.ObmSyncProviderFactory.java

protected ObmSyncProviderFactory() {
    MultiThreadedHttpConnectionManager mtConMan = new MultiThreadedHttpConnectionManager();
    HttpClient ret = new HttpClient(mtConMan);
    HttpConnectionManagerParams mp = ret.getHttpConnectionManager().getParams();

    mp.setDefaultMaxConnectionsPerHost(10);
    mp.setMaxTotalConnections(20);/* w  w  w  .ja  v a2  s.  co  m*/

    this.hc = ret;
}

From source file:org.onecmdb.utils.wsdl.CMDBChangeUpload.java

public void sendFiles(String targetURL, String files[]) {
    PostMethod filePost = new PostMethod(targetURL);

    /*/*from   w w  w .  j av a 2s. com*/
      filePost.getParams().setBooleanParameter(
         HttpMethodParams.USE_EXPECT_CONTINUE,
         cbxExpectHeader.isSelected());
      */
    try {
        List<Part> partList = new ArrayList<Part>();
        for (String file : files) {
            System.out.println("Send file : " + file);
            File f = new File(file);
            partList.add(new FilePart(f.getName(), f));
        }
        Part[] parts = partList.toArray(new Part[0]);
        /*
        Part[] parts = {
         new FilePart(targetFile.getName(), targetFile)
        };
        */
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }

}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Checks if the given client files exist on the server and internally stores duplications.<p>
 * /* w w w.j  a v  a2 s  .  co  m*/
 * Comparison is made by cutting the current directory of the file chooser from the path of the given files. 
 * The server files (VFS files) to compare to are found by the current session of the user which finds the correct site and 
 * the knowledge about the current directory. File translation rules are taken into account on the server. <p>
 * 
 * @param files the local files to check if they exist in the VFS 
 * 
 * @return one of {@link ModalDialog#ERROR_OPTION} , {@link ModalDialog#CANCEL_OPTION}, {@link ModalDialog#APPROVE_OPTION}. 
 */
int checkServerOverwrites(File[] files) {

    m_action = m_actionOverwriteCheck;
    repaint();
    int rtv = ModalDialog.ERROR_OPTION;
    // collect files
    List fileNames = new ArrayList();
    for (int i = 0; i < files.length; i++) {
        getRelativeFilePaths(files[i], fileNames);
    }

    StringBuffer uploadFiles = new StringBuffer();
    Iterator it = fileNames.iterator();
    // Http post header is limited, therefore only a ceratain amount of files may be checked 
    // for server overwrites. Solution is: multiple requests. 
    int count = 0;
    List duplications;
    // request to server
    HttpClient client = new HttpClient();
    this.m_overwrites = new ArrayList();
    try {
        while (it.hasNext()) {
            count++;
            uploadFiles.append(((String) it.next())).append('\n');

            if (((count % 40) == 0) || (!it.hasNext())) {
                // files to upload:
                PostMethod post = new PostMethod(m_targetUrl);
                Header postHeader = new Header("uploadFiles",
                        URLEncoder.encode(uploadFiles.toString(), "utf-8"));
                post.addRequestHeader(postHeader);
                // upload folder in vfs: 
                Header header2 = new Header("uploadFolder",
                        URLEncoder.encode(getParameter("filelist"), "utf-8"));
                post.addRequestHeader(header2);

                // the action constant
                post.setParameter("action", DIALOG_CHECK_OVERWRITE);

                // add jsessionid query string
                String sessionId = getParameter("sessionId");
                String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
                post.setQueryString(query);
                post.addRequestHeader(C_JSESSIONID, sessionId);

                HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
                connectionParams.setConnectionTimeout(5000);

                // add the session cookie
                client.getState();
                client.getHostConfiguration().getHost();

                HttpState initialState = new HttpState();
                URI uri = new URI(m_targetUrl, false);
                Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
                initialState.addCookie(sessionCookie);
                client.setState(initialState);
                int status = client.executeMethod(post);

                if (status == HttpStatus.SC_OK) {
                    String response = post.getResponseBodyAsString();
                    duplications = parseDuplicateFiles(URLDecoder.decode(response, "utf-8"));
                    this.m_overwrites.addAll(duplications);

                } else {
                    // continue without overwrite check 
                    String error = m_errorLine1 + "\n" + post.getStatusLine();
                    System.err.println(error);
                }

                count = 0;
                uploadFiles = new StringBuffer();
            }

        }
        if (m_overwrites.size() > 0) {
            rtv = showDuplicationsDialog(m_overwrites);
        } else {
            rtv = ModalDialog.APPROVE_OPTION;
        }

    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

    return rtv;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Uploads the zipfile to the OpenCms.<p>
 * /* ww w.  j  a va  2  s.c  o m*/
 * @param uploadFile the zipfile to upload
 */
private void uploadZipFile(File uploadFile) {

    m_action = m_actionOutputUpload;
    repaint();

    PostMethod post = new PostMethod(m_targetUrl);

    try {
        Part[] parts = new Part[5];
        parts[0] = new FilePart(uploadFile.getName(), uploadFile);
        parts[1] = new StringPart("action", "submitform");
        parts[2] = new StringPart("unzipfile", "true");
        parts[3] = new StringPart("uploadfolder", m_uploadFolder);
        parts[4] = new StringPart("clientfolder", m_fileSelector.getCurrentDirectory().getAbsolutePath());

        HttpMethodParams methodParams = post.getParams();
        methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams);
        post.setRequestEntity(request);

        // add jsessionid query string
        String sessionId = getParameter("sessionId");
        String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
        post.setQueryString(query);
        post.addRequestHeader(C_JSESSIONID, sessionId);

        HttpClient client = new HttpClient();
        HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
        connectionParams.setConnectionTimeout(5000);

        // add the session cookie
        client.getState();
        client.getHostConfiguration().getHost();

        HttpState initialState = new HttpState();
        URI uri = new URI(m_targetUrl, false);
        Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
        initialState.addCookie(sessionCookie);
        client.setState(initialState);

        // no execute the file upload
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_OK) {
            //return to the specified url and frame target
            getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame);
        } else {
            // create the error text
            String error = m_errorLine1 + "\n" + post.getStatusLine();
            //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE);
            getAppletContext().showDocument(new URL(m_errorUrl + "?action=showerror&uploaderror=" + error),
                    "explorer_files");
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        // finally delete the zipFile on the harddisc
        uploadFile.delete();
    }
}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * @param since last modified time to use
 * @param req/*from   w  w w . j  a v a 2 s. co  m*/
 * @param url if null, ignored
 * @param redirCount number of redirs we've done
 */
public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl,
        int redirCount, int timeout)
        throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.
              
      if (res != null) {
    res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    }
    */

    try {

        // TODO: [2002-01-09 bloch] cope with cache-control
        // response headers (no-store, no-cache, must-revalidate, 
        // proxy-revalidate).

        if (surl == null) {
            surl = getURL(req);
        }
        if (surl == null || surl.equals("")) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="url is empty or null"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                            "051018-312"));
        }

        String reqType = "";
        String headers = "";

        if (req != null) {
            reqType = req.getParameter("reqtype");
            headers = req.getParameter("headers");
        }

        boolean isPost = false;
        mLogger.debug("reqtype = " + reqType);

        if (reqType != null && reqType.equals("POST")) {
            request = new LZPostMethod();
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            isPost = true;
            mLogger.debug("setting POST req method");
        } else if (reqType != null && reqType.equals("PUT")) {
            request = new LZPutMethod();
            // todo [hqm 2007] treat PUT like POST? 
            isPost = true;
            mLogger.debug("setting PUT req method");
        } else if (reqType != null && reqType.equals("DELETE")) {
            request = new LZDeleteMethod();
            mLogger.debug("setting DELETE req method");
        } else {
            mLogger.debug("setting GET (default) req method");
            request = new LZGetMethod();
        }

        request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0);

        // Proxy the request headers
        if (req != null) {
            LZHttpUtils.proxyRequestHeaders(req, request);
        }

        // Set headers from query string
        if (headers != null && headers.length() > 0) {
            StringTokenizer st = new StringTokenizer(headers, "\n");
            while (st.hasMoreTokens()) {
                String h = st.nextToken();
                int i = h.indexOf(":");
                if (i > -1) {
                    String n = h.substring(0, i);
                    String v = h.substring(i + 2, h.length());
                    request.setRequestHeader(n, v);
                    mLogger.debug(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes="setting header " + p[0] + "=" + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-359", new Object[] { n, v }));
                }
            }
        }

        mLogger.debug("Parsing url");
        URI uri = LZHttpUtils.newURI(surl);
        try {
            hcfg.setHost(uri);
        } catch (Exception e) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="can't form uri from " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376",
                            new Object[] { surl }));
        }

        // This gets us the url-encoded (escaped) path and query string
        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded path:  " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389",
                        new Object[] { path }));
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded query: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397",
                        new Object[] { query }));

        // This call takes a decoded (unescaped) path
        request.setPath(path);

        boolean hasQuery = (query != null && query.length() > 0);

        String rawcontent = null;
        // Newer rawpost protocol puts lzpostbody as a separate
        // top level query arg in the request.
        rawcontent = req.getParameter("lzpostbody");

        if (isPost) {
            // Older rawpost protocol put the "lzpostbody" arg
            // embedded in the "url" args's query args
            if (rawcontent == null && hasQuery) {
                rawcontent = findQueryArg("lzpostbody", query);
            }
            if (rawcontent != null) {
                // Get the unescaped query string
                ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent));
            } else if (hasQuery) {
                StringTokenizer st = new StringTokenizer(query, "&");
                while (st.hasMoreTokens()) {
                    String it = st.nextToken();
                    int i = it.indexOf("=");
                    if (i > 0) {
                        String n = it.substring(0, i);
                        String v = it.substring(i + 1, it.length());
                        // POST encodes values during request
                        ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
                    } else {
                        mLogger.warn(
                                /* (non-Javadoc)
                                 * @i18n.test
                                 * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                                 */
                                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                        "051018-429", new Object[] { it }));
                    }
                }
            }
        } else {
            // This call takes an encoded (escaped) query string
            request.setQueryString(query);
        }

        // Put in the If-Modified-Since headers
        if (since != -1) {
            String lms = LZHttpUtils.getDateString(since);
            request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="proxying lms: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450",
                            new Object[] { lms }));
        }

        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting up http client"
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460"));
        HttpClient htc = null;
        if (mConnectionMgr != null) {
            htc = new HttpClient(mConnectionMgr);
        } else {
            htc = new HttpClient();
        }

        htc.setHostConfiguration(hcfg);

        // This is the data timeout
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="timeout set to " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478",
                        new Object[] { timeout }));
        htc.getParams().setSoTimeout(timeout);

        // Set connection timeout the same
        htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout);

        // Set timeout for getting a connection
        htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout);

        // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
        if (!isPost) {
            request.setFollowRedirects(mFollowRedirects > 0);
        }

        long t1 = System.currentTimeMillis();
        mLogger.debug("starting remote request");
        int rc = htc.executeMethod(hcfg, request);
        String status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="remote response status: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504",
                        new Object[] { status }));

        HttpData data = null;
        if (isRedirect(rc) && mFollowRedirects > redirCount) {
            String loc = request.getResponseHeader("Location").toString();
            String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="Following URL from redirect: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517",
                            new Object[] { hostURI }));
            long t2 = System.currentTimeMillis();
            if (timeout > 0) {
                timeout -= (t2 - t1);
                if (timeout < 0) {
                    throw new InterruptedIOException(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-529", new Object[] { surl, loc }));
                }
            }

            data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
        } else {
            data = new HttpData(request, rc);
        }

        if (req != null && res != null) {
            // proxy response headers
            LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
        }

        return data;

    } catch (ConnectTimeoutException ce) {
        // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
        if (request != null) {
            request.releaseConnection();
        }
        throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557",
                        new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout }));
    } catch (HttpRecoverableException hre) {
        if (request != null) {
            request.releaseConnection();
        }
        throw hre;
    } catch (HttpException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    } catch (IOException ie) {
        if (request != null) {
            request.releaseConnection();
        }
        throw ie;
    } catch (RuntimeException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    }
}

From source file:org.openmrs.module.openconceptlab.client.OclClient.java

public OclResponse fetchUpdates(String url, String token, Date updatedSince) throws IOException {
    totalBytesToDownload = -1; //unknown yet
    bytesDownloaded = 0;/*  w ww.j a v  a 2 s .c o  m*/

    GetMethod get = new GetMethod(url);
    if (!StringUtils.isBlank(token)) {
        get.addRequestHeader("Authorization", "Token " + token);
        get.addRequestHeader("Compress", "true");
    }

    List<NameValuePair> query = new ArrayList<NameValuePair>();
    query.add(new NameValuePair("includeMappings", "true"));
    query.add(new NameValuePair("includeConcepts", "true"));
    query.add(new NameValuePair("includeRetired", "true"));
    query.add(new NameValuePair("limit", "100000"));

    if (updatedSince != null) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        query.add(new NameValuePair("updatedSince", dateFormat.format(updatedSince)));
    }

    get.setQueryString(query.toArray(new NameValuePair[0]));

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_IN_MS);
    client.executeMethod(get);

    if (get.getStatusCode() != 200) {
        throw new IOException(get.getStatusLine().toString());
    }

    return extractResponse(get);
}

From source file:org.openmrs.module.openconceptlab.client.OclClient.java

public OclResponse fetchInitialUpdates(String url, String token) throws IOException, HttpException {
    totalBytesToDownload = -1; //unknown yet
    bytesDownloaded = 0;//from   w w w .  j a va 2s. co  m

    if (url.endsWith("/")) {
        url = url.substring(0, url.length() - 1);
    }

    String latestVersion = fetchLatestVersion(url, token);

    String exportUrl = fetchExportUrl(url, token, latestVersion);

    GetMethod exportUrlGet = new GetMethod(exportUrl);

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_IN_MS);
    client.executeMethod(exportUrlGet);

    if (exportUrlGet.getStatusCode() != 200) {
        throw new IOException(exportUrlGet.getStatusLine().toString());
    }

    return extractResponse(exportUrlGet);
}

From source file:org.openmrs.module.openconceptlab.client.OclClient.java

private String fetchExportUrl(String url, String token, String latestVersion)
        throws IOException, HttpException {
    String latestVersionExportUrl = url + "/" + latestVersion + "/export";

    GetMethod latestVersionExportUrlGet = new GetMethod(latestVersionExportUrl);
    if (!StringUtils.isBlank(token)) {
        latestVersionExportUrlGet.addRequestHeader("Authorization", "Token " + token);
    }//from ww w.ja  v a 2 s. com

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_IN_MS);
    client.executeMethod(latestVersionExportUrlGet);
    if (latestVersionExportUrlGet.getStatusCode() != 200) {
        throw new IOException(latestVersionExportUrlGet.getPath() + " responded with "
                + latestVersionExportUrlGet.getStatusLine().toString());
    }

    String exportUrl = latestVersionExportUrlGet.getResponseHeader("exportURL").getValue();
    return exportUrl;
}

From source file:org.openmrs.module.openconceptlab.client.OclClient.java

private String fetchLatestVersion(String url, String token)
        throws IOException, HttpException, JsonParseException, JsonMappingException {
    String latestVersionUrl = url + "/latest";

    GetMethod latestVersionGet = new GetMethod(latestVersionUrl);
    if (!StringUtils.isBlank(token)) {
        latestVersionGet.addRequestHeader("Authorization", "Token " + token);
    }/*from  w  ww .  j a  va 2  s  . c o  m*/

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_IN_MS);
    client.executeMethod(latestVersionGet);
    if (latestVersionGet.getStatusCode() != 200) {
        throw new IOException(latestVersionGet.getStatusLine().toString());
    }

    ObjectMapper objectMapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
    Map<String, Object> latestVersionResponse = objectMapper
            .readValue(latestVersionGet.getResponseBodyAsStream(), Map.class);
    String latestVersion = (String) latestVersionResponse.get("id");
    return latestVersion;
}

From source file:org.openmrs.module.sync.server.ServerConnection.java

public static ConnectionResponse sendExportedData(String url, String username, String password, String content,
        boolean isResponse) {

    // Default response - default constructor instantiates contains error codes 
    ConnectionResponse syncResponse = new ConnectionResponse();

    HttpClient client = new HttpClient();

    url = url + SyncConstants.DATA_IMPORT_SERVLET;
    log.info("POST multipart request to " + url);

    if (url.startsWith("https")) {
        try {/*from  ww  w .j  av  a2 s.  c  o  m*/
            if (Boolean.parseBoolean(Context.getAdministrationService()
                    .getGlobalProperty(SyncConstants.PROPERTY_ALLOW_SELFSIGNED_CERTS))) {

                // It is necessary to provide a relative url (from the host name and port to the right)
                String relativeUrl;

                URI uri = new URI(url, true);
                String host = uri.getHost();
                int port = uri.getPort();

                // URI.getPort() returns -1 if port is not explicitly set
                if (port <= 0) {
                    port = SyncConstants.DEFAULT_HTTPS_PORT;
                    relativeUrl = url.split(host, 2)[1];
                } else {
                    relativeUrl = url.split(host + ":" + port, 2)[1];
                }

                Protocol easyhttps = new Protocol("https",
                        (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), port);
                client.getHostConfiguration().setHost(host, port, easyhttps);

                url = relativeUrl;
            }
        } catch (IOException ioe) {
            log.error("Unable to configure SSL to accept self-signed certificates");
        } catch (GeneralSecurityException e) {
            log.error("Unable to configure SSL to accept self-signed certificates");
        }
    }

    PostMethod method = new PostMethod(url);

    try {

        boolean useCompression = Boolean.parseBoolean(Context.getAdministrationService()
                .getGlobalProperty(SyncConstants.PROPERTY_ENABLE_COMPRESSION, "true"));

        log.info("use compression: " + useCompression);
        // Compress content
        ConnectionRequest request = new ConnectionRequest(content, useCompression);

        // Create up multipart request
        Part[] parts = {
                new FilePart("syncDataFile", new ByteArrayPartSource("syncDataFile", request.getBytes())),
                new StringPart("username", username), new StringPart("password", password),
                new StringPart("compressed", String.valueOf(useCompression)),
                new StringPart("isResponse", String.valueOf(isResponse)),
                new StringPart("checksum", String.valueOf(request.getChecksum())) };

        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        // Open a connection to the server and post the data
        client.getHttpConnectionManager().getParams().setSoTimeout(ServerConnection.getTimeout().intValue());
        client.getHttpConnectionManager().getParams()
                .setConnectionTimeout(ServerConnection.getTimeout().intValue());
        int status = client.executeMethod(method);

        // As long as the response is OK (200)
        if (status == HttpStatus.SC_OK) {
            // Decompress the response from the server
            //log.info("Response from server:" + method.getResponseBodyAsString());

            // Check to see if the child/parent sent back a compressed response
            Header compressionHeader = method.getResponseHeader("Enable-Compression");
            useCompression = (compressionHeader != null) ? new Boolean(compressionHeader.getValue()) : false;
            log.info("Response header Enable-Compression: " + useCompression);

            // Decompress the data received (if compression is enabled)
            syncResponse = new ConnectionResponse(method.getResponseBodyAsStream(), useCompression);

            // Now we want to validate the checksum
            Header checksumHeader = method.getResponseHeader("Content-Checksum");
            long checksumReceived = (checksumHeader != null) ? new Long(checksumHeader.getValue()) : 0;
            log.info("Response header Content-Checksum: " + checksumReceived);

            log.info("checksum value received in response header: " + checksumReceived);
            log.info("checksum of payload: " + syncResponse.getChecksum());

            // TODO Need to figure out what to do with this response
            if (checksumReceived > 0 && (checksumReceived != syncResponse.getChecksum())) {
                log.error("ERROR: FAILED CHECKSUM!");
                syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message           
            }
        }
        // if there's an error response code we should set the tran
        else {
            // HTTP error response code
            syncResponse
                    .setResponsePayload("HTTP " + status + " Error Code: " + method.getResponseBodyAsString());
            syncResponse.setState(ServerConnectionState.CONNECTION_FAILED); // contains error message 
        }

    } catch (MalformedURLException mue) {
        log.error("Malformed URL " + url, mue);
        syncResponse.setState(ServerConnectionState.MALFORMED_URL);
    } catch (Exception e) { // all other exceptions really just mean that the connection was bad
        log.error("Error occurred while sending/receiving data ", e);
        syncResponse.setState(ServerConnectionState.CONNECTION_FAILED);
    } finally {
        method.releaseConnection();
    }
    return syncResponse;
}