List of usage examples for org.apache.http.entity InputStreamEntity setChunked
public void setChunked(boolean z)
From source file:com.msopentech.odatajclient.engine.utils.URIUtils.java
public static InputStreamEntity buildInputStreamEntity(final ODataClient client, final InputStream input) { InputStreamEntity entity; if (client.getConfiguration().isUseChuncked()) { entity = new InputStreamEntity(input, -1); } else {//from w w w . j a v a 2s . c o m byte[] bytes = new byte[0]; try { bytes = IOUtils.toByteArray(input); } catch (IOException e) { LOG.error("While reading input for not chunked encoding", e); } entity = new InputStreamEntity(new ByteArrayInputStream(bytes), bytes.length); } entity.setChunked(client.getConfiguration().isUseChuncked()); return entity; }
From source file:service.xml.YmlLoaderServiceTest.java
@Test public void test() { HttpClient client = new DefaultHttpClient(); try {/*w w w. j a v a2 s .c om*/ Configuration config = new Configuration(IConstants.TEST_PROPERTIES); HttpPost post = new HttpPost(config.getConfigProperties().getProperty("test.url")); String testXmlPath = config.getConfigProperties().getProperty("test.xml.path"); assertNotNull(testXmlPath); logger.info("Working with xml: " + testXmlPath); InputStreamEntity entity = new InputStreamEntity(new FileInputStream(testXmlPath), -1); entity.setChunked(true); entity.setContentType("application/xml"); post.setEntity(entity); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { logger.info(line); assertEquals("Export complete", line); } } catch (IOException e) { logger.error(e.getMessage()); } }
From source file:com.ibm.stocator.fs.swift.SwiftOutputStream.java
/** * Default constructor// w ww. ja v a 2 s . c o m * * @param account JOSS account object * @param url URL connection * @param contentType content type * @param metadata input metadata * @param connectionManager SwiftConnectionManager * @throws IOException if error */ public SwiftOutputStream(JossAccount account, URL url, final String contentType, Map<String, String> metadata, SwiftConnectionManager connectionManager) throws IOException { mUrl = url; totalWritten = 0; mAccount = account; client = connectionManager.createHttpConnection(); request = new HttpPut(mUrl.toString()); request.addHeader("X-Auth-Token", account.getAuthToken()); if (metadata != null && !metadata.isEmpty()) { for (Map.Entry<String, String> entry : metadata.entrySet()) { request.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue()); } } PipedOutputStream out = new PipedOutputStream(); final PipedInputStream in = new PipedInputStream(); out.connect(in); execService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); mOutputStream = out; Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { InputStreamEntity entity = new InputStreamEntity(in, -1); entity.setChunked(true); entity.setContentType(contentType); request.setEntity(entity); LOG.debug("HTTP PUT request {}", mUrl.toString()); HttpResponse response = client.execute(request); int responseCode = response.getStatusLine().getStatusCode(); LOG.debug("HTTP PUT response {}. Response code {}", mUrl.toString(), responseCode); if (responseCode == 401) { // Unauthorized error mAccount.authenticate(); request.removeHeaders("X-Auth-Token"); request.addHeader("X-Auth-Token", mAccount.getAuthToken()); LOG.warn("Token recreated for {}. Retry request", mUrl.toString()); response = client.execute(request); responseCode = response.getStatusLine().getStatusCode(); } if (responseCode >= 400) { // Code may have changed from retrying throw new IOException("HTTP Error: " + responseCode + " Reason: " + response.getStatusLine().getReasonPhrase()); } return null; } }; futureTask = execService.submit(task); }
From source file:org.mahasen.thread.MahasenReplicateWorker.java
public void run() { HttpClient uploadHttpClient = new DefaultHttpClient(); uploadHttpClient = SSLWrapper.wrapClient(uploadHttpClient); if (file.exists()) { HttpPost httppost = new HttpPost(uri); try {/*from w w w .ja va 2s. com*/ InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httppost.setEntity(reqEntity); System.out.println("Executing Replicate request " + httppost.getRequestLine()); HttpResponse response = uploadHttpClient.execute(httppost); System.out.println("Replicate worker----------------------------------------"); System.out.println(response.getStatusLine()); if ((response.getStatusLine().getReasonPhrase().equals("OK")) && (response.getStatusLine().getStatusCode() == 200)) { log.debug(currentPart + " was replicated at " + nodeIp); //PutUtil.incrementNoOfReplicas(currentPart); mahasenResource.addSplitPartStoredIp(currentPart, nodeIp); try { nodeManager.insertIntoDHT(parentFileId, mahasenResource, true); } catch (InterruptedException e) { log.error("Interrupted while updating replicated file's metadata"); } catch (PastException e) { log.error( "Error while updating replicated file ID:" + mahasenResource.getId() + "medatada"); } } } catch (IOException e) { log.error("Error occurred in URL connection"); } } }
From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java
private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp) throws IOException { /* File tmp = null; FileOutputStream fos = null;/* w ww .j av a 2 s. co m*/ PostMethod post = null; //System.out.println(filename + " -> " + depositurl); */ try { /* tmp = File.createTempFile("fileupload", null); fos = new FileOutputStream(tmp); FileUtil.copy(is, fos); HttpClient client = new HttpClient(); post = new PostMethod(depositurl); Part[] parts = {new FilePart(filename, tmp)}; post.setRequestEntity(new MultipartRequestEntity(parts, post .getParams())); */ org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(depositurl); InputStreamEntity data = new InputStreamEntity(is, -1); data.setContentType("binary/octet-stream"); data.setChunked(false); post.setEntity(data); HttpResponse response = client.execute(post); System.out.println(response.toString()); int status = 202;//response.getStatusLine(); // int status = client.executeMethod(post); if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) { resp.setStatus(status); String src = response.getHeaders("X-dcs-src")[0].getValue(); String atomurl = response.getHeaders("Location")[0].getValue(); resp.setContentType("text/html"); resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>"); resp.flushBuffer(); } else { resp.sendError(status, response.getStatusLine().toString()); return; } } finally { /* if (tmp != null) { tmp.delete(); } if (is != null) { is.close(); } if (fos != null) { fos.close(); } if (post != null) { post.releaseConnection(); }*/ } }
From source file:org.bitrepository.protocol.http.HttpFileExchange.java
/** * Method for putting data on the HTTP-server of a given url. * /*ww w. j av a 2 s . com*/ * TODO perhaps make it synchronized around the URL, to prevent data from * trying to uploaded several times to the same location simultaneously. * * @param in The data to put into the url. * @param url The place to put the data. * @throws IOException If a problem with the connection occurs during the * transaction. Also if the response code is 300 or above, which indicates * that the transaction has not been successful. */ private void performUpload(InputStream in, URL url) throws IOException { HttpClient httpClient = null; try { httpClient = getHttpClient(); HttpPut httpPut = new HttpPut(url.toExternalForm()); InputStreamEntity reqEntity = new InputStreamEntity(in, -1); reqEntity.setChunked(true); httpPut.setEntity(reqEntity); HttpResponse response = httpClient.execute(httpPut); // HTTP code >= 300 means error! if (response.getStatusLine().getStatusCode() >= HTTP_ERROR_CODE_BARRIER) { throw new IOException("Could not upload file to URL '" + url.toExternalForm() + "'. got status code '" + response.getStatusLine() + "'"); } log.debug("Uploaded datastream to url '" + url.toString() + "' and " + "received the response line '" + response.getStatusLine() + "'."); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } }
From source file:org.fashiontec.bodyapps.sync.SyncPic.java
/** * Multipart put request for images.// ww w . j a v a 2 s.co m * @param url * @param path * @return */ public HttpResponse put(String url, String path) { HttpResponse response = null; try { File file = new File(path); HttpClient client = new DefaultHttpClient(); HttpPut post = new HttpPut(url); InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file.getPath()), file.length()); entity.setContentType("image/jpeg"); entity.setChunked(true); post.setEntity(entity); response = client.execute(post); } catch (IOException e) { e.printStackTrace(); } return response; }
From source file:org.fashiontec.bodyapps.sync.SyncPic.java
/** * Multipart post for images./*w w w . j a v a2 s . c o m*/ * @param url * @param path * @return */ public HttpResponse post(String url, String path) { HttpResponse response = null; try { File file = new File(path); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file.getPath()), file.length()); entity.setContentType("image/jpeg"); entity.setChunked(true); post.setEntity(entity); response = client.execute(post); } catch (IOException e) { e.printStackTrace(); } return response; }
From source file:org.mahasen.thread.MahasenUploadWorker.java
public void run() { HttpClient uploadHttpClient = new DefaultHttpClient(); uploadHttpClient = SSLWrapper.wrapClient(uploadHttpClient); if (file.exists()) { if (!nodeIp.equals(localIp)) { HttpPost httppost = new HttpPost(uri); try { InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httppost.setEntity(reqEntity); System.out.println("Executing Upload request " + httppost.getRequestLine()); HttpResponse response = uploadHttpClient.execute(httppost); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if ((response.getStatusLine().getReasonPhrase().equals("OK")) && (response.getStatusLine().getStatusCode() == 200)) { mahasenResource.addSplitPartStoredIp(currentPart, nodeIp); PutUtil.storedNoOfParts.get(jobId).getAndIncrement(); }/*from w w w.j av a 2 s .c o m*/ } catch (IOException e) { log.error("Error occurred in Uploading part : " + currentPart, e); } } else { try { FileInputStream inputStream = new FileInputStream(file); File filePart = new File( MahasenConfiguration.getInstance().getRepositoryPath() + file.getName()); FileOutputStream outputStream = new FileOutputStream(filePart); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); outputStream.close(); mahasenResource.addSplitPartStoredIp(currentPart, nodeIp); PutUtil.storedNoOfParts.get(jobId).getAndIncrement(); } catch (Exception e) { log.error("Error while storing file " + currentPart + " locally", e); } } } }
From source file:org.mahasen.client.Upload.java
/** * @param uploadFile/*from www. j a v a 2 s . co m*/ * @param tags * @param folderStructure * @param addedProperties * @throws IOException */ public void upload(File uploadFile, String tags, String folderStructure, List<NameValuePair> addedProperties) throws IOException, MahasenClientException, URISyntaxException { httpclient = new DefaultHttpClient(); if (addedProperties != null) { this.customProperties = addedProperties; } try { System.out.println(" Is Logged : " + clientLoginData.isLoggedIn()); if (clientLoginData.isLoggedIn() == true) { httpclient = WebClientSSLWrapper.wrapClient(httpclient); File file = uploadFile; if (file.exists()) { if (!folderStructure.equals("")) { customProperties.add(new BasicNameValuePair("folderStructure", folderStructure)); } customProperties.add(new BasicNameValuePair("fileName", file.getName())); customProperties.add(new BasicNameValuePair("tags", tags)); URI uri = URIUtils.createURI("https", clientLoginData.getHostNameAndPort(), -1, "/mahasen/upload_ajaxprocessor.jsp", URLEncodedUtils.format(customProperties, "UTF-8"), null); HttpPost httppost = new HttpPost(uri); InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httppost.setEntity(reqEntity); httppost.setHeader("testHeader", "testHeadervalue"); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(resEntity); if (response.getStatusLine().getStatusCode() == 900) { throw new MahasenClientException(String.valueOf(response.getStatusLine())); } } } else { System.out.println("User has to be logged in to perform this function"); } } finally { httpclient.getConnectionManager().shutdown(); } }