List of usage examples for org.apache.commons.httpclient HttpClient getState
public HttpState getState()
From source file:net.sourceforge.eclipsetrader.yahoo.FrenchNewsProvider.java
private void update(URL feedUrl, Security security) { System.out.println("Fetching " + feedUrl.toExternalForm()); //$NON-NLS-1$ boolean subscribersOnly = YahooPlugin.getDefault().getPreferenceStore() .getBoolean(YahooPlugin.PREFS_SHOW_SUBSCRIBERS_ONLY); try {//from ww w . j a va 2s. c o m HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); BundleContext context = YahooPlugin.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())); } } SyndFeed feed = fetcher.retrieveFeed(feedUrl, client); for (Iterator iter = feed.getEntries().iterator(); iter.hasNext();) { SyndEntry entry = (SyndEntry) iter.next(); if (!subscribersOnly && entry.getTitle().indexOf("[$$]") != -1) //$NON-NLS-1$ continue; NewsItem news = new NewsItem(); news.setRecent(true); Date entryDate = entry.getPublishedDate(); if (entry.getUpdatedDate() != null) entryDate = entry.getUpdatedDate(); if (entryDate != null) { Calendar date = Calendar.getInstance(); date.setTime(entryDate); date.set(Calendar.SECOND, 0); news.setDate(date.getTime()); } String title = entry.getTitle(); if (title.endsWith(")")) //$NON-NLS-1$ { int s = title.lastIndexOf('('); if (s != -1) { news.setSource(title.substring(s + 1, title.length() - 1)); title = title.substring(0, s - 1).trim(); } } news.setTitle(title); news.setUrl(entry.getLink()); if (security != null) news.addSecurity(security); // System.out.println("** News found:"); // System.out.println(news.getTitle()); // System.out.println(news.getSource()); // System.out.println(news.getUrl()); // System.out.println("--"); CorePlugin.getRepository().save(news); } } catch (Exception e) { CorePlugin.logException(e); } }
From source file:at.ait.dme.yuma.server.annotation.ImageAnnotationManager.java
private EuropeanaAnnotationService getAnnotationService(MultivaluedMap<String, String> headers) { List<String> cookieHeaders = (headers != null) ? headers.get("Set-Cookie") : new ArrayList<String>(); HttpClient client = new HttpClient(); // make sure to forward all cookies javax.servlet.http.Cookie[] cookies = clientRequest.getCookies(); for (javax.servlet.http.Cookie c : cookies) { c.setDomain(clientRequest.getServerName()); c.setPath("/"); String value = c.getValue(); for (String cookieHeader : cookieHeaders) { if (cookieHeader.startsWith(c.getName())) { String cookieHeaderParts[] = cookieHeader.split("="); if (cookieHeaderParts.length >= 2) value = cookieHeaderParts[1]; }//ww w . j a v a2s .c o m } Cookie apacheCookie = new Cookie(c.getDomain(), c.getName(), value, c.getPath(), c.getMaxAge(), c.getSecure()); client.getState().addCookie(apacheCookie); } client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); return ProxyFactory.create(EuropeanaAnnotationService.class, annotationServiceBaseUrl, new ApacheHttpClientExecutor(client)); }
From source file:mitm.application.djigzo.net.ProxyInjectorImpl.java
@Override public void setProxy(HttpClient httpClient) throws ProxyException { try {/*from w w w.j a v a 2 s .c o m*/ if (httpClient == null) { return; } ProxySettings proxySettings = new PropertiesProxySettings( globalPreferencesManager.getGlobalUserPreferences().getProperties()); if (proxySettings.isEnabled()) { if (logger.isDebugEnabled()) { logger.debug("Setting proxy. Host: " + proxySettings.getHost() + ", Port: " + proxySettings.getPort() + ", Username: " + proxySettings.getUsername()); } httpClient.getHostConfiguration().setProxy(proxySettings.getHost(), proxySettings.getPort()); Credentials credentials = new NTCredentials(StringUtils.defaultString(proxySettings.getUsername()), proxySettings.getPassword(), StringUtils.defaultString(proxySettings.getDomain()), StringUtils.defaultString(proxySettings.getHost())); httpClient.getState().setProxyCredentials(AuthScope.ANY, credentials); } else { httpClient.getHostConfiguration().setProxyHost(null); } } catch (HierarchicalPropertiesException e) { throw new ProxyException(e); } }
From source file:com.googlecode.fascinator.indexer.SolrIndexer.java
/** * Initialize a Solr core object./*from ww w . j a v a2 s. c o m*/ * * @param coreName : The core to initialize * @return SolrServer : The initialized core */ private SolrServer initCore(String coreName) { try { String uri = config.getString(null, "indexer", coreName, "uri"); if (uri == null) { log.error("No URI provided for core: '{}'", coreName); return null; } URI solrUri = new URI(uri); CommonsHttpSolrServer thisCore = new CommonsHttpSolrServer(solrUri.toURL()); String username = config.getString(null, "indexer", coreName, "username"); String password = config.getString(null, "indexer", coreName, "password"); usernameMap.put(coreName, username); passwordMap.put(coreName, password); if (username != null && password != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); HttpClient hc = (thisCore).getHttpClient(); hc.getParams().setAuthenticationPreemptive(true); hc.getState().setCredentials(AuthScope.ANY, credentials); } return thisCore; } catch (MalformedURLException mue) { log.error(coreName + " : Malformed URL", mue); } catch (URISyntaxException urise) { log.error(coreName + " : Invalid URI", urise); } return null; }
From source file:net.sourceforge.eclipsetrader.yahoo.NewsProvider.java
private void update(URL feedUrl, Security security) { Calendar limit = Calendar.getInstance(); limit.add(Calendar.DATE,//from w w w . j a va2s .c om -CorePlugin.getDefault().getPreferenceStore().getInt(CorePlugin.PREFS_NEWS_DATE_RANGE)); boolean subscribersOnly = YahooPlugin.getDefault().getPreferenceStore() .getBoolean(YahooPlugin.PREFS_SHOW_SUBSCRIBERS_ONLY); log.debug(feedUrl); try { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); BundleContext context = YahooPlugin.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())); } } SyndFeed feed = fetcher.retrieveFeed(feedUrl, client); for (Iterator iter = feed.getEntries().iterator(); iter.hasNext();) { SyndEntry entry = (SyndEntry) iter.next(); if (!subscribersOnly && entry.getTitle().indexOf("[$$]") != -1) //$NON-NLS-1$ continue; NewsItem news = new NewsItem(); news.setRecent(true); String title = entry.getTitle(); if (title.endsWith(")")) //$NON-NLS-1$ { int s = title.lastIndexOf('('); if (s != -1) { news.setSource(title.substring(s + 1, title.length() - 1)); title = title.substring(0, s - 1).trim(); } } news.setTitle(title); news.setUrl(entry.getLink()); Date entryDate = entry.getPublishedDate(); if (entry.getUpdatedDate() != null) entryDate = entry.getUpdatedDate(); if (entryDate != null) { Calendar date = Calendar.getInstance(); date.setTime(entryDate); date.set(Calendar.SECOND, 0); date.set(Calendar.MILLISECOND, 0); news.setDate(date.getTime()); } if (security != null) news.addSecurity(security); if (!news.getDate().before(limit.getTime()) && !isDuplicated(news)) { log.trace(news.getTitle() + " (" + news.getSource() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ CorePlugin.getRepository().save(news); oldItems.add(news); } } } catch (Exception e) { log.error(e, e); } }
From source file:com.google.enterprise.connector.sharepoint.wsclient.soap.SPClientFactory.java
private HttpClient createHttpClient(Credentials credentials) { HttpClient httpClientToUse = new HttpClient(); HttpClientParams params = httpClientToUse.getParams(); // Fix for the Issue[5408782] SharePoint connector fails to traverse a site, // circular redirect exception is observed. params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); // If ALLOW_CIRCULAR_REDIRECTS is set to true, HttpClient throws an // exception if a series of redirects includes the same resources more than // once. MAX_REDIRECTS allows you to specify a maximum number of redirects // to follow. params.setIntParameter(HttpClientParams.MAX_REDIRECTS, 10); params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, HTTP_CLIENT_TIMEOUT_SECONDS * 1000); params.setIntParameter(HttpClientParams.SO_TIMEOUT, HTTP_CLIENT_TIMEOUT_SECONDS * 1000); httpClientToUse.getState().setCredentials(AuthScope.ANY, credentials); return httpClientToUse; }
From source file:com.inbravo.scribe.rest.service.crm.zd.ZDV2RESTCRMService.java
@Override public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject) throws Exception { logger.debug("----Inside getObjects"); /* Check if all record types are to be searched */ if (cADCommandObject.getObjectType().trim().equalsIgnoreCase(HTTPConstants.anyObject)) { return this.searchAllTypeOfObjects(cADCommandObject, null, null, null); } else {/* ww w.j ava2 s. co m*/ GetMethod getMethod = null; try { String serviceURL = null; String serviceProtocol = null; String userId = null; String password = null; String crmPort = "80"; /* Get agent from session manager */ final ScribeCacheObject cacheObject = zDCRMSessionManager .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId()); /* Get CRM information from agent */ serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL(); serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol(); userId = cacheObject.getScribeMetaObject().getCrmUserId(); password = cacheObject.getScribeMetaObject().getCrmPassword(); crmPort = cacheObject.getScribeMetaObject().getCrmPort(); /* Create Zen desk URL */ final String zenDeskURL = serviceProtocol + "://" + serviceURL + zdAPISubPath + cADCommandObject.getObjectType().toLowerCase() + "s.json"; if (logger.isDebugEnabled()) { logger.debug("----Inside getObjects zenDeskURL: " + zenDeskURL); } /* Instantiate get method */ getMethod = new GetMethod(zenDeskURL); /* Set request content type */ getMethod.addRequestHeader("Content-Type", "application/json"); getMethod.addRequestHeader("accept", "application/json"); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)), new UsernamePasswordCredentials(userId, password)); /* Execute method */ int result = httpclient.executeMethod(getMethod); if (logger.isDebugEnabled()) { logger.debug("----Inside getObjects response code: " + result + " & body: " + getMethod.getResponseBodyAsString()); } if (result == HttpStatus.SC_OK) { /* Create Scribe object from JSON response */ return this.createSearchResponse(getMethod.getResponseBodyAsString(), cADCommandObject.getObjectType().toLowerCase()); } else if (result == HttpStatus.SC_FORBIDDEN) { throw new ScribeException(ScribeResponseCodes._1020 + "Query is forbidden by Zendesk CRM"); } else if (result == HttpStatus.SC_BAD_REQUEST) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content"); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException( ScribeResponseCodes._1004 + "Requested record not found at Zendesk CRM"); } } catch (final ScribeException exception) { throw exception; } catch (final JSONException e) { /* Throw user error */ throw new ScribeException( ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM", e); } catch (final ParserConfigurationException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM", exception); } catch (final SAXException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM", exception); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (getMethod != null) { getMethod.releaseConnection(); } } return cADCommandObject; } }
From source file:net.sourceforge.eclipsetrader.yahoo.Feed.java
private void update() { // Builds the url for quotes download String host = "quote.yahoo.com"; //$NON-NLS-1$ StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols="); //$NON-NLS-1$ //$NON-NLS-2$ for (Iterator iter = map.values().iterator(); iter.hasNext();) url = url.append((String) iter.next() + "+"); //$NON-NLS-1$ if (url.charAt(url.length() - 1) == '+') url.deleteCharAt(url.length() - 1); url.append("&format=sl1d1t1c1ohgvbap"); //$NON-NLS-1$ log.debug(url.toString());/*from ww w . j ava 2 s. c o m*/ // Read the last prices String line = ""; //$NON-NLS-1$ try { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); BundleContext context = YahooPlugin.getDefault().getBundle().getBundleContext(); ServiceReference reference = context.getServiceReference(IProxyService.class.getName()); if (reference != null) { IProxyService proxy = (IProxyService) context.getService(reference); IProxyData data = proxy.getProxyDataForHost(host, 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())); } } HttpMethod method = new GetMethod(url.toString()); method.setFollowRedirects(true); client.executeMethod(method); BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); while ((line = in.readLine()) != null) { String[] item = line.split(","); //$NON-NLS-1$ if (line.indexOf(";") != -1) //$NON-NLS-1$ item = line.split(";"); //$NON-NLS-1$ Double open = null, high = null, low = null, close = null; Quote quote = new Quote(); // 2 = Date // 3 = Time try { GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US); //$NON-NLS-1$ usDateTimeParser.setTimeZone(c.getTimeZone()); usDateParser.setTimeZone(c.getTimeZone()); usTimeParser.setTimeZone(c.getTimeZone()); String date = stripQuotes(item[2]); if (date.indexOf("N/A") != -1) //$NON-NLS-1$ date = usDateParser.format(Calendar.getInstance().getTime()); String time = stripQuotes(item[3]); if (time.indexOf("N/A") != -1) //$NON-NLS-1$ time = usTimeParser.format(Calendar.getInstance().getTime()); c.setTime(usDateTimeParser.parse(date + " " + time)); //$NON-NLS-1$ c.setTimeZone(TimeZone.getDefault()); quote.setDate(c.getTime()); } catch (Exception e) { log.error(e.getMessage() + ": " + line); //$NON-NLS-1$ } // 1 = Last price or N/A if (item[1].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ quote.setLast(numberFormat.parse(item[1]).doubleValue()); // 4 = Change // 5 = Open if (item[5].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ open = new Double(numberFormat.parse(item[5]).doubleValue()); // 6 = Maximum if (item[6].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ high = new Double(numberFormat.parse(item[6]).doubleValue()); // 7 = Minimum if (item[7].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ low = new Double(numberFormat.parse(item[7]).doubleValue()); // 8 = Volume if (item[8].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ quote.setVolume(numberFormat.parse(item[8]).intValue()); // 9 = Bid Price if (item[9].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ quote.setBid(numberFormat.parse(item[9]).doubleValue()); // 10 = Ask Price if (item[10].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ quote.setAsk(numberFormat.parse(item[10]).doubleValue()); // 11 = Close Price if (item[11].equalsIgnoreCase("N/A") == false) //$NON-NLS-1$ close = new Double(numberFormat.parse(item[11]).doubleValue()); // 0 = Code String symbol = stripQuotes(item[0]); for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { Security security = (Security) iter.next(); if (symbol.equalsIgnoreCase((String) map.get(security))) { security.setQuote(quote, open, high, low, close); } } } in.close(); } catch (Exception e) { log.error(e); } }
From source file:com.inbravo.scribe.rest.service.crm.zd.ZDV2RESTCRMService.java
@Override public final ScribeCommandObject createObject(final ScribeCommandObject cADCommandObject) throws Exception { logger.debug("----Inside createObject"); PostMethod postMethod = null;/*from w w w. j a va 2s .co m*/ try { String serviceURL = null; String serviceProtocol = null; String userId = null; String password = null; String sessionId = null; String crmPort = "80"; /* Get agent from session manager */ final ScribeCacheObject cacheObject = zDCRMSessionManager .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId()); /* Get CRM information from agent */ serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL(); serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol(); userId = cacheObject.getScribeMetaObject().getCrmUserId(); password = cacheObject.getScribeMetaObject().getCrmPassword(); crmPort = cacheObject.getScribeMetaObject().getCrmPort(); /* Create Zen desk URL */ final String zenDeskURL = serviceProtocol + "://" + serviceURL + zdAPISubPath + cADCommandObject.getObjectType().toLowerCase() + "s.json"; if (logger.isDebugEnabled()) { logger.debug("----Inside createObject zenDeskURL: " + zenDeskURL); } /* Instantiate get method */ postMethod = new PostMethod(zenDeskURL); /* Set request content type */ postMethod.addRequestHeader("Content-Type", "application/json"); postMethod.addRequestHeader("accept", "application/json"); /* Cookie is required to be set for session management */ postMethod.addRequestHeader("Cookie", sessionId); /* Add request entity */ final RequestEntity entity = new StringRequestEntity( ZDCRMMessageFormatUtils.getCreateRequestJSON(cADCommandObject), null, null); postMethod.setRequestEntity(entity); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)), new UsernamePasswordCredentials(userId, password)); /* Execute method */ int result = httpclient.executeMethod(postMethod); if (logger.isDebugEnabled()) { logger.debug("----Inside createObject response code: " + result + " & body: " + postMethod.getResponseBodyAsString()); } /* Check if object is created */ if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) { /* Create Scribe object from JSON response */ return this.createCreateResponse(postMethod.getResponseBodyAsString(), cADCommandObject.getObjectType().toLowerCase()); } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED || result == HttpStatus.SC_NOT_ACCEPTABLE || result == HttpStatus.SC_UNPROCESSABLE_ENTITY) { /* Throw user error with valid reasons */ throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : " + ZDCRMMessageFormatUtils.getErrorFromResponse(postMethod.getResponseBodyAsString())); } else if (result == HttpStatus.SC_UNAUTHORIZED) { /* Throw user error with valid reasons */ throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { /* Throw user error with valid reasons */ throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM"); } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) { /* Throw user error with valid reasons */ throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct"); } } catch (final ScribeException exception) { throw exception; } catch (final JSONException e) { /* Throw user error */ throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM", e); } catch (final ParserConfigurationException exception) { /* Throw user error */ throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM", exception); } catch (final SAXException exception) { /* Throw user error */ throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM", exception); } catch (final IOException exception) { /* Throw user error */ throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (postMethod != null) { postMethod.releaseConnection(); } } return cADCommandObject; }
From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java
/** * @return the cookies return from this request on the login page. * @throws MojoExecutionException/*from www .jav a 2 s . c o m*/ * if any error occurs during this process. */ private Cookie[] getCookies() throws MojoExecutionException { Cookie[] cookie = null; GetMethod loginGet = new GetMethod(crxPath + "/login.jsp"); loginGet.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try { getLog().info("login to " + loginGet.getURI()); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT); int status = client.executeMethod(loginGet); // log the status getLog().info( "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n"); if (status == HttpStatus.SC_OK) { getLog().info("Login page accessed"); cookie = client.getState().getCookies(); } else { logResponseDetails(loginGet); throw new MojoExecutionException("Login failed, response=" + HttpStatus.getStatusText(status)); } } catch (Exception ex) { getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage()); throw new MojoExecutionException(ex.getMessage()); } finally { loginGet.releaseConnection(); } return cookie; }