Example usage for org.apache.commons.httpclient HttpURL HttpURL

List of usage examples for org.apache.commons.httpclient HttpURL HttpURL

Introduction

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

Prototype

public HttpURL(char[] paramArrayOfChar) throws URIException, NullPointerException 

Source Link

Usage

From source file:com.mirth.connect.connectors.file.filesystems.WebDavConnection.java

public WebDavConnection(String host, boolean secure, FileSystemConnectionOptions fileSystemOptions)
        throws Exception {
    this.secure = secure;
    username = fileSystemOptions.getUsername();
    password = fileSystemOptions.getPassword();

    HttpURL url = null;/*from  ww w .  j a v  a 2 s .  c o m*/

    if (secure) {
        url = new HttpsURL("https://" + host);
    } else {
        url = new HttpURL("http://" + host);
    }

    if (!username.equals("null")) {
        url.setUserinfo(username, password);
    }

    client = new WebdavResource(url);
}

From source file:com.mirth.connect.connectors.file.filesystems.WebDavConnection.java

private List<FileInfo> list(String fromDir, boolean files, FilenameFilter filenameFilter, boolean ignoreDot)
        throws Exception {
    client.setPath(fromDir);//  w  ww. j a  v a  2s. c  o m
    WebdavResource[] resources = client.listWebdavResources();

    if (resources == null || resources.length == 0) {
        return new ArrayList<FileInfo>();
    }

    List<FileInfo> fileInfoList = new ArrayList<FileInfo>(resources.length);
    for (int i = 0; i < resources.length; i++) {

        WebdavFile file = null;
        String filePath = getFullPath(fromDir, resources[i].getPath());

        if (secure) {

            HttpsURL hrl = new HttpsURL("https://" + client.getHost() + filePath);
            if (!username.equals("null")) {
                hrl.setUserinfo(username, password);
            }
            file = new WebdavFile(hrl);

        } else {

            HttpURL hrl = new HttpURL("http://" + client.getHost() + filePath);
            if (!username.equals("null")) {
                hrl.setUserinfo(username, password);
            }
            file = new WebdavFile(hrl);

        }

        if (files) {
            if (file.isFile() && filenameFilter.accept(null, file.getName())
                    && !(ignoreDot && file.getName().startsWith("."))) {
                fileInfoList.add(new WebDavFileInfo(fromDir, file));
            }
        } else if (file.isDirectory()) {
            fileInfoList.add(new WebDavFileInfo(fromDir, file));
        }
    }

    return fileInfoList;
}

From source file:com.gist.twitter.TwitterClient.java

/**
 * Extracts the host and post from the baseurl and constructs an
 * appropriate AuthScope for them for use with HttpClient.
 *///from  ww w . jav  a 2 s . c o m
private AuthScope createAuthScope(String baseUrl) throws URIException {
    HttpURL url = new HttpURL(baseUrl);
    return new AuthScope(url.getHost(), url.getPort());
}

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

private static RemoteDataInfo retrieveRemoteData(String url, Folder.SyncData fsd)
        throws ServiceException, HttpException, IOException {
    assert !Strings.isNullOrEmpty(url);

    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);

    // cannot set connection timeout because it'll affect all HttpClients associated with the conn mgr.
    // see comments in ZimbraHttpConnectionManager
    // client.setConnectionTimeout(10000);

    HttpMethodParams params = new HttpMethodParams();
    params.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, MimeConstants.P_CHARSET_UTF8);
    params.setSoTimeout(60000);/*from w ww.  ja  va 2 s . co  m*/

    GetMethod get = null;
    BufferedInputStream content = null;
    long lastModified = 0;
    String expectedCharset = MimeConstants.P_CHARSET_UTF8;
    int redirects = 0;
    int statusCode = HttpServletResponse.SC_NOT_FOUND;
    try {
        do {
            String lcurl = url.toLowerCase();
            if (lcurl.startsWith("webcal:")) {
                url = "http:" + url.substring(7);
            } else if (lcurl.startsWith("feed:")) {
                url = "http:" + url.substring(5);
            } else if (!lcurl.startsWith("http:") && !lcurl.startsWith("https:")) {
                throw ServiceException.INVALID_REQUEST("url must begin with http: or https:", null);
            }

            // username and password are encoded in the URL as http://user:pass@host/...
            if (url.indexOf('@') != -1) {
                HttpURL httpurl = lcurl.startsWith("https:") ? new HttpsURL(url) : new HttpURL(url);
                if (httpurl.getUser() != null) {
                    String user = httpurl.getUser();
                    if (user.indexOf('%') != -1) {
                        try {
                            user = URLDecoder.decode(user, "UTF-8");
                        } catch (OutOfMemoryError e) {
                            Zimbra.halt("out of memory", e);
                        } catch (Throwable t) {
                        }
                    }
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user,
                            httpurl.getPassword());
                    client.getParams().setAuthenticationPreemptive(true);
                    client.getState().setCredentials(AuthScope.ANY, creds);
                }
            }

            try {
                get = new GetMethod(url);
            } catch (OutOfMemoryError e) {
                Zimbra.halt("out of memory", e);
                return null;
            } catch (Throwable t) {
                throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, t);
            }
            get.setParams(params);
            get.setFollowRedirects(true);
            get.setDoAuthentication(true);
            get.addRequestHeader("User-Agent", HTTP_USER_AGENT);
            get.addRequestHeader("Accept", HTTP_ACCEPT);
            if (fsd != null && fsd.getLastSyncDate() > 0) {
                String lastSyncAt = org.apache.commons.httpclient.util.DateUtil
                        .formatDate(new Date(fsd.getLastSyncDate()));
                get.addRequestHeader("If-Modified-Since", lastSyncAt);
            }
            HttpClientUtil.executeMethod(client, get);

            Header locationHeader = get.getResponseHeader("location");
            if (locationHeader != null) {
                // update our target URL and loop again to do another HTTP GET
                url = locationHeader.getValue();
                get.releaseConnection();
            } else {
                statusCode = get.getStatusCode();
                if (statusCode == HttpServletResponse.SC_OK) {
                    Header contentEncoding = get.getResponseHeader("Content-Encoding");
                    InputStream respInputStream = get.getResponseBodyAsStream();
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().indexOf("gzip") != -1) {
                            respInputStream = new GZIPInputStream(respInputStream);
                        }
                    }
                    content = new BufferedInputStream(respInputStream);
                    expectedCharset = get.getResponseCharSet();

                    Header lastModHdr = get.getResponseHeader("Last-Modified");
                    if (lastModHdr == null) {
                        lastModHdr = get.getResponseHeader("Date");
                    }
                    if (lastModHdr != null) {
                        try {
                            Date d = org.apache.commons.httpclient.util.DateUtil
                                    .parseDate(lastModHdr.getValue());
                            lastModified = d.getTime();
                        } catch (DateParseException e) {
                            ZimbraLog.misc.warn(
                                    "unable to parse Last-Modified/Date header: " + lastModHdr.getValue(), e);
                            lastModified = System.currentTimeMillis();
                        }
                    } else {
                        lastModified = System.currentTimeMillis();
                    }
                } else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
                    ZimbraLog.misc.debug("Remote data at " + url + " not modified since last sync");
                    return new RemoteDataInfo(statusCode, redirects, null, expectedCharset, lastModified);
                } else {
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusLine().toString(), null);
                }
                break;
            }
        } while (++redirects <= MAX_REDIRECTS);
    } catch (ServiceException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (HttpException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (IOException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    }
    RemoteDataInfo rdi = new RemoteDataInfo(statusCode, redirects, content, expectedCharset, lastModified);
    rdi.setGetMethod(get);
    return rdi;
}

From source file:com.zimbra.common.util.HttpUtil.java

/** Strips any userinfo (username/password) data from the passed-in URL
 *  and returns the result. *//*  w  w w. j  a va  2s  .  c  o  m*/
public static String sanitizeURL(String url) {
    if (url != null && url.indexOf('@') != -1) {
        try {
            HttpURL httpurl = (url.indexOf("https:") == 0) ? new HttpsURL(url) : new HttpURL(url);
            if (httpurl.getPassword() != null) {
                httpurl.setPassword("");
                return httpurl.toString();
            }
        } catch (org.apache.commons.httpclient.URIException urie) {
        }
    }
    return url;
}

From source file:net.sf.jftp.net.WebdavConnection.java

private HttpURL getURL(String u) {
    try {/*w w w  .  j  av  a  2s .co m*/
        HttpURL url = new HttpURL(u);

        //System.out.println(user + ":"+ pass);
        url.setUserinfo(user, pass);

        return url;
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.debug("ERROR: " + ex);

        return null;
    }
}

From source file:com.sos.VirtualFileSystem.WebDAV.SOSVfsWebDAV.java

/**
 *
 * \brief setRootHttpURL/*from   w  w w.  j  a  v a  2s . c o m*/
 *
 * \details
 *
 * \return void
 *
 * @param puser
 * @param ppassword
 * @param phost
 * @param pport
 * @return HttpURL
 * @throws Exception
 */
private HttpURL setRootHttpURL(final String puser, final String ppassword, final String phost, final int pport)
        throws Exception {

    rootUrl = null;
    HttpURL httpUrl = null;
    String path = "/";
    String normalizedHost = normalizeRootHttpURL(phost, pport);

    if (connection2OptionsAlternate.auth_method.isURL()) {
        if (phost.toLowerCase().startsWith("https://")) {
            httpUrl = new HttpsURL(normalizedHost);
        } else {
            httpUrl = new HttpURL(normalizedHost);
        }

        String phostRootUrl = httpUrl.getScheme() + "://" + httpUrl.getAuthority() + "/";
        if (httpUrl.getScheme().equalsIgnoreCase("https")) {
            rootUrl = new HttpsURL(phostRootUrl);

            if (pport > 0) {
                Protocol.registerProtocol("https", new Protocol("https",
                        (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(), pport));
            }
        } else {
            rootUrl = new HttpURL(phostRootUrl);
        }
    } else {
        httpUrl = new HttpURL(phost, pport, path);
        rootUrl = new HttpURL(phost, pport, path);
    }
    httpUrl.setUserinfo(puser, ppassword);
    return httpUrl;
}

From source file:com.sos.VirtualFileSystem.WebDAV.SOSVfsWebDAV.java

private HttpURL getWebdavRessourceURL(String path) throws Exception {
    HttpURL url = null;/*w w w  .  j av  a 2s. c  o m*/

    if (rootUrl != null) {
        path = path.startsWith("/") ? path.substring(1) : path;
        if (rootUrl.getScheme().equalsIgnoreCase("https")) {
            url = new HttpsURL(rootUrl.getEscapedURI() + path);
        } else {
            url = new HttpURL(rootUrl.getEscapedURI() + path);
        }
    }
    url.setUserinfo(userName, password);

    return url;
}

From source file:com.cladonia.xngreditor.URLUtilities.java

private static WebdavResource createWebdavResource(String uri, String username, String password)
        throws IOException {
    WebdavResource webdavResource = null;

    if (!uri.endsWith("/")) {
        int index = uri.lastIndexOf('/');

        if (index != -1) {
            uri = uri.substring(0, index + 1);
        }/* w w w  .  ja  va2  s .  c  o m*/
    }

    HttpURL httpURL = null;

    if (uri.startsWith("https")) {
        httpURL = new HttpsURL(uri.toCharArray());
    } else {
        httpURL = new HttpURL(uri.toCharArray());
    }

    try {
        // Set up for processing WebDAV resources
        webdavResource = new WebdavResource(httpURL);
    } catch (HttpException we) {
        // try with authorization ...
        we.printStackTrace();
        //         System.out.println( we.getReasonCode()+": "+we.getReason());
        if ((username == null) || (username.length() == 0)) {
            if (webdavResource != null) {
                webdavResource.close();
            }

            return null;
        }

        if (webdavResource != null) {
            webdavResource.close();
        }

        httpURL.setUserinfo(username, password);

        webdavResource = new WebdavResource(httpURL);
    }

    return webdavResource;
}

From source file:org.aksonov.mages.connection.ConnectionManager.java

/**
 * Gets the connection.//  w w w.j  a v a  2 s  . co m
 * 
 * @param host the host
 * 
 * @return the connection
 */
private static HttpConnection getConnection(String host) {
    try {
        synchronized (hosts) {
            if (!hosts.contains(host)) {
                HttpURL httpURL = new HttpURL(host);
                HostConfiguration hostConfig = new HostConfiguration();
                hostConfig.setHost(httpURL.getHost(), httpURL.getPort());
                hosts.put(host, hostConfig);
            }
        }
        HostConfiguration hostConfig = hosts.get(host);
        //Log.d("ConnectionManager", "Retrieving connection from the pool");
        HttpConnection connection = connectionManager.getConnectionWithTimeout(hostConfig, TIMEOUT);

        return connection;
    } catch (Exception e) {
        Log.e("ConnectionManager.getConnection", e);
        return null;
    }
}