List of usage examples for org.apache.commons.httpclient HttpClient getState
public HttpState getState()
From source file:edu.unc.lib.dl.cdr.sword.server.managers.MediaResourceManagerImpl.java
@Override public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> accept, AuthCredentials auth, SwordConfiguration config) throws SwordError, SwordServerException, SwordAuthException { log.debug("Retrieving media resource representation for " + uri); DatastreamPID targetPID = (DatastreamPID) extractPID(uri, SwordConfigurationImpl.EDIT_MEDIA_PATH + "/"); Datastream datastream = Datastream.getDatastream(targetPID.getDatastream()); if (datastream == null) datastream = virtualDatastreamMap.get(targetPID.getDatastream()); if (datastream == null) throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404, "Media representations other than those of datastreams are not currently supported"); HttpClient client = new HttpClient(); UsernamePasswordCredentials cred = new UsernamePasswordCredentials(accessClient.getUsername(), accessClient.getPassword()); client.getState().setCredentials(new AuthScope(null, 443), cred); client.getState().setCredentials(new AuthScope(null, 80), cred); GetMethod method = new GetMethod(fedoraPath + "/objects/" + targetPID.getPid() + "/datastreams/" + datastream.getName() + "/content"); InputStream inputStream = null; String mimeType = null;/* ww w . jav a 2s. c o m*/ String lastModified = null; try { method.setDoAuthentication(true); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { StringBuffer query = new StringBuffer(); query.append("select $mimeType $lastModified from <%1$s>") .append(" where <%2$s> <%3$s> $mimeType and <%2$s> <%4$s> $lastModified").append(";"); String formatted = String.format(query.toString(), tripleStoreQueryService.getResourceIndexModelUri(), targetPID.getURI() + "/" + datastream.getName(), ContentModelHelper.FedoraProperty.mimeType.getURI().toString(), ContentModelHelper.FedoraProperty.lastModifiedDate.getURI().toString()); List<List<String>> datastreamResults = tripleStoreQueryService.queryResourceIndex(formatted); if (datastreamResults.size() > 0) { mimeType = datastreamResults.get(0).get(0); lastModified = datastreamResults.get(0).get(1); } inputStream = new MethodAwareInputStream(method); } else if (method.getStatusCode() >= 500) { throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, method.getStatusCode(), "Failed to retrieve " + targetPID.getPid() + ": " + method.getStatusLine().toString()); } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404, "Object " + targetPID.getPid() + " could not be found."); } } catch (HttpException e) { throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, "An exception occurred while attempting to retrieve " + targetPID.getPid()); } catch (IOException e) { throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, "An exception occurred while attempting to retrieve " + targetPID.getPid()); } // For the ACL virtual datastream, transform RELS-EXT into accessControl tag if ("ACL".equals(targetPID.getDatastream())) { try { log.debug("Converting response XML to ACL format"); SAXBuilder saxBuilder = new SAXBuilder(); Document relsExt = saxBuilder.build(inputStream); XMLOutputter outputter = new XMLOutputter(); Element accessElement = AccessControlTransformationUtil.rdfToACL(relsExt.getRootElement()); inputStream.close(); inputStream = new ByteArrayInputStream(outputter.outputString(accessElement).getBytes()); } catch (Exception e) { log.debug("Failed to parse response from " + targetPID.getDatastreamURI() + " into ACL format", e); throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, "An exception occurred while attempting to retrieve " + targetPID.getPid()); } } MediaResource resource = new MediaResource(inputStream, mimeType, null, true); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date lastModifiedDate; try { lastModifiedDate = formatter.parse(lastModified); resource.setLastModified(lastModifiedDate); } catch (ParseException e) { log.error("Unable to set last modified date for " + uri, e); } return resource; }
From source file:fedora.localservices.saxon.SaxonServlet.java
/** * Get the content at the given location using the configured credentials * (if any)./* www.j a v a2s .c om*/ */ private InputStream getInputStream(String url) throws Exception { GetMethod getMethod = new GetMethod(url); HttpClient client = new HttpClient(m_cManager); UsernamePasswordCredentials creds = getCreds(url); if (creds != null) { client.getState().setCredentials(AuthScope.ANY, creds); client.getParams().setAuthenticationPreemptive(true); getMethod.setDoAuthentication(true); } getMethod.setFollowRedirects(true); HttpInputStream in = new HttpInputStream(client, getMethod, url); if (in.getStatusCode() != 200) { try { in.close(); } catch (Exception e) { } throw new IOException("HTTP request failed. Got status code " + in.getStatusCode() + " from remote server while attempting to GET " + url); } else { return in; } }
From source file:com.htmlhifive.tools.jslint.engine.download.AbstractDownloadEngineSupport.java
/** * ?url????eclipse?????HttpClient??.<br> * ??//ww w . ja va2 s . co m * {@link AbstractDownloadEngineSupport#getConnectionTimeout()}.<br> * ? {@link AbstractDownloadEngineSupport#getRetryTimes()} * * @param url URL * @return HttpClient */ private HttpClient createHttpClient(String url) { ServiceTracker<IProxyService, IProxyService> proxyTracker = new ServiceTracker<IProxyService, IProxyService>( JSLintPlugin.getDefault().getBundle().getBundleContext(), IProxyService.class, null); boolean useProxy = false; String proxyHost = null; int proxyPort = 0; String userId = null; String password = null; try { proxyTracker.open(); IProxyService service = proxyTracker.getService(); IProxyData[] datas = service.select(new URI(url)); for (IProxyData proxyData : datas) { if (proxyData.getHost() != null) { useProxy = true; proxyHost = proxyData.getHost(); proxyPort = proxyData.getPort(); userId = proxyData.getUserId(); password = proxyData.getPassword(); } } } catch (URISyntaxException e) { throw new RuntimeException(Messages.EM0100.getText(), e); } finally { proxyTracker.close(); } HttpClient client = new HttpClient(); if (useProxy) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotEmpty(userId)) { // ????? client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort, "realm"), new UsernamePasswordCredentials(userId, password)); } } client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(getRetryTimes(), true)); client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getConnectionTimeout()); return client; }
From source file:edu.mayo.cts2.framework.core.client.Cts2RestClient.java
/** * Creates the secure transport./* ww w. j av a 2 s . co m*/ * * @param username the username * @param password the password * @return the client http request factory */ protected ClientHttpRequestFactory createSecureTransport(String username, String password) { HttpClient client = new HttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(AuthScope.ANY, credentials); CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client); return commons; }
From source file:com.liferay.portal.search.solr.server.BasicAuthSolrServer.java
public BasicAuthSolrServer(AuthScope authScope, String username, String password, String url) throws MalformedURLException { _username = username;/*w w w .j a v a 2 s. c o m*/ _password = password; _multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpClient httpClient = new HttpClient(_multiThreadedHttpConnectionManager); if ((_username != null) && (_password != null)) { if (authScope == null) { authScope = AuthScope.ANY; } HttpState httpState = httpClient.getState(); httpState.setCredentials(authScope, new UsernamePasswordCredentials(_username, _password)); HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setAuthenticationPreemptive(true); } _server = new CommonsHttpSolrServer(url, httpClient); }
From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java
private int getRequestStatus(String path) { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); GetMethod httpget = new GetMethod(this.baseURL + path); client.getParams().setAuthenticationPreemptive(true); try {/*w ww .ja va2 s . co m*/ client.executeMethod(httpget); return httpget.getStatusCode(); } catch (HttpException e) { LOGGER.log(Level.SEVERE, "Communication error", e); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Communication error", e); } finally { httpget.releaseConnection(); } return -1; }
From source file:com.acc.test.ProductWebServiceTest.java
@Before public void before() { LOG.setLevel(Level.DEBUG);/*from w w w.j av a 2s. c o m*/ final HttpClient client = new HttpClient(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USER, PASSWD); client.getState().setCredentials(new AuthScope(AuthScope.ANY), credentials); final CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client); final HttpMessageConverter<?> jsonConverter = new org.springframework.http.converter.xml.MarshallingHttpMessageConverter( new org.springframework.oxm.xstream.XStreamMarshaller()); ((org.springframework.http.converter.xml.MarshallingHttpMessageConverter) jsonConverter) .setSupportedMediaTypes(Arrays.asList(org.springframework.http.MediaType.APPLICATION_JSON)); final HttpMessageConverter<?> xmlConverter = new org.springframework.http.converter.xml.MarshallingHttpMessageConverter( new org.springframework.oxm.xstream.XStreamMarshaller()); ((org.springframework.http.converter.xml.MarshallingHttpMessageConverter) jsonConverter) .setSupportedMediaTypes(Arrays.asList(org.springframework.http.MediaType.APPLICATION_XML)); converters = new ArrayList<HttpMessageConverter<?>>(); converters.add(jsonConverter); converters.add(xmlConverter); template = new RestTemplate(commons); template.setMessageConverters(converters); }
From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java
private String getRequest(String path) { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); GetMethod httpget = new GetMethod(this.baseURL + path); client.getParams().setAuthenticationPreemptive(true); String response = null;// ww w .j a v a2 s . c o m InputStream responseBodyAsStream = null; try { client.executeMethod(httpget); responseBodyAsStream = httpget.getResponseBodyAsStream(); response = IOUtils.toString(responseBodyAsStream, "UTF-8"); if (httpget.getStatusCode() != HttpStatus.SC_OK) { throw new GogsRequestException(httpget.getStatusCode(), "HTTP request error. Status: " + httpget.getStatusCode() + ": " + httpget.getStatusText() + ".\n" + response); } } catch (HttpException e) { throw new GogsRequestException(0, "Communication error: " + e, e); } catch (IOException e) { throw new GogsRequestException(0, "Communication error: " + e, e); } finally { httpget.releaseConnection(); if (responseBodyAsStream != null) { IOUtils.closeQuietly(responseBodyAsStream); } } if (response == null) { throw new GogsRequestException(0, "HTTP request error " + httpget.getStatusCode() + ":" + httpget.getStatusText()); } return response; }
From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java
private String postRequest(PostMethod httppost) throws UnsupportedEncodingException { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); client.getParams().setAuthenticationPreemptive(true); String response = null;//from ww w . ja v a 2s. c o m InputStream responseBodyAsStream = null; try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_NO_CONTENT) { // 204, no content return ""; } responseBodyAsStream = httppost.getResponseBodyAsStream(); if (responseBodyAsStream != null) { response = IOUtils.toString(responseBodyAsStream, "UTF-8"); } if (httppost.getStatusCode() != HttpStatus.SC_OK && httppost.getStatusCode() != HttpStatus.SC_CREATED) { throw new GogsRequestException(httppost.getStatusCode(), "HTTP request error. Status: " + httppost.getStatusCode() + ": " + httppost.getStatusText() + ".\n" + response); } } catch (HttpException e) { throw new GogsRequestException(0, "Communication error: " + e, e); } catch (IOException e) { throw new GogsRequestException(0, "Communication error: " + e, e); } finally { httppost.releaseConnection(); if (responseBodyAsStream != null) { IOUtils.closeQuietly(responseBodyAsStream); } } if (response == null) { throw new GogsRequestException(0, "HTTP request error"); } return response; }
From source file:icom.jpa.bdk.BdkUserContextImpl.java
BdkUserContextImpl(PersistenceContextImpl context, String host, int port, String protocol, String username, char[] password) throws Exception { HttpClient httpClient = new HttpClient(connectionManager); Credentials defaultCredentials = new UsernamePasswordCredentials(username, new String(password)); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getHostConfiguration().setHost(host, port, protocol); AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM); httpClient.getState().setCredentials(authScope, defaultCredentials); this.httpClient = httpClient; this.authUserName = username; OrganizationUser myUser = getMyUser(context); actorId = myUser.getCollabId().getId(); String enterpriseId = actorId.substring(0, 4); String siteId = actorId.substring(5, 9); BdkDataAccessUtilsImpl bdkDataAccessUtils = (BdkDataAccessUtilsImpl) context.getDataAccessUtils(); bdkDataAccessUtils.setEnterpriseId(enterpriseId); bdkDataAccessUtils.setSiteId(siteId); antiCSRF = getAntiCrossSiteRequestForgery(); }