Java Code Examples for org.apache.commons.httpclient.HttpClient

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project integration-tests, under directory /picketlink-trust-tests/src/test/java/org/picketlink/test/trust/tests/.

Source file: ServletToWSTestCase.java

  33 
vote

@Test public void testServlet2WS() throws Exception {
  HttpClient client=new HttpClient();
  PostMethod post=new PostMethod("http://localhost:8080/binary-test/TestWSInvokingServlet");
  post.addRequestHeader("TEST_HEADER","somevalue");
  int result=client.executeMethod(post);
  assertEquals(200,result);
}
 

Example 2

From project bioclipse.opentox, under directory /plugins/net.bioclipse.opentox/src/net/bioclipse/opentox/api/.

Source file: Dataset.java

  32 
vote

public static void deleteDataset(String datasetURI) throws Exception {
  HttpClient client=new HttpClient();
  DeleteMethod method=new DeleteMethod(datasetURI);
  HttpMethodHelper.addMethodHeaders(method,null);
  client.executeMethod(method);
  int status=method.getStatusCode();
  method.releaseConnection();
  if (status == 404)   throw new IllegalArgumentException("Dataset does not exist.");
  if (status == 503)   throw new IllegalStateException("Service error: " + status);
}
 

Example 3

From project candlepin, under directory /src/main/java/org/candlepin/client/.

Source file: CandlepinConnection.java

  32 
vote

/** 
 * Connects to another Candlepin instance located at the given uri.
 * @param clazz the client class to create.
 * @param creds authentication credentials for the given uri.
 * @param uri the Candlepin instance to connect to
 * @return Client proxy used to interact with Candlepin via REST API.
 */
public <T>T connect(Class<T> clazz,Credentials creds,String uri){
  HttpClient httpclient=new HttpClient();
  httpclient.getState().setCredentials(AuthScope.ANY,creds);
  ClientExecutor clientExecutor=new ApacheHttpClientExecutor(httpclient);
  return ProxyFactory.create(clazz,uri,clientExecutor);
}
 

Example 4

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/api/.

Source file: BeesClientBase.java

  32 
vote

public String executeRequest(String url) throws Exception {
  HttpClient httpClient=HttpClientHelper.createClient(this.beesClientConfiguration);
  GetMethod getMethod=new GetMethod(url);
  int code=httpClient.executeMethod(getMethod);
  String response=getResponseString(getMethod.getResponseBodyAsStream());
  if (code >= 300) {
    processError(response,code);
  }
  return response;
}
 

Example 5

From project conversation, under directory /spi/src/test/java/org/jboss/seam/conversation/test/.

Source file: SmokeBase.java

  32 
vote

@Test public void testFactory() throws Exception {
  Thread.sleep(1000L);
  SimpleHttpConnectionManager connManager=new SimpleHttpConnectionManager(true);
  HttpClient client=new HttpClient(connManager);
  HttpMethod method=new GetMethod(Deployments.CONTEXT_PATH + "dummy/");
  int response=client.executeMethod(method);
  Assert.assertEquals(200,response);
  Assert.assertEquals("OK",method.getResponseBodyAsString());
  method=new GetMethod(Deployments.CONTEXT_PATH + "dummy/?cid=1234");
  response=client.executeMethod(method);
  Assert.assertEquals(200,response);
  Assert.assertEquals("OK",method.getResponseBodyAsString());
}
 

Example 6

From project eclipse-instasearch, under directory /instasearch/src/it/unibz/instasearch/jobs/.

Source file: CheckUpdatesJob.java

  32 
vote

private boolean checkForUpdates(IProgressMonitor monitor) throws HttpException, IOException, URISyntaxException {
  updateAvailable=false;
  String versionCheckUrl=InstaSearchPlugin.getUpdateLocation();
  String v=InstaSearchPlugin.getVersion();
  HttpClient httpClient=new HttpClient();
  configureProxy(httpClient,versionCheckUrl);
  GetMethod getMethod=new GetMethod(versionCheckUrl + "?v=" + v);
  int statusCode=httpClient.executeMethod(getMethod);
  if (statusCode != HttpStatus.SC_OK)   return updateAvailable;
  String response=getMethod.getResponseBodyAsString();
  getMethod.releaseConnection();
  if ("y".equals(response))   updateAvailable=true;
  return updateAvailable;
}
 

Example 7

From project ereviewboard, under directory /org.review_board.ereviewboard.core/src/org/review_board/ereviewboard/core/client/.

Source file: ReviewboardHttpClient.java

  32 
vote

private HttpClient createAndInitHttpClient(String characterEncoding,boolean selfSignedSSL){
  if (selfSignedSSL) {
    Protocol.registerProtocol("https",new Protocol("https",new EasySSLProtocolSocketFactory(),443));
  }
  HttpClient httpClient=new HttpClient();
  WebUtil.configureHttpClient(httpClient,"Mylyn");
  httpClient.getParams().setContentCharset(characterEncoding);
  return httpClient;
}
 

Example 8

From project eucalyptus, under directory /clc/modules/storage-controller/src/edu/ucsb/eucalyptus/cloud/ws/tests/.

Source file: CreateSnapshotTest.java

  32 
vote

public void testSendDummy() throws Throwable {
  HttpClient httpClient=new HttpClient();
  String addr=System.getProperty(WalrusProperties.URL_PROPERTY) + "/meh/ttt.wsl?gg=vol&hh=snap";
  HttpMethodBase method=new PutMethod(addr);
  method.setRequestHeader("Authorization","Euca");
  method.setRequestHeader("Date",(new Date()).toString());
  method.setRequestHeader("Expect","100-continue");
  httpClient.executeMethod(method);
  String responseString=method.getResponseBodyAsString();
  System.out.println(responseString);
  method.releaseConnection();
}
 

Example 9

From project Foglyn, under directory /com.foglyn.core/src/com/foglyn/core/.

Source file: FoglynCorePlugin.java

  32 
vote

public void start(BundleContext context) throws Exception {
  super.start(context);
  ServiceTracker pt=new ServiceTracker(context,IProxyService.class.getName(),null);
  proxyServiceTracker.set(pt);
  pt.open();
  this.connectionManager.set(new MultiThreadedHttpConnectionManager());
  HttpClient hc=createHttpClient(connectionManager.get());
  this.httpClient.set(hc);
  this.clientFactory.set(new FogBugzClientFactory(hc));
  plugin.set(this);
}
 

Example 10

From project GeoBI, under directory /print/src/test/java/org/mapfish/print/.

Source file: FakeHttpd.java

  32 
vote

public void shutdown() throws IOException, InterruptedException {
  GetMethod method=new GetMethod("http://localhost:" + port + "/stop");
  HttpClient client=new HttpClient();
  client.executeMethod(method);
  join();
}
 

Example 11

From project guj.com.br, under directory /src/br/com/caelum/guj/newsletter/request/.

Source file: NewsletterRequest.java

  32 
vote

public void executeRequest(String url){
  HttpMethod get=new GetMethod(url);
  HttpClient client=new HttpClient();
  try {
    client.executeMethod(get);
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
 finally {
    get.releaseConnection();
  }
}
 

Example 12

From project interoperability-framework, under directory /interfaces/taverna/T2-Client/workflow-lib/src/main/java/eu/impact_project/iif/t2/client/.

Source file: Helper.java

  32 
vote

/** 
 * Creates an http client that uses basic authentication. The credentials will be sent preemptively with each request.
 * @param domain Authentication domain
 * @param user User name for basic authentication
 * @param password Password for basic authentication
 * @return Created client object
 */
public static HttpClient createAuthenticatingClient(String domain,String user,String password){
  HttpClient client=new HttpClient();
  client.getParams().setAuthenticationPreemptive(true);
  client.getState().setCredentials(new AuthScope(domain,-1),new UsernamePasswordCredentials(user,password));
  return client;
}
 

Example 13

From project jBilling, under directory /src/java/com/sapienter/jbilling/server/payment/tasks/.

Source file: PaymentSageTask.java

  32 
vote

/** 
 * Make request to agteway
 * @return response from gateway
 */
private String makeCall(NVPList request,boolean isAch) throws IOException {
  LOG.debug("Request to " + PROCESSOR + " gateway sending...");
  HttpClient client=new HttpClient();
  client.setConnectionTimeout(getTimeoutSeconds() * 1000);
  PostMethod post=new PostMethod(getUrl(isAch));
  post.setRequestBody(request.toArray());
  client.executeMethod(post);
  String responseBody=post.getResponseBodyAsString();
  LOG.debug("Got response:" + responseBody);
  post.releaseConnection();
  post.recycle();
  return responseBody;
}
 

Example 14

From project jbpm-form-builder, under directory /jbpm-gwt-form-builder/src/test/java/org/jbpm/formbuilder/server/file/.

Source file: GuvnorFileServiceTest.java

  32 
vote

public void testStoreFileOK() throws Exception {
  GuvnorFileService service=createService("http://www.redhat.com","user","pass");
  HttpClient client=EasyMock.createMock(HttpClient.class);
  Map<String,Integer> statuses=new HashMap<String,Integer>();
  statuses.put("GET http://www.redhat.com/rest/packages/somePackage/assets/fileName-upfile",404);
  EasyMock.expect(client.executeMethod(EasyMock.isA(MockGetMethod.class))).andAnswer(new MockAnswer(statuses)).once();
  EasyMock.expect(client.executeMethod(EasyMock.isA(MockPostMethod.class))).andReturn(201).once();
  service.getHelper().setClient(client);
  EasyMock.replay(client);
  String url=service.storeFile("somePackage","fileName.txt",new byte[]{1,2,3,4,5,6,7,8,9});
  EasyMock.verify(client);
  assertNotNull("url shouldn't be null",url);
}
 

Example 15

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Commands/.

Source file: cmdURL.java

  31 
vote

private String getTinyUrl(String fullUrl){
  try {
    HttpClient httpclient=new HttpClient();
    HttpMethod method=new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[]{new NameValuePair("url",fullUrl)});
    httpclient.executeMethod(method);
    String tinyUrl=method.getResponseBodyAsString();
    method.releaseConnection();
    return tinyUrl;
  }
 catch (  Exception e) {
    ConsoleUtils.printException(e,pluginName,"Can't tiny the URL " + fullUrl + " !");
    return null;
  }
}
 

Example 16

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  31 
vote

protected int executeFormConfigUpload(String formConfig){
  HttpState state=new HttpState();
  state.setCredentials(new AuthScope(null,AuthScope.ANY_PORT),new UsernamePasswordCredentials(cmisUser,cmisPassword));
  LOGGER.info("Deploying form config XML: ");
  prettyLogXml(formConfig);
  PostMethod postMethod=new PostMethod(FORM_CONFIG_UPLOAD_URL);
  try {
    postMethod.setRequestEntity(new StringRequestEntity(formConfig,"application/xml","UTF-8"));
    HttpClient httpClient=new HttpClient();
    int result=httpClient.executeMethod(null,postMethod,state);
    LOGGER.info("Response status code: " + result);
    LOGGER.info("Response body: ");
    LOGGER.info(postMethod.getResponseBodyAsString());
    return result;
  }
 catch (  Throwable t) {
    System.err.println("Error: " + t.getMessage());
    t.printStackTrace();
  }
 finally {
    postMethod.releaseConnection();
  }
  throw new RuntimeException("Programmatic error. You shouldn't be here.");
}
 

Example 17

From project android-client, under directory /xwiki-android-test-fixture-setup/src/org/xwiki/test/integration/utils/.

Source file: XWikiExecutor.java

  31 
vote

public Response isXWikiStarted(String url,int timeout) throws Exception {
  HttpClient client=new HttpClient();
  boolean connected=false;
  long startTime=System.currentTimeMillis();
  Response response=new Response();
  response.timedOut=false;
  response.responseCode=-1;
  response.responseBody=new byte[0];
  while (!connected && !response.timedOut) {
    GetMethod method=new GetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(0,false));
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,new Integer(10000));
    try {
      response.responseCode=client.executeMethod(method);
      response.responseBody=method.getResponseBody();
      if (DEBUG) {
        System.out.println(String.format("Result of pinging [%s] = [%s], Message = [%s]",url,response.responseCode,new String(response.responseBody)));
      }
      connected=(response.responseCode < 400 || response.responseCode == 401);
    }
 catch (    Exception e) {
    }
 finally {
      method.releaseConnection();
    }
    Thread.sleep(500L);
    response.timedOut=(System.currentTimeMillis() - startTime > timeout * 1000L);
  }
  return response;
}
 

Example 18

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/util/binsearch/impl/.

Source file: HTTPSeekableLineReaderFactory.java

  31 
vote

public HTTPSeekableLineReaderFactory(String uriString){
  connectionManager=new MultiThreadedHttpConnectionManager();
  hostConfiguration=new HostConfiguration();
  HttpClientParams params=new HttpClientParams();
  http=new HttpClient(params,connectionManager);
  http.setHostConfiguration(hostConfiguration);
  this.uriString=uriString;
}
 

Example 19

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/deploy/activebpel/.

Source file: ActiveBPELDeployer.java

  31 
vote

/** 
 * @param re SOAP request entity to be sent to ActiveBPEL.
 * @return Response from the ActiveBPEL administration service.
 * @throws IOException
 */
private static RequestResult sendRequestToActiveBPEL(final String url,RequestEntity re) throws IOException {
  PostMethod method=null;
  try {
    HttpClient client=new HttpClient(new NoPersistenceConnectionManager());
    method=new PostMethod(url);
    method.setRequestEntity(re);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(1,false));
    method.addRequestHeader("SOAPAction","");
    client.executeMethod(method);
    RequestResult result=new RequestResult();
    result.setStatusCode(method.getStatusCode());
    result.setResponseBody(method.getResponseBodyAsString());
    return result;
  }
  finally {
    if (method != null) {
      method.releaseConnection();
    }
  }
}
 

Example 20

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/adapter/.

Source file: ConfigurableHttpCalendarAdapter.java

  31 
vote

/** 
 * Uses Commons HttpClient to retrieve the specified url (optionally with the provided  {@link Credentials}. The response body is returned as an  {@link InputStream}.
 * @param url URL of the calendar to be retrieved
 * @param credentials {@link Credentials} to use with the request, if necessary (null is ok if credentials not required)
 * @return the body of the http response as a stream
 * @throws CalendarException wraps all potential {@link Exception} types 
 */
protected InputStream retrieveCalendarHttp(String url,Credentials credentials) throws CalendarException {
  HttpClient client=new HttpClient();
  if (null != credentials) {
    client.getState().setCredentials(AuthScope.ANY,credentials);
  }
  GetMethod get=null;
  try {
    if (log.isDebugEnabled()) {
      log.debug("Retrieving calendar " + url);
    }
    get=new GetMethod(url);
    int rc=client.executeMethod(get);
    if (rc == HttpStatus.SC_OK) {
      log.debug("request completed successfully");
      InputStream in=get.getResponseBodyAsStream();
      ByteArrayOutputStream buffer=new ByteArrayOutputStream();
      IOUtils.copyLarge(in,buffer);
      return new ByteArrayInputStream(buffer.toByteArray());
    }
 else {
      log.warn("HttpStatus for " + url + ":"+ rc);
      throw new CalendarException("non successful status code retrieving " + url + ", status code: "+ rc);
    }
  }
 catch (  HttpException e) {
    log.warn("Error fetching iCalendar feed",e);
    throw new CalendarException("Error fetching iCalendar feed",e);
  }
catch (  IOException e) {
    log.warn("Error fetching iCalendar feed",e);
    throw new CalendarException("Error fetching iCalendar feed",e);
  }
 finally {
    if (get != null) {
      get.releaseConnection();
    }
  }
}
 

Example 21

From project Carolina-Digital-Repository, under directory /access/src/main/java/edu/unc/lib/dl/ui/service/.

Source file: DjatokaContentService.java

  31 
vote

public void getMetadata(String simplepid,String datastream,OutputStream outStream,HttpServletResponse response,int retryServerError){
  HttpClientParams params=new HttpClientParams();
  params.setContentCharset("UTF-8");
  HttpClient client=new HttpClient();
  client.setParams(params);
  StringBuilder path=new StringBuilder(applicationPathSettings.getDjatokaPath());
  path.append("resolver?url_ver=Z39.88-2004&rft_id=").append(applicationPathSettings.getFedoraPathWithoutDefaultPort()).append("/objects/").append(simplepid).append("/datastreams/").append(datastream).append("/content").append("&svc_id=info:lanl-repo/svc/getMetadata");
  GetMethod method=new GetMethod(path.toString());
  try {
    client.executeMethod(method);
    if (method.getStatusCode() == HttpStatus.SC_OK) {
      if (response != null) {
        response.setHeader("Content-Type","application/json");
        response.setHeader("content-disposition","inline");
        FileIOUtil.stream(outStream,method);
      }
    }
 else {
      if ((method.getStatusCode() == 500 || method.getStatusCode() == 404) && retryServerError > 0) {
        this.getMetadata(simplepid,datastream,outStream,response,retryServerError - 1);
      }
 else {
        LOG.error("Unexpected failure: " + method.getStatusLine().toString());
        LOG.error("Path was: " + method.getURI().getURI());
      }
    }
  }
 catch (  Exception e) {
    LOG.error("Problem retrieving metadata for " + path,e);
  }
 finally {
    method.releaseConnection();
  }
}
 

Example 22

From project caseconductor-platform, under directory /utest-domain-services/src/main/java/com/utest/domain/service/util/.

Source file: FileUploadUtil.java

  31 
vote

public static void uploadFile(final File targetFile,final String targetURL,final String targerFormFieldName_) throws Exception {
  final PostMethod filePost=new PostMethod(targetURL);
  filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,true);
  filePost.addRequestHeader("X-Atlassian-Token","no-check");
  try {
    final FilePart fp=new FilePart(targerFormFieldName_,targetFile);
    fp.setTransferEncoding(null);
    final Part[] parts={fp};
    filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
    final HttpClient client=new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    final int status=client.executeMethod(filePost);
    if (status == HttpStatus.SC_OK) {
      Logger.getLogger(FileUploadUtil.class).info("Upload complete, response=" + filePost.getResponseBodyAsString());
    }
 else {
      Logger.getLogger(FileUploadUtil.class).info("Upload failed, response=" + HttpStatus.getStatusText(status));
    }
  }
 catch (  final Exception ex) {
    Logger.getLogger(FileUploadUtil.class).error("ERROR: " + ex.getClass().getName() + " "+ ex.getMessage(),ex);
    throw ex;
  }
 finally {
    Logger.getLogger(FileUploadUtil.class).debug(new String(filePost.getResponseBody()));
    filePost.releaseConnection();
  }
}
 

Example 23

From project community-plugins, under directory /deployit-udm-plugins/utility-plugins/deployment-test-plugin/src/main/java/com/xebialabs/deployit/plugins/tests/step/.

Source file: LocalHttpTesterStep.java

  31 
vote

@Override protected Result doExecute() throws Exception {
  HttpClient client=new HttpClient();
  GetMethod method=new GetMethod(url);
  try {
    getCtx().logOutput("Waiting for " + startDelay + " secs before executing step");
    waitFor(startDelay);
    return verifyContentWithRetryAttempts(getCtx(),client,method);
  }
 catch (  InterruptedException e) {
    Thread.currentThread().interrupt();
  }
 finally {
    method.releaseConnection();
  }
  return Result.Fail;
}
 

Example 24

From project data-access, under directory /src/org/pentaho/platform/dataaccess/client/.

Source file: ConnectionServiceClient.java

  31 
vote

/** 
 * Returns an instance of an HttpClient. Only one is created per  ConnectionServiceClient so all calls should be made synchronously.
 * @return The HTTP client to be used for web service calls
 */
private HttpClient getClient(){
  if (httpClientInstance == null) {
    httpClientInstance=new HttpClient();
    if ((userId != null) && (userId.length() > 0) && (password != null)&& (password.length() > 0)) {
      Credentials creds=new UsernamePasswordCredentials(userId,password);
      httpClientInstance.getState().setCredentials(AuthScope.ANY,creds);
      httpClientInstance.getParams().setAuthenticationPreemptive(true);
    }
  }
  return httpClientInstance;
}
 

Example 25

From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/model/util/.

Source file: RESTFacade.java

  31 
vote

public RESTFacade(int connectionTimeout,int socketTimeout){
  httpClient=new HttpClient();
  final String proxyHost=System.getProperty("http.proxyHost");
  final String proxyPort=System.getProperty("http.proxyPort");
  logger.debug("configure proxy with " + proxyHost + ":"+ proxyPort);
  if (proxyHost != null && proxyPort != null && !"".equals(proxyHost) && !"".equals(proxyPort)) {
    httpClient.getHostConfiguration().setProxy(proxyHost,new Integer(proxyPort));
  }
  final HttpClientParams params=new HttpClientParams();
  params.setConnectionManagerTimeout(connectionTimeout);
  httpClient.setParams(params);
}
 

Example 26

From project Diver, under directory /ca.uvic.chisel.logging.eclipse/src/ca/uvic/chisel/logging/eclipse/internal/network/.

Source file: LogUploadRunnable.java

  31 
vote

public void run(IProgressMonitor sendMonitor) throws InterruptedException, InvocationTargetException {
  File[] filesToUpload=log.getCategory().getFilesToUpload();
  sendMonitor.beginTask("Uploading Log " + log.getCategory().getName(),filesToUpload.length);
  LoggingCategory category=log.getCategory();
  IMemento memento=category.getMemento();
  for (  File file : filesToUpload) {
    if (sendMonitor.isCanceled()) {
      throw new InterruptedException();
    }
    PostMethod post=new PostMethod(category.getURL().toString());
    try {
      Part[] parts={new StringPart("KIND","workbench-log"),new StringPart("CATEGORY",category.getCategoryID()),new StringPart("USER",WorkbenchLoggingPlugin.getDefault().getLocalUser()),new FilePart("WorkbenchLogger",file.getName(),file,"application/zip",null)};
      post.setRequestEntity(new MultipartRequestEntity(parts,post.getParams()));
      HttpClient client=new HttpClient();
      int status=client.executeMethod(post);
      String resp=getData(post.getResponseBodyAsStream());
      if (status != 200 || !resp.startsWith("Status: 200 Success")) {
        IOException ex=new IOException(resp);
        throw (ex);
      }
      memento.putString("lastUpload",file.getName());
      file.delete();
    }
 catch (    IOException e) {
      throw new InvocationTargetException(e);
    }
 finally {
      sendMonitor.worked(1);
    }
  }
  sendMonitor.done();
}
 

Example 27

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/location/.

Source file: ClientClass.java

  31 
vote

public boolean connectMe(){
  client=new HttpClient();
  postMethod=new PostMethod(uri);
  if (client == null)   return false;
 else {
    return true;
  }
}
 

Example 28

From project Ebselen, under directory /ebselen-core/src/main/java/com/lazerycode/ebselen/customhandlers/.

Source file: FileDownloader.java

  31 
vote

public String downloader(WebElement element,String attribute) throws Exception {
  String downloadLocation=element.getAttribute(attribute);
  if (downloadLocation.trim().equals("")) {
    throw new Exception("The element you have specified does not link to anything!");
  }
  URL downloadURL=new URL(downloadLocation);
  HttpClient client=new HttpClient();
  client.getParams().setCookiePolicy(CookiePolicy.RFC_2965);
  client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(),downloadURL.getPort()));
  client.setState(mimicCookieState(driver.manage().getCookies()));
  HttpMethod getRequest=new GetMethod(downloadURL.getPath());
  FileHandler downloadedFile=new FileHandler(downloadPath + downloadURL.getFile().replaceFirst("/|\\\\",""),true);
  try {
    int status=client.executeMethod(getRequest);
    LOGGER.info("HTTP Status {} when getting '{}'",status,downloadURL.toExternalForm());
    BufferedInputStream in=new BufferedInputStream(getRequest.getResponseBodyAsStream());
    int offset=0;
    int len=4096;
    int bytes=0;
    byte[] block=new byte[len];
    while ((bytes=in.read(block,offset,len)) > -1) {
      downloadedFile.getWritableFileOutputStream().write(block,0,bytes);
    }
    downloadedFile.close();
    in.close();
    LOGGER.info("File downloaded to '{}'",downloadedFile.getAbsoluteFile());
  }
 catch (  Exception Ex) {
    LOGGER.error("Download failed: {}",Ex);
    throw new Exception("Download failed!");
  }
 finally {
    getRequest.releaseConnection();
  }
  return downloadedFile.getAbsoluteFile();
}
 

Example 29

From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.core/src/org/springsource/ide/eclipse/commons/internal/core/net/.

Source file: HttpClientTransportService.java

  31 
vote

/** 
 * Verify availability of resources at the given web locations. Normally this would be done using an HTTP HEAD.
 * @param locations the locations of the resource to verify
 * @param one indicate if only one of the resources must exist
 * @param progressMonitor the monitor
 * @return true if the resource exists
 */
public long getLastModified(java.net.URI uri,IProgressMonitor progressMonitor) throws CoreException {
  WebLocation location=new WebLocation(uri.toString());
  SubMonitor monitor=SubMonitor.convert(progressMonitor);
  monitor.subTask(NLS.bind("Fetching {0}",location.getUrl()));
  try {
    HttpClient client=new HttpClient();
    org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client,"");
    HeadMethod method=new HeadMethod(location.getUrl());
    try {
      HostConfiguration hostConfiguration=org.eclipse.mylyn.commons.net.WebUtil.createHostConfiguration(client,location,monitor);
      int result=org.eclipse.mylyn.commons.net.WebUtil.execute(client,hostConfiguration,method,monitor);
      if (result == HttpStatus.SC_OK) {
        Header lastModified=method.getResponseHeader("Last-Modified");
        if (lastModified != null) {
          try {
            return DateUtil.parseDate(lastModified.getValue()).getTime();
          }
 catch (          DateParseException e) {
          }
        }
        return 0;
      }
 else {
        throw toException(location,result);
      }
    }
 catch (    IOException e) {
      throw toException(location,e);
    }
 finally {
      method.releaseConnection();
    }
  }
  finally {
    monitor.done();
  }
}
 

Example 30

From project embed-for-vaadin, under directory /com.bsb.common.vaadin.embed/src/test/java/com/bsb/common/vaadin/embed/.

Source file: AbstractEmbedTest.java

  31 
vote

protected void checkVaadinIsDeployed(int port,String context){
  final StringBuilder sb=new StringBuilder();
  sb.append("http://localhost:").append(port);
  if (context.trim().isEmpty() || context.equals("/")) {
    sb.append("/");
  }
 else {
    sb.append(context);
  }
  final String url=sb.toString();
  final HttpClient client=new HttpClient();
  client.getParams().setConnectionManagerTimeout(2000);
  final GetMethod method=new GetMethod(url);
  try {
    assertEquals("Wrong return code invoking [" + url + "]",HttpStatus.SC_OK,client.executeMethod(method));
  }
 catch (  IOException e) {
    throw new IllegalStateException("Failed to invoke url [" + url + "]",e);
  }
}
 

Example 31

From project gatein-sso, under directory /agent/src/main/java/org/gatein/sso/agent/opensso/.

Source file: OpenSSOAgent.java

  31 
vote

private boolean isTokenValid(String token) throws Exception {
  HttpClient client=new HttpClient();
  PostMethod post=null;
  try {
    String url=this.serverUrl + "/identity/isTokenValid";
    post=new PostMethod(url);
    post.addParameter("tokenid",token);
    int status=client.executeMethod(post);
    String response=post.getResponseBodyAsString();
    log.debug("-------------------------------------------------------");
    log.debug("Status: " + status);
    log.debug("Response: " + response);
    log.debug("-------------------------------------------------------");
    if (response.contains(Boolean.TRUE.toString())) {
      return true;
    }
    return false;
  }
  finally {
    if (post != null) {
      post.releaseConnection();
    }
  }
}
 

Example 32

From project glimpse, under directory /glimpse-client/src/main/java/br/com/tecsinapse/glimpse/client/http/.

Source file: HttpInvoker.java

  31 
vote

public String invoke(String context,String body){
  try {
    HttpClient client=new HttpClient();
    PostMethod post=new PostMethod(url + context);
    String base64=username + ":" + password;
    post.setRequestHeader("Authorization","Basic " + new String(Base64.encodeBase64(base64.getBytes())));
    post.setRequestEntity(new StringRequestEntity(body,"text/plain","UTF-8"));
    int statusCode=client.executeMethod(post);
    StringBuilder builder=new StringBuilder();
    InputStream in=post.getResponseBodyAsStream();
    if (in != null) {
      int c=0;
      while ((c=in.read()) != -1) {
        builder.append((char)c);
      }
    }
    post.releaseConnection();
    if (statusCode == HttpStatus.SC_OK) {
      return builder.toString();
    }
 else     if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
      return "update\nStatus: " + statusCode + "\nUnauthorized Access, check your username and password.\nclose\n";
    }
 else {
      return "update\nStatus: " + statusCode + "\n"+ builder.toString()+ "\nclose\n";
    }
  }
 catch (  UnsupportedEncodingException e) {
    return exceptionResult(e);
  }
catch (  HttpException e) {
    return exceptionResult(e);
  }
catch (  IOException e) {
    return exceptionResult(e);
  }
}
 

Example 33

From project Hesperid, under directory /microclient/src/main/java/ch/astina/hesperid/microclient/.

Source file: MicroClient.java

  31 
vote

private String getVersionOnServer(){
  String version="";
  HttpClient client=new HttpClient();
  HttpMethod method=new GetMethod(xmlConfiguration.getString("hostBaseURL") + "/microclient/latestagentversion");
  try {
    client.executeMethod(method);
    version=method.getResponseBodyAsString();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    try {
      method.releaseConnection();
    }
 catch (    Exception exx) {
      exx.printStackTrace();
    }
  }
  return version;
}
 

Example 34

From project httpobjects, under directory /jetty/src/test/java/org/httpobjects/jetty/.

Source file: IntegrationTest.java

  31 
vote

private void assertResource(HttpMethod method,String expectedBody,int expectedResponseCode,HeaderSpec... header){
  try {
    HttpClient client=new HttpClient();
    int response=client.executeMethod(method);
    Assert.assertEquals(expectedResponseCode,response);
    if (expectedBody != null)     Assert.assertEquals(expectedBody,method.getResponseBodyAsString());
    if (header != null) {
      for (      HeaderSpec next : header) {
        Header h=method.getResponseHeader(next.name);
        Assert.assertNotNull("Expected a \"" + next.name + "\" value of \""+ next.value+ "\"",h);
        Assert.assertEquals(next.value,h.getValue());
      }
    }
  }
 catch (  HttpException e) {
    throw new RuntimeException(e);
  }
catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 35

From project ihtika, under directory /Incubator/JenkinsHandler/src/main/java/khartn/jenkinshandler/.

Source file: SecuredMain.java

  31 
vote

/** 
 * On most security configurations, except "delegate to servlet container" authentication, simply sending in the BASIC authentication pre-emptively works. See http://hc.apache.org/httpclient-3.x/authentication.html for how to configure pre-emptive authentication. <p> However, in the "delegate to servlet container" mode, BASIC auth support depends on the container implementation, and hence inherently unreliable. The following code uses Jakarta Commons HTTP client to work around this problem by essentially emulating what the user does through the browser. <p> The code first emulates a click of the "login" link, then submit the login form. Once that's done, you are authenticated, so you can access the information you wanted. This is all possible because {@link HttpClient} maintains a cookie jar in it.
 */
public static void main(String[] args) throws IOException {
  HttpClient client=new HttpClient();
  String hostName="https://ihtika-hantest.rhcloud.com/";
  GetMethod loginLink=new GetMethod(hostName + "loginEntry");
  client.executeMethod(loginLink);
  checkResult(loginLink.getStatusCode());
  String location=hostName + "j_acegi_security_check";
  while (true) {
    PostMethod loginMethod=new PostMethod(location);
    loginMethod.addParameter("j_username","externaluser");
    loginMethod.addParameter("j_password","externaluser");
    loginMethod.addParameter("action","login");
    client.executeMethod(loginMethod);
    if (loginMethod.getStatusCode() / 100 == 3) {
      location=loginMethod.getResponseHeader("Location").getValue();
      continue;
    }
    System.out.println(loginMethod.getStatusCode());
    checkResult(loginMethod.getStatusCode());
    break;
  }
  HttpMethod method=new GetMethod(hostName + "/job/ihtika-build/build");
  client.executeMethod(method);
  System.out.println(method.getStatusCode());
}
 

Example 36

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/ontologiser/logic/impl/.

Source file: AnnotatorSearchClient.java

  31 
vote

public Map<String,Map<String,AnnotatorResult>> searchForTerms(Set<String> terms,String ontologiesToSearchOn,boolean wholeWordOnly){
  try {
    HttpClient client=new HttpClient();
    PostMethod method=new PostMethod(BASE_QUERY_URL);
    method.addParameter("wholeWordOnly",wholeWordOnly ? " true" : "false");
    method.addParameter("scored","true");
    method.addParameter("ontologiesToKeepInResult",ontologiesToSearchOn);
    method.addParameter("isVirtualOntologyId","true");
    method.addParameter("withSynonyms","true");
    method.addParameter("textToAnnotate",flattenSetToString(terms));
    method.addParameter("apikey","fd88ee35-6995-475d-b15a-85f1b9dd7a42");
    try {
      HostConfiguration configuration=new HostConfiguration();
      configuration.setHost("http://rest.bioontology.org");
      configuration.setProxy(System.getProperty("http.proxyHost"),Integer.valueOf(System.getProperty("http.proxyPort")));
      client.setHostConfiguration(configuration);
    }
 catch (    Exception e) {
      System.err.println("Problem encountered setting proxy for annotator search");
    }
    int statusCode=client.executeMethod(method);
    if (statusCode != -1) {
      String contents=method.getResponseBodyAsString();
      method.releaseConnection();
      return processContent(contents,terms);
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 37

From project jabox, under directory /cis-hudson/src/main/java/org/jabox/cis/hudson/.

Source file: HudsonConnector.java

  31 
vote

/** 
 * Implementation inspired by groovy code here: http://wiki.hudson-ci.org/display/HUDSON/Authenticating+scripted+clients
 */
public boolean addProject(final Project project,final CISConnectorConfig dc) throws IOException, SAXException {
  HudsonConnectorConfig hcc=(HudsonConnectorConfig)dc;
  String url=dc.getServer().getUrl();
  HttpClient client=new HttpClient();
  client.getState().setCredentials(null,null,new UsernamePasswordCredentials(hcc.getUsername(),hcc.getPassword()));
  client.getState().setAuthenticationPreemptive(true);
  String uri=url + "createItem?name=" + project.getName();
  PostMethod post=new PostMethod(uri);
  post.setDoAuthentication(true);
  post.setRequestHeader("Content-type","text/xml; charset=UTF-8");
  InputStream is=getConfigXMLStream(project);
  String body=parseInputStream(is,project);
  post.setRequestBody(body);
  try {
    int result=client.executeMethod(post);
    System.out.println("Return code: " + result);
    for (    Header header : post.getResponseHeaders()) {
      System.out.println(header.toString().trim());
    }
    System.out.println(post.getResponseBodyAsString());
  }
  finally {
    post.releaseConnection();
  }
  PostMethod triggerBuild=new PostMethod(url + "/job/" + project.getName()+ "/build");
  client.executeMethod(triggerBuild);
  return true;
}
 

Example 38

From project JasigWidgetPortlets, under directory /src/main/java/org/jasig/portlet/widget/service/xml/.

Source file: HttpXmlAlertService.java

  31 
vote

@Override protected Document loadDocument(PortletRequest req){
  if (log.isInfoEnabled()) {
    log.info("Updating feed from external source");
  }
  Document rslt=null;
  final String url=req.getPreferences().getValue(URL_PREFERENCE,null);
  HttpClient client=new HttpClient();
  HttpMethod get=new GetMethod(url.toString());
  Reader inpt=null;
  try {
    int statusCode=client.executeMethod(get);
    if (statusCode != HttpStatus.SC_OK) {
      String msg="Method failed: " + get.getStatusLine();
      throw new RuntimeException(msg);
    }
    byte[] responseBody=get.getResponseBody();
    String xml=new String(responseBody).trim();
    inpt=new CharArrayReader(xml.toCharArray());
    rslt=new SAXReader().read(inpt);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
 finally {
    if (inpt != null) {
      try {
        inpt.close();
      }
 catch (      IOException ioe) {
        log.warn(ioe.getMessage(),ioe);
      }
    }
    get.releaseConnection();
  }
  return rslt;
}
 

Example 39

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHTTPClient.java

  30 
vote

public AGHTTPClient(String serverURL,HttpConnectionManager manager){
  this.serverURL=serverURL;
  if (manager == null) {
    mManager=new MultiThreadedHttpConnectionManager();
    manager=mManager;
    HttpConnectionManagerParams params=new HttpConnectionManagerParams();
    params.setDefaultMaxConnectionsPerHost(Integer.MAX_VALUE);
    params.setMaxTotalConnections(Integer.MAX_VALUE);
    manager.setParams(params);
  }
  httpClient=new HttpClient(manager);
  if (logger.isDebugEnabled()) {
    logger.debug("connect: " + serverURL + " "+ httpClient+ " "+ manager);
  }
}
 

Example 40

From project any23, under directory /core/src/main/java/org/apache/any23/http/.

Source file: DefaultHTTPClient.java

  30 
vote

private void ensureClientInitialized(){
  if (configuration == null)   throw new IllegalStateException("client must be initialized first.");
  if (client != null)   return;
  client=new HttpClient(manager);
  HttpConnectionManager connectionManager=client.getHttpConnectionManager();
  HttpConnectionManagerParams params=connectionManager.getParams();
  params.setConnectionTimeout(configuration.getDefaultTimeout());
  params.setSoTimeout(configuration.getDefaultTimeout());
  params.setMaxTotalConnections(configuration.getMaxConnections());
  HostConfiguration hostConf=client.getHostConfiguration();
  List<Header> headers=new ArrayList<Header>();
  headers.add(new Header("User-Agent",configuration.getUserAgent()));
  if (configuration.getAcceptHeader() != null) {
    headers.add(new Header("Accept",configuration.getAcceptHeader()));
  }
  headers.add(new Header("Accept-Language","en-us,en-gb,en,*;q=0.3"));
  headers.add(new Header("Accept-Charset","utf-8,iso-8859-1;q=0.7,*;q=0.5"));
  hostConf.getParams().setParameter("http.default-headers",headers);
}
 

Example 41

From project flume-twitter, under directory /src/main/java/st/happy_camper/flume/twitter/.

Source file: TwitterStreamingConnection.java

  30 
vote

/** 
 * @param name
 * @param password
 * @param connectionTimeout
 * @throws IOException
 */
public TwitterStreamingConnection(String name,String password,int connectionTimeout) throws IOException {
  httpClient=new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
  httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);
  httpClient.getParams().setAuthenticationPreemptive(true);
  httpClient.getState().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(name,password));
  doOpen();
  Executors.newSingleThreadExecutor(new ThreadFactory(){
    @Override public Thread newThread(    Runnable runnable){
      return new Thread(runnable,"TwitterStreamingConnection");
    }
  }
).execute(new Runnable(){
    @Override public void run(){
      BlockingQueue<String> queue=TwitterStreamingConnection.this.queue;
      String line;
      while ((line=readLine()) != null) {
        queue.add(line);
      }
    }
  }
);
}
 

Example 42

From project heritrix3, under directory /modules/src/main/java/org/archive/modules/fetcher/.

Source file: FetchHTTP.java

  30 
vote

protected void configureHttp(int soTimeout,String addressStr,String proxy,int port,String user,String password){
  int timeout=(soTimeout > 0) ? soTimeout : 0;
  HttpConnectionManager cm=new SingleHttpConnectionManager();
  HttpConnectionManagerParams hcmp=cm.getParams();
  hcmp.setConnectionTimeout(timeout);
  hcmp.setStaleCheckingEnabled(true);
  hcmp.setTcpNoDelay(false);
  this.http=new HttpClient(cm);
  HttpClientParams hcp=this.http.getParams();
  hcp.setSoTimeout(timeout);
  hcp.setVersion(HttpVersion.HTTP_1_0);
  this.http.getParams().setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER,new Boolean(true));
  this.http.getParams().setParameter(HttpMethodParams.UNAMBIGUOUS_STATUS_LINE,new Boolean(false));
  this.http.getParams().setParameter(HttpMethodParams.STRICT_TRANSFER_ENCODING,new Boolean(false));
  this.http.getParams().setIntParameter(HttpMethodParams.STATUS_LINE_GARBAGE_LIMIT,10);
  if ((proxy != null) && (proxy.length() == 0)) {
    proxy=null;
  }
  HostConfiguration config=http.getHostConfiguration();
  configureProxy(proxy,port,user,password,config);
  configureBindAddress(addressStr,config);
  hcmp.setParameter(SSL_FACTORY_KEY,this.sslfactory);
}
 

Example 43

From project iserve, under directory /iserve-rest-client/src/main/java/uk/ac/open/kmi/iserve/client/rest/.

Source file: IServeHttpClient.java

  30 
vote

public IServeHttpClient(String serverUrl,String userName,String password) throws MalformedURLException {
  if (serverUrl.endsWith("/")) {
    int len=serverUrl.length();
    serverUrl=serverUrl.substring(0,len - 1);
  }
  this.serverUrl=serverUrl;
  URL url=new URL(this.serverUrl);
  this.host=url.getHost();
  this.port=url.getPort();
  if (-1 == this.port) {
    this.port=80;
  }
  this.servicesUrl=serverUrl + "/data/services/";
  this.documentsUrl=serverUrl + "/data/documents/";
  this.queryUrl=serverUrl + "/data/execute-query";
  this.userName=userName;
  this.password=password;
  this.tika=new Tika();
  this.client=new HttpClient();
  this.client.getState().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(userName,password));
}