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

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

Introduction

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

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:org.eclipse.php.composer.core.HttpHelper.java

private static HttpClient createHttpClient(String url, IProxyService proxyService)
        throws IOException, URISyntaxException {
    HttpClient httpClient = new HttpClient();

    if (proxyService.isProxiesEnabled()) {
        IProxyData[] proxyData = proxyService.select(new URI(url));

        if (proxyData.length != 0) {
            IProxyData proxy = proxyData[0];
            String proxyHostName = proxy.getHost();
            if (proxyHostName != null) {
                int portNumber = proxy.getPort();
                if (portNumber == -1) {
                    portNumber = 80;//w  w w . j  a va2  s  .c om
                }
                httpClient.getHostConfiguration().setProxy(proxyHostName, portNumber);
                if (proxy.isRequiresAuthentication()) {
                    String userName = proxy.getUserId();
                    if (userName != null) {
                        String password = proxy.getPassword();
                        Credentials credentials = new UsernamePasswordCredentials(userName, password);
                        httpClient.getState().setProxyCredentials(
                                new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                                credentials);
                    }
                }
            }
        }
    }

    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

    return httpClient;
}

From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * //  w  w w.  j a  v  a2 s  .c om
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:org.eclipse.swordfish.tooling.target.platform.test.TestRunProvider.java

private void checkIsServiceRun(String uri, String request) {
    PostMethod post = new PostMethod(uri);
    bot.viewByTitle("Console").show();
    bot.viewByTitle("Console").setFocus();
    Util.maximizeView(bot, "Console");
    String consoleContent = bot.styledText().getText();
    try {/*from w ww  .j av a 2 s  .  co  m*/
        RequestEntity entity = new StringRequestEntity(request, "text/xml", "UTF8");
        post.setRequestEntity(entity);
        post.setRequestHeader("SOAPAction", "");
        // Get HTTP client
        HttpClient httpclient = new HttpClient();
        LOG.info("PROXY:" + httpclient.getHostConfiguration().getProxyHost()
                + httpclient.getHostConfiguration().getProxyPort());
        int result = httpclient.executeMethod(post);
        if (result != 200) {
            fail("Response status code: " + result + post.getResponseBodyAsString() + consoleContent);
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "Could not send request to address: ", ex);
        fail("Could not send request to address " + uri + ex.getMessage() + consoleContent);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.eclipsetrader.directa.internal.core.connector.StreamingConnector.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (Activator.getDefault() != null) {
        BundleContext context = Activator.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxyService = (IProxyService) context.getService(reference);
            IProxyData[] proxyData = proxyService.select(new URI(null, host, null, null));
            for (int i = 0; i < proxyData.length; i++) {
                if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData[i].getType())) {
                    IProxyData data = proxyData[i];
                    if (data.getHost() != null) {
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    }/*from w w  w.  j a va  2 s  .c  o  m*/
                    if (data.isRequiresAuthentication()) {
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                    }
                    break;
                }
            }
            context.ungetService(reference);
        }
    }
}

From source file:org.eclipsetrader.directa.internal.core.WebConnector.java

private void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (Activator.getDefault() != null) {
        BundleContext context = Activator.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxyService = (IProxyService) context.getService(reference);
            IProxyData[] proxyData = proxyService.select(new URI(null, host, null, null));
            for (int i = 0; i < proxyData.length; i++) {
                if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData[i].getType())) {
                    IProxyData data = proxyData[i];
                    if (data.getHost() != null) {
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    }//from   w w  w  .  j  a  v a2 s  .co m
                    if (data.isRequiresAuthentication()) {
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                    }
                    break;
                }
            }
            context.ungetService(reference);
        }
    }
}

From source file:org.eclipsetrader.directaworld.internal.core.connector.SnapshotConnector.java

private void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (Activator.getDefault() != null) {
        BundleContext context = Activator.getDefault().getBundle().getBundleContext();
        ServiceReference<IProxyService> reference = context.getServiceReference(IProxyService.class);
        if (reference != null) {
            IProxyService proxyService = context.getService(reference);
            IProxyData[] proxyData = proxyService.select(new URI(null, host, null, null));
            for (int i = 0; i < proxyData.length; i++) {
                if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData[i].getType())) {
                    IProxyData data = proxyData[i];
                    if (data.getHost() != null) {
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    }//from ww  w .j  av  a2 s .c  o m
                    if (data.isRequiresAuthentication()) {
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                    }
                    break;
                }
            }
            context.ungetService(reference);
        }
    }
}

From source file:org.eclipsetrader.kdb.internal.core.Util.java

public static void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (KdbActivator.getDefault() == null) {
        return;/*  ww  w .ja  va2 s  .  c om*/
    }
    BundleContext context = KdbActivator.getDefault().getBundle().getBundleContext();
    ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
    if (reference != null) {
        IProxyService proxyService = (IProxyService) context.getService(reference);
        IProxyData[] proxyData = proxyService
                .select(new java.net.URI(IProxyData.HTTP_PROXY_TYPE, "//" + host, null));
        if (proxyData != null && proxyData.length != 0) {
            if (proxyData[0].getHost() != null) {
                client.getHostConfiguration().setProxy(proxyData[0].getHost(), proxyData[0].getPort());
            }
            if (proxyData[0].isRequiresAuthentication()) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(proxyData[0].getUserId(), proxyData[0].getPassword()));
            }
        }
        context.ungetService(reference);
    }
}

From source file:org.eclipsetrader.news.internal.connectors.RSSNewsProvider.java

private HeadLine[] update(URL feedUrl, String source) {
    Map<String, SyndEntry> titles = new HashMap<String, SyndEntry>();
    Map<SyndEntry, Set<ISecurity>> entries = new HashMap<SyndEntry, Set<ISecurity>>();
    Set<HeadLine> headLines = new HashSet<HeadLine>();

    try {//from   w w w .  j  a v  a  2 s.  c om
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        if (Activator.getDefault() != null) {
            BundleContext context = Activator.getDefault().getBundle().getBundleContext();
            ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
            if (reference != null) {
                IProxyService proxy = (IProxyService) context.getService(reference);
                IProxyData data = proxy.getProxyDataForHost(feedUrl.getHost(), IProxyData.HTTP_PROXY_TYPE);
                if (data != null) {
                    if (data.getHost() != null) {
                        client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                    }
                    if (data.isRequiresAuthentication()) {
                        client.getState().setProxyCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
                    }
                }
                context.ungetService(reference);
            }
        }

        SyndFeed feed = fetcher.retrieveFeed(feedUrl, client);
        for (Iterator<?> iter = feed.getEntries().iterator(); iter.hasNext();) {
            SyndEntry entry = (SyndEntry) iter.next();

            if (titles.containsKey(entry.getTitle())) {
                entry = titles.get(entry.getTitle());
            } else {
                titles.put(entry.getTitle(), entry);
            }

            Set<ISecurity> set = entries.get(entry);
            if (set == null) {
                set = new HashSet<ISecurity>();
                entries.put(entry, set);
            }
        }

        for (SyndEntry entry : entries.keySet()) {
            Set<ISecurity> set = entries.get(entry);

            String url = entry.getLink();
            if (url.indexOf('*') != -1) {
                url = url.substring(url.indexOf('*') + 1);
            }

            String title = entry.getTitle();
            if (title.endsWith(")")) {
                int s = title.lastIndexOf('(');
                if (s != -1) {
                    source = title.substring(s + 1, title.length() - 1);
                    if (source.startsWith("at ")) {
                        source = source.substring(3);
                    }
                    title = title.substring(0, s - 1).trim();
                }
            }

            HeadLine headLine = new HeadLine(entry.getPublishedDate(), source, title,
                    set.toArray(new ISecurity[set.size()]), url);
            headLines.add(headLine);
        }
    } catch (Exception e) {
        Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0,
                "Error reading RSS subscription " + feedUrl.toString(), e); //$NON-NLS-1$
        Activator.getDefault().getLog().log(status);
    }
    return headLines.toArray(new HeadLine[headLines.size()]);
}

From source file:org.eclipsetrader.yahoo.internal.core.Util.java

public static void setupProxy(HttpClient client, String host) throws URISyntaxException {
    if (YahooActivator.getDefault() == null) {
        return;//from  w w w  .ja  va  2  s  . com
    }
    BundleContext context = YahooActivator.getDefault().getBundle().getBundleContext();
    ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
    if (reference != null) {
        IProxyService proxyService = (IProxyService) context.getService(reference);
        IProxyData[] proxyData = proxyService
                .select(new java.net.URI(IProxyData.HTTP_PROXY_TYPE, "//" + host, null));
        if (proxyData != null && proxyData.length != 0) {
            if (proxyData[0].getHost() != null) {
                client.getHostConfiguration().setProxy(proxyData[0].getHost(), proxyData[0].getPort());
            }
            if (proxyData[0].isRequiresAuthentication()) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(proxyData[0].getUserId(), proxyData[0].getPassword()));
            }
        }
        context.ungetService(reference);
    }
}

From source file:org.eclipsetrader.yahoo.internal.news.NewsProvider.java

protected IStatus jobRunner(IProgressMonitor monitor) {
    IPreferenceStore store = YahooActivator.getDefault().getPreferenceStore();

    Date limitDate = getLimitDate();

    Calendar today = Calendar.getInstance();
    int hoursAsRecent = YahooActivator.getDefault().getPreferenceStore()
            .getInt(YahooActivator.PREFS_HOURS_AS_RECENT);
    today.add(Calendar.HOUR_OF_DAY, -hoursAsRecent);
    Date recentLimitDate = today.getTime();

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

    try {//from   w  w  w.j  a v  a2s.c  o  m
        JAXBContext jaxbContext = JAXBContext.newInstance(Category[].class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        InputStream inputStream = FileLocator.openStream(YahooActivator.getDefault().getBundle(),
                new Path("data/news_feeds.xml"), false);
        JAXBElement<Category[]> element = unmarshaller.unmarshal(new StreamSource(inputStream),
                Category[].class);

        int total = 0;
        for (Category category : element.getValue()) {
            for (Page page : category.getPages()) {
                if (store.getBoolean(YahooActivator.PREFS_SUBSCRIBE_PREFIX + page.getId())) {
                    total++;
                }
            }
        }

        ISecurity[] securities = getRepositoryService().getSecurities();
        total += securities.length;

        monitor.beginTask("Fetching Yahoo! News", total);

        resetRecentFlag();

        final Set<HeadLine> added = new HashSet<HeadLine>();
        final Set<HeadLine> updated = new HashSet<HeadLine>();

        Category[] category = element.getValue();
        for (int i = 0; i < category.length && !monitor.isCanceled(); i++) {
            INewsHandler handler = new RSSNewsHandler();
            if (category[i].getHandler() != null) {
                try {
                    handler = (INewsHandler) Class.forName(category[i].getHandler()).newInstance();
                } catch (Exception e) {
                    Status status = new Status(IStatus.ERROR, YahooActivator.PLUGIN_ID, 0,
                            "Invalid news handler class", e);
                    YahooActivator.log(status);
                }
            }

            List<URL> l = new ArrayList<URL>();

            Page[] page = category[i].getPages();
            for (int ii = 0; ii < page.length && !monitor.isCanceled(); ii++) {
                if (store.getBoolean(YahooActivator.PREFS_SUBSCRIBE_PREFIX + page[ii].getId())) {
                    l.add(new URL(page[ii].getUrl()));
                }
            }

            HeadLine[] list = handler.parseNewsPages(l.toArray(new URL[l.size()]), monitor);
            for (HeadLine headLine : list) {
                if (headLine.getDate() == null || headLine.getDate().before(limitDate)) {
                    continue;
                }
                if (!oldItems.contains(headLine)) {
                    if (!headLine.getDate().before(recentLimitDate)) {
                        headLine.setRecent(true);
                    }
                    oldItems.add(headLine);
                    added.add(headLine);
                }
            }
        }

        if (store.getBoolean(YahooActivator.PREFS_UPDATE_SECURITIES_NEWS)) {
            for (int i = 0; i < securities.length && !monitor.isCanceled(); i++) {
                URL feedUrl = Util.getRSSNewsFeedForSecurity(securities[i]);
                if (feedUrl == null) {
                    continue;
                }

                monitor.subTask(feedUrl.toString());

                try {
                    if (YahooActivator.getDefault() != null) {
                        BundleContext context = YahooActivator.getDefault().getBundle().getBundleContext();
                        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
                        if (reference != null) {
                            IProxyService proxy = (IProxyService) context.getService(reference);
                            IProxyData data = proxy.getProxyDataForHost(feedUrl.getHost(),
                                    IProxyData.HTTP_PROXY_TYPE);
                            if (data != null) {
                                if (data.getHost() != null) {
                                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                                }
                                if (data.isRequiresAuthentication()) {
                                    client.getState().setProxyCredentials(AuthScope.ANY,
                                            new UsernamePasswordCredentials(data.getUserId(),
                                                    data.getPassword()));
                                }
                            }
                            context.ungetService(reference);
                        }
                    }

                    SyndFeed feed = fetcher.retrieveFeed(feedUrl, client);
                    for (Iterator<?> iter = feed.getEntries().iterator(); iter.hasNext();) {
                        SyndEntry entry = (SyndEntry) iter.next();

                        String link = entry.getLink();
                        if (link == null && entry.getLinks().size() != 0) {
                            link = (String) entry.getLinks().get(0);
                        }
                        if (link != null) {
                            while (link.indexOf('*') != -1) {
                                link = link.substring(link.indexOf('*') + 1);
                            }
                            link = URLDecoder.decode(link, "UTF-8");
                        }
                        if (link == null) {
                            continue;
                        }

                        String source = null;

                        String title = entry.getTitle();
                        if (title.startsWith("[$$]")) {
                            title = title.substring(4, title.length());
                        }

                        if (title.endsWith(")")) {
                            int s = title.lastIndexOf('(');
                            if (s != -1) {
                                source = title.substring(s + 1, title.length() - 1);
                                if (source.startsWith("at ")) {
                                    source = source.substring(3);
                                }
                                title = title.substring(0, s - 1).trim();
                            }
                        }

                        HeadLine headLine = new HeadLine(entry.getPublishedDate(), source, title,
                                new ISecurity[] { securities[i] }, link);
                        int index = oldItems.indexOf(headLine);
                        if (index != -1) {
                            if (headLine.getDate().before(limitDate)) {
                                continue;
                            }
                            headLine = oldItems.get(index);
                            if (!headLine.contains(securities[i])) {
                                headLine.addMember(securities[i]);
                                updated.add(headLine);
                            }
                        } else {
                            if (!headLine.getDate().before(recentLimitDate)) {
                                headLine.setRecent(true);
                            }
                            oldItems.add(headLine);
                            added.add(headLine);
                        }
                    }
                } catch (Exception e) {
                    String msg = "Error fetching news from " + feedUrl.toString();
                    Status status = new Status(IStatus.ERROR, YahooActivator.PLUGIN_ID, 0, msg, e);
                    YahooActivator.log(status);
                }

                monitor.worked(1);
            }
        }

        if (added.size() != 0 || updated.size() != 0) {
            final INewsService service = getNewsService();
            service.runInService(new INewsServiceRunnable() {

                @Override
                public IStatus run(IProgressMonitor monitor) throws Exception {
                    service.addHeadLines(added.toArray(new IHeadLine[added.size()]));
                    service.updateHeadLines(updated.toArray(new IHeadLine[updated.size()]));
                    return Status.OK_STATUS;
                }
            }, null);
        }

        save();
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, YahooActivator.PLUGIN_ID, 0, "Error fetching news", e);
        YahooActivator.log(status);
    } finally {
        monitor.done();
    }

    return Status.OK_STATUS;
}