List of usage examples for org.apache.commons.httpclient.methods FileRequestEntity FileRequestEntity
public FileRequestEntity(final File file, final String contentType)
From source file:au.org.ala.spatial.util.UploadSpatialResource.java
public static String loadSld(String url, String extra, String username, String password, String resourcepath) { System.out.println("loadSld url:" + url); System.out.println("path:" + resourcepath); String output = ""; HttpClient client = new HttpClient(); client.setConnectionTimeout(10000);/* w w w . j av a 2s .c o m*/ client.setTimeout(60000); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); client.getParams().setAuthenticationPreemptive(true); File input = new File(resourcepath); PutMethod put = new PutMethod(url); put.setDoAuthentication(true); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "application/vnd.ogc.sld+xml"); put.setRequestEntity(entity); // Execute the request try { int result = client.executeMethod(put); output = result + ": " + put.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(System.out); output = "0: " + e.getMessage(); } finally { // Release current connection to the connection pool once you are done put.releaseConnection(); } return output; }
From source file:com.nokia.helium.diamonds.DiamondsClient.java
private PostMethod getPostMethod(String fileName, String urlPath) { // Get the Diamonds XML-file which is to be exported File input = new File(fileName); // Prepare HTTP post PostMethod post = new PostMethod(urlPath); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity);//from www . j av a 2 s. co m return post; }
From source file:eu.learnpad.cw.rest.internal.DefaultXWikiPackage.java
private void postObject(File objectFile, String spaceName, String pageName, String className) throws XWikiRestException { HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials("Admin", "admin"); httpClient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds); PostMethod postMethod = new PostMethod("http://localhost:8080/xwiki/rest/wikis/xwiki/spaces/" + spaceName + "/pages/" + pageName + "/objects"); postMethod.addRequestHeader("Accept", "application/xml"); postMethod.addRequestHeader("Accept-Ranges", "bytes"); RequestEntity fileRequestEntity = new FileRequestEntity(objectFile, "application/xml"); postMethod.setRequestEntity(fileRequestEntity); try {// w w w . j a v a 2 s . c om httpClient.executeMethod(postMethod); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.linkedin.pinot.common.utils.webhdfs.WebHdfsV1Client.java
public synchronized boolean uploadSegment(String webHdfsPath, String localFilePath) { // Step 1: Submit a HTTP PUT request without automatically following // redirects and without sending the file data. String firstPutReqString = String.format(WEB_HDFS_UPLOAD_PATH_TEMPLATE, _protocol, _host, _port, webHdfsPath, _overwrite, _permission); HttpMethod firstPutReq = new PutMethod(firstPutReqString); try {/* w ww .j a v a 2 s . c o m*/ LOGGER.info("Trying to send request: {}.", firstPutReqString); int firstResponseCode = _httpClient.executeMethod(firstPutReq); if (firstResponseCode != 307) { LOGGER.error(String.format( "Failed to execute the first PUT request to upload segment to webhdfs: %s. " + "Expected response code 307, but get %s. Response body: %s", firstPutReqString, firstResponseCode, firstPutReq.getResponseBodyAsString())); return false; } } catch (Exception e) { LOGGER.error(String.format("Failed to execute the first request to upload segment to webhdfs: %s.", firstPutReqString), e); return false; } finally { firstPutReq.releaseConnection(); } // Step 2: Submit another HTTP PUT request using the URL in the Location // header with the file data to be written. String redirectedReqString = firstPutReq.getResponseHeader(LOCATION).getValue(); PutMethod redirectedReq = new PutMethod(redirectedReqString); File localFile = new File(localFilePath); RequestEntity requestEntity = new FileRequestEntity(localFile, "application/binary"); redirectedReq.setRequestEntity(requestEntity); try { LOGGER.info("Trying to send request: {}.", redirectedReqString); int redirectedResponseCode = _httpClient.executeMethod(redirectedReq); if (redirectedResponseCode != 201) { LOGGER.error(String.format( "Failed to execute the redirected PUT request to upload segment to webhdfs: %s. " + "Expected response code 201, but get %s. Response: %s", redirectedReqString, redirectedResponseCode, redirectedReq.getResponseBodyAsString())); } return true; } catch (IOException e) { LOGGER.error(String.format("Failed to execute the redirected request to upload segment to webhdfs: %s.", redirectedReqString), e); return false; } finally { redirectedReq.releaseConnection(); } }
From source file:com.bdaum.juploadr.uploadapi.smugrest.upload.SmugmugUpload.java
@Override public boolean execute() throws ProtocolException, CommunicationException { HttpClient client = HttpClientFactory.getHttpClient(session.getAccount()); this.monitor.uploadStarted(new UploadEvent(image, 0, true, false)); SortedMap<String, String> params = getParams(); String name = params.get(X_SMUG_FILE_NAME); PutMethod put = new PutMethod(URL + name); for (Map.Entry<String, String> entry : params.entrySet()) put.addRequestHeader(entry.getKey(), entry.getValue()); File file = new File(image.getImagePath()); Asset asset = image.getAsset();/*from w w w. j av a 2 s.c o m*/ FileRequestEntity entity = new FileRequestEntity(file, asset.getMimeType()); put.setRequestEntity(entity); try { int status = client.executeMethod(put); if (status == HttpStatus.SC_OK) { // deal with the response try { String response = put.getResponseBodyAsString(); put.releaseConnection(); boolean success = parseResponse(response); if (success) { image.setState(UploadImage.STATE_UPLOADED); ImageUploadResponse resp = new ImageUploadResponse(handler.getPhotoID(), handler.getKey(), handler.getUrl()); this.monitor.uploadFinished(new UploadCompleteEvent(resp, image)); } else { throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$ } } catch (IOException e) { // TODO: Is it safe to assume the upload failed here? this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$ + e.getMessage(), e); } } else { this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$ } } catch (ConnectException ce) { this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$ } catch (NoRouteToHostException route) { this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$ } catch (UnknownHostException uhe) { this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$ } catch (HttpException e) { this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$ } catch (IOException e) { this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$ + e, e); } return true; }
From source file:com.nokia.helium.diamonds.DiamondsSessionSocket.java
/** * Internal method to send data to diamonds. * If ignore result is true, then the method will return null, else the message return by the query * will be returned.//from w ww. j ava 2 s . c om * @param message * @param ignoreResult * @return * @throws DiamondsException is thrown in case of message retrieval error, connection error. */ protected synchronized String sendInternal(Message message, boolean ignoreResult) throws DiamondsException { URL destURL = url; if (buildId != null) { try { destURL = new URL(url.getProtocol(), url.getHost(), url.getPort(), buildId); } catch (MalformedURLException e) { throw new DiamondsException("Error generating the url to send the message: " + e.getMessage(), e); } } PostMethod post = new PostMethod(destURL.toExternalForm()); try { File tempFile = streamToTempFile(message.getInputStream()); tempFile.deleteOnExit(); messages.add(tempFile); post.setRequestEntity(new FileRequestEntity(tempFile, "text/xml")); } catch (MessageCreationException e) { throw new DiamondsException("Error retrieving the message: " + e.getMessage(), e); } catch (IOException e) { throw new DiamondsException("Error serializing the message into a temporary file: " + e.getMessage(), e); } try { int result = httpClient.executeMethod(post); if (result != HttpStatus.SC_OK && result != HttpStatus.SC_ACCEPTED) { throw new DiamondsException("Error sending the message: " + post.getStatusLine() + "(" + post.getResponseBodyAsString() + ")"); } if (!ignoreResult) { return post.getResponseBodyAsString(); } } catch (HttpException e) { throw new DiamondsException("Error sending the message: " + e.getMessage(), e); } catch (IOException e) { throw new DiamondsException("Error sending the message: " + e.getMessage(), e); } finally { post.releaseConnection(); } return null; }
From source file:it.geosolutions.figis.requester.HTTPUtils.java
/** * PUTs a File to the given URL.//from w ww . j a va 2 s . c om * <BR>Basic auth is used if both username and pw are not null. * * @param url The URL where to connect to. * @param file The File to be sent. * @param contentType The content-type to advert in the PUT. * @param username Basic auth credential. No basic auth if null. * @param pw Basic auth credential. No basic auth if null. * @return The HTTP response as a String if the HTTP response code was 200 (OK). * @throws MalformedURLException * @return the HTTP response or <TT>null</TT> on errors. */ public static String put(String url, File file, String contentType, String username, String pw) { return put(url, new FileRequestEntity(file, contentType), username, pw); }
From source file:au.org.ala.spatial.util.UploadSpatialResource.java
public static String loadCreateStyle(String url, String extra, String username, String password, String name) { System.out.println("loadCreateStyle url:" + url); System.out.println("name:" + name); String output = ""; HttpClient client = new HttpClient(); client.setConnectionTimeout(10000);/*from w w w . j av a 2s.c om*/ client.setTimeout(60000); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); PostMethod post = new PostMethod(url); post.setDoAuthentication(true); // Execute the request try { // Request content will be retrieved directly // from the input stream File file = File.createTempFile("sld", "xml"); FileWriter fw = new FileWriter(file); fw.append("<style><name>" + name + "</name><filename>" + name + ".sld</filename></style>"); fw.close(); RequestEntity entity = new FileRequestEntity(file, "text/xml"); post.setRequestEntity(entity); int result = client.executeMethod(post); output = result + ": " + post.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(System.out); output = "0: " + e.getMessage(); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return output; }
From source file:com.redhat.demo.CrmTest.java
/** * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of * the add_customer.json file to add a new customer to the system. * <p/>// w ww .j ava 2s .c o m * On the server side, it matches the CustomerService's addCustomer() method * * @throws Exception */ @Test public void postCustomerTestJson() throws IOException { LOG.info("Sent HTTP POST request to add customer"); String inputFile = this.getClass().getResource("/add_customer.json").getFile(); File input = new File(inputFile); PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL); post.addRequestHeader("Accept", "application/json"); RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); String res = ""; try { int result = httpclient.executeMethod(post); LOG.info("Response status code: " + result); LOG.info("Response body: "); res = post.getResponseBodyAsString(); LOG.info(res); } catch (IOException e) { LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL); LOG.error( "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test"); LOG.error("Please read the README.md file in 'rest' quick start root"); Assert.fail("Connection error"); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } Assert.assertTrue(res.contains("Jack")); }
From source file:$.CrmTest.java
/** * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of * the add_customer.json file to add a new customer to the system. * <p/>//www.ja v a 2s . c om * On the server side, it matches the CustomerService's addCustomer() method * * @throws Exception */ @Test public void postCustomerTestJson() throws IOException { LOG.info("Sent HTTP POST request to add customer"); String inputFile = this.getClass().getResource("/add_customer.json").getFile(); File input = new File(inputFile); PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL); post.addRequestHeader("Accept", "application/json"); RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); String res = ""; try { int result = httpclient.executeMethod(post); LOG.info("Response status code: " + result); LOG.info("Response body: "); res = post.getResponseBodyAsString(); LOG.info(res); } catch (IOException e) { LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL); LOG.error( "You should build the 'cxf-cdi' quick start and deploy it to a local Fabric8 before running this test"); LOG.error("Please read the README.md file in 'cxf-cdi' quick start root"); Assert.fail("Connection error"); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } Assert.assertTrue(res.contains("Jack")); }