@Test public void should_download() throws Exception { CloseableHttpResponse tokenResponse = mock(CloseableHttpResponse.class); when(tokenResponse.getEntity()).thenReturn(new StringEntity("validToken","UTF-8")); CloseableHttpResponse fileResponse = mock(CloseableHttpResponse.class); when(fileResponse.getEntity()).thenReturn(new FileEntity(new File(getClass().getResource("/tomtom/download/test.metalink").toURI()))); when(client.execute(any(HttpPost.class))).thenReturn(tokenResponse, fileResponse); Metalink download = metalinkDownloader.download(); assertThat(download.getUrls()).isEqualTo(newArrayList( new MetalinkParser.MetalinkUrl("test-shpd-mn-and-and.7z.001", "test", "and", "d", "mn", "and", "http://test.com/and.7z.001"), new MetalinkParser.MetalinkUrl("test-shpd-mn-and-ax.7z.001", "test", "and", "d", "mn", "ax", "http://test.com/ax.7z.001") )); }
protected void upload(final UploadPluginExtension ext, final File artifact) throws ClientProtocolException, IOException { final HttpEntity entity = new FileEntity(artifact); final StringBuilder url = new StringBuilder(); url.append(ext.getUrl()).append('/').append(ext.getRepository()).append('/').append(ext.getFolder()).append('/').append(artifact.getName()); logger.debug("Uploading {} to {}", artifact.getName(), url.toString()); credentialsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(ext.getUsername(), ext.getPassword())); final HttpPut request = new HttpPut(url.toString()); request.setEntity(entity); final HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != 201) { EntityUtils.consume(response.getEntity()); throw new GradleException("Unable to upload artifact. Response from artifactory was " + response.getStatusLine()); } EntityUtils.consume(response.getEntity()); logger.debug("Uploaded {} successfully!", artifact.getName()); }
public void canCreateInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_CREATED, "Created"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/created.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); Instance instance = new Instance() .setName("some_name") .setPackageId(new UUID(12L, 24L)) .setImage(new UUID(8L, 16L)) .setTags(Collections.singletonMap(TEST_TAG_KEY, TEST_TAG)); try (CloudApiConnectionContext context = createMockContext(response)) { final Instance created = instanceApi.create(context, instance); assertNotNull(created); assertNotNull(created.getId()); } }
public void errorsCorrectlyWhenDeletingUnknownInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Not Found"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/error/not_found.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); boolean thrown = false; try (CloudApiConnectionContext context = createMockContext(response)) { UUID instanceId = new UUID(512L, 1024L); instanceApi.delete(context, instanceId); } catch (CloudApiResponseException e) { thrown = true; assertTrue(e.getMessage().contains("VM not found"), "Unexpected message on exception"); } assertTrue(thrown, "CloudApiResponseException never thrown"); }
public void canWaitForStateChangeWhenItAlreadyChanged() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/domain/instance.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); final String stateToChangeFrom = "provisioning"; try (CloudApiConnectionContext context = createMockContext(response)) { final Instance running = instanceApi.waitForStateChange( context, instanceId, stateToChangeFrom, 0L, 0L); assertEquals(running.getId(), instanceId, "ids should match"); assertNotEquals(running.getState(), stateToChangeFrom, "shouldn't be in [" + stateToChangeFrom + "] state"); assertEquals(running.getState(), "running", "should be in running state"); } }
public void canFindRunningInstanceById() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/domain/instance.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); try (CloudApiConnectionContext context = createMockContext(response)) { Instance found = instanceApi.findById(context, instanceId); assertNotNull(found, "expecting instance to be found"); assertEquals(found.getId(), instanceId, "expecting ids to match"); } }
public void canAddAdditionalTagsToAnInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/additional_tags.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); try (CloudApiConnectionContext context = createMockContext(response)) { Map<String, String> tags = instanceApi.addTags(context, instanceId, ImmutableMap.of("additional_1", "val1", "additional_2", "val2")); assertEquals(tags.size(), 3, "Expecting 3 tags"); assertEquals(tags.get("name"), "value"); assertEquals(tags.get("additional_1"), "val1"); assertEquals(tags.get("additional_2"), "val2"); } }
public void canReplaceTagsOnAnInstance() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/replace_tags.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); final UUID instanceId = UUID.fromString("c872d3bf-cbaa-4165-8e18-f6e3e1d94da9"); try (CloudApiConnectionContext context = createMockContext(response)) { Map<String, String> tags = instanceApi.replaceTags(context, instanceId, ImmutableMap.of("additional_1", "val1", "additional_2", "val2")); assertEquals(tags.size(), 2, "Expecting 2 tags"); assertEquals(tags.get("additional_1"), "val1"); assertEquals(tags.get("additional_2"), "val2"); } }
public void canFindTheSmallestMemoryPackages() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/packages/packages.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); try (CloudApiConnectionContext context = createMockContext(response)) { Collection<Package> packages = packagesApi.smallestMemory(context); assertFalse(packages.isEmpty(), "This should not be an empty collection"); assertEquals(packages.size(), 1); final Package pkg = packages.iterator().next(); assertEquals(pkg.getName(), "t4-standard-128M", "Package name is unexpected. Actual package:\n" + pkg); } }
/** * Constructs octet-stream entity based upon the specified value or the file and its mimetype (ie. request * parameter). * * @param requestParam * request parameter * @return request octet-stream entity for the service */ private static HttpEntity constructOctetStreamEntity(ExecutionBodyParam requestParam) { if (requestParam == null) { return null; } if (requestParam.getValue() != null) { return new StringEntity(requestParam.getValue(), TEXTPLAIN); } if (requestParam.getFileValue() != null) { try { ContentType contentType = ContentType.create(requestParam.getFileValue().getMimetype()); return new FileEntity(requestParam.getFileValue().getFile(), contentType); } catch (IllegalArgumentException e) { return new FileEntity(requestParam.getFileValue().getFile()); } } return null; }
public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String target = request.getRequestLine().getUri(); final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8")); HttpCoreContext coreContext = HttpCoreContext.adapt(context); HttpConnection conn = coreContext.getConnection(HttpConnection.class); response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null)); response.setEntity(body); System.out.println(conn + ": serving file " + file.getPath()); new Thread() { @Override public void run() { System.out.println("Stopping HTTP Server..."); server.stop(); } }.start(); }
private void uploadConfiguration() throws IOException { System.out.print(ImplMessages.getMessage("PROVISIONER_UPLOADING_CONFIG_MSG")); // String url = "https://"+hostname+":"+6143+"/geoevent/admin/configuration/install/.json"; String url = "https://" + hostName + ":" + 6143 + "/geoevent/admin/configuration/.json"; File configAsFile = new File(configFile); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(getSSLSocketFactory()).build(); FileEntity file = new FileEntity(configAsFile, ContentType.APPLICATION_XML); HttpUriRequest post = RequestBuilder.put().setUri(url).addHeader("GeoEventAuthorization", token).addHeader("referer", referer).setEntity(file).build(); HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); ObjectMapper mapper = new ObjectMapper(); @SuppressWarnings("unused") JsonNode jsonResponse = mapper.readTree(entity.getContent()); sleep(10 * 1000); System.out.println(ImplMessages.getMessage("DONE")); }
@Override public void upload(final File src, final URL dest, final CopyProgressListener listener, final TimeoutConstraint timeoutConstraint) throws IOException { final int connectionTimeout = (timeoutConstraint == null || timeoutConstraint.getConnectionTimeout() < 0) ? 0 : timeoutConstraint.getConnectionTimeout(); final int readTimeout = (timeoutConstraint == null || timeoutConstraint.getReadTimeout() < 0) ? 0 : timeoutConstraint.getReadTimeout(); final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout) .setConnectTimeout(connectionTimeout) .setAuthenticationEnabled(hasCredentialsConfigured(dest)) .setTargetPreferredAuthSchemes(getAuthSchemePreferredOrder()) .setProxyPreferredAuthSchemes(getAuthSchemePreferredOrder()) .setExpectContinueEnabled(true) .build(); final HttpPut put = new HttpPut(normalizeToString(dest)); put.setConfig(requestConfig); put.setEntity(new FileEntity(src)); try (final CloseableHttpResponse response = this.httpClient.execute(put)) { validatePutStatusCode(dest, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } }
public String setJobState(String uri, String jobState) throws IOException { File templateFile = new File(jobStateTemplate); String job_id = uri.substring(uri.lastIndexOf("/"), uri.length()); File outputFile = new File(basedir + "/result/" + job_id + "_JobState.xml"); Template t = new Template(templateFile); t.setValue("state", jobState); t.export(new FileOutputStream(outputFile)); FileEntity entity = new FileEntity(outputFile, ContentType.create("text/xml", "UTF-8")); HttpResponseObj resp = null; try { App.logInfo("Settting Job State URL: " + uri); Header h = new Header(); h.addHeader("X-SFDC-Session", session_id); h.addHeader("Content-Type", "text/csv"); resp = wa.doPost(uri, h.getAllHeaders(), entity); } catch (Exception e) { e.printStackTrace(); } App.logInfo("Job State Response:\n" + resp.getContent()); printSFJobInformation(resp.getContent()); String status = parseXMLResponse(resp.getContent(), "state"); App.logInfo("Job Status: " + status); return status; }
private CloseableHttpResponse submitUploadText() throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://localhost/upload.txt"); File file = new File("x.txt"); FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8")); httppost.setEntity(entity); CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); } finally { response.close(); } return response; }
private PostThread[] submitMultiThreadRequest(int threadNo) throws IllegalStateException, IOException, InterruptedException { // create a thread for each URI PostThread[] threads = new PostThread[threadNo]; for (int i = 0; i < threads.length; i++) { HttpPost httppost = new HttpPost("http://localhost/upload"+i+".jpg"); File file = new File("img.jpg"); FileEntity entity = new FileEntity(file, ContentType.create("image/jpg", "UTF-8")); httppost.setEntity(entity); threads[i] = new PostThread(httpclient, httppost); } // start the threads for (int j = 0; j < threads.length; j++) { threads[j].start(); } // join the threads for (int j = 0; j < threads.length; j++) { threads[j].join(); } return threads; }
/** * <p>Test for a {@link Request} with a {@link File} entity.</p> * * @since 1.3.0 */ @Test public final void testFileEntity() throws ParseException, IOException, URISyntaxException { String subpath = "/fileentity"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File file = new File(classLoader.getResource("LICENSE.txt").toURI()); FileEntity fe = new FileEntity(file); stubFor(put(urlEqualTo(subpath)) .willReturn(aResponse() .withStatus(200))); requestEndpoint.fileEntity(file); verify(putRequestedFor(urlEqualTo(subpath)) .withRequestBody(equalTo(EntityUtils.toString(fe)))); }
@Test public void testUploadEmpty() throws Exception { assertThat(testDirectory.exists()).isTrue(); assertThat(testDirectory.isDirectory()).isTrue(); assertThat(testDirectory.list()).isEmpty(); File zipFile = new File(this.getClass().getClassLoader().getResource("zip1.zip").getPath()); FileEntity fileEntity = new FileEntity(zipFile); HttpResponse response = put(ZIP_UPLOAD_PATH).addHeader(Headers.CONTENT_TYPE, MediaType.ZIP.toString()) .addHeader("Accept", MediaType.ZIP.toString()) .setEntity(fileEntity) .execute(); checkFileExists("foo.txt"); checkDirectory("bar", 2); checkFileExists("bar/baz.json"); checkDirectory("bar/bat", 1); checkFileExists("bar/bat/hello.html"); }
/** * <p>Test for a {@link Request} with a {@link File} entity.</p> * * @since 1.3.0 */ @Test public final void testFileEntity() throws ParseException, IOException, URISyntaxException { Robolectric.getFakeHttpLayer().interceptHttpRequests(false); String subpath = "/fileentity"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File file = new File(classLoader.getResource("LICENSE.txt").toURI()); FileEntity fe = new FileEntity(file, null); stubFor(put(urlEqualTo(subpath)) .willReturn(aResponse() .withStatus(200))); requestEndpoint.fileEntity(file); verify(putRequestedFor(urlEqualTo(subpath)) .withRequestBody(equalTo(EntityUtils.toString(fe)))); }
public MethodBuilder withFile(File file, ContentType mimeType) { if (file != null) { FileEntity fileEntity = new FileEntity(file, mimeType); if (request instanceof HttpEntityEnclosingRequest) { ((HttpEntityEnclosingRequest) request).setEntity(fileEntity); } else { throw new MethodBuildException("Can only File to Post or Put methods."); } } return this; }
@Override protected HttpEntity getEntity(String path, Map<String, String> query, File localFile) throws IOException { String extension = FileHelper.getExtension(path); ContentType contentType = ContentType.create(getContentType(extension.toLowerCase())); return new FileEntity(localFile, contentType); }
@Override public void setPostEntity(File file, HttpPost httppost) { httppost.setHeader("Content-Type", "application/octet-stream"); httppost.setHeader("Slug", file.getName()); HttpEntity e = new FileEntity(file, ContentType.create(MIME.getType(file))); httppost.setEntity(e); }
public void canHandleRestErrors() throws IOException { CloudApiResponseHandler<Map<String, Header>> handler = new CloudApiResponseHandler<>( "error test", mapper, new TypeReference<Map<String, Header>>() {}, SC_OK, true ); StatusLine statusLine = new BasicStatusLine(HTTP_1_1, SC_BAD_REQUEST, "Bad Request"); HttpResponse response = new BasicHttpResponse(statusLine); response.setHeader(CloudApiHttpHeaders.REQUEST_ID, new UUID(0L, 0L).toString()); final File file = new File("src/test/data/error/bad_request.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); boolean thrown = false; try { handler.handleResponse(response); } catch (CloudApiResponseException e) { if (!e.getMessage().contains("requestID=00000000-0000-0000-0000-000000000000")) { fail("Request id not logged as part of error. Actual:\n" + e.getMessage()); } thrown = true; } assertTrue(thrown, "Expected CloudApiResponseException to be thrown"); }
public void wontCreateInstanceWithoutPackage() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_CREATED, "Created"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/created.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); Instance instance = new Instance() .setName("some_name") .setImage(new UUID(8L, 16L)) .setTags(Collections.singletonMap(TEST_TAG_KEY, TEST_TAG)); boolean thrown = false; try (CloudApiConnectionContext context = createMockContext(response)) { final Instance created = instanceApi.create(context, instance); assertNotNull(created); } catch (NullPointerException e) { if (e.getMessage().equals("Package id must be present")) { thrown = true; } else { fail("Unexpected NPE message: " + e.getMessage()); } } assertTrue(thrown, "Expected exception was never thrown"); }
public void wontCreateInstanceWithoutImage() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_CREATED, "Created"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/instances/created.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); Instance instance = new Instance() .setName("some_name") .setPackageId(new UUID(12L, 24L)) .setTags(Collections.singletonMap(TEST_TAG_KEY, TEST_TAG)); boolean thrown = false; try (CloudApiConnectionContext context = createMockContext(response)) { final Instance created = instanceApi.create(context, instance); assertNull(created); } catch (NullPointerException e) { if (e.getMessage().equals("Image id must be present")) { thrown = true; } else { fail("Unexpected NPE message: " + e.getMessage()); } } assertTrue(thrown, "Expected exception was never thrown"); }
public void canListWithInstancesUnderQueryLimit() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response1 = new BasicHttpResponse(statusLine); response1.setHeader(CloudApiHttpHeaders.X_RESOURCE_COUNT, "2"); response1.setHeader(CloudApiHttpHeaders.X_QUERY_LIMIT, "1000"); final HttpResponse response2 = new BasicHttpResponse(statusLine); response2.setHeader(CloudApiHttpHeaders.X_RESOURCE_COUNT, "2"); response2.setHeader(CloudApiHttpHeaders.X_QUERY_LIMIT, "1000"); final File file = new File("src/test/data/instances/list_under_limit.json"); final HttpEntity entity = new FileEntity(file); response2.setEntity(entity); final Queue<HttpResponse> responses = new LinkedList<>( ImmutableList.of(response1, response2) ); try (CloudApiConnectionContext context = createMockContext(responses)) { Iterator<Instance> itr = instanceApi.list(context); assertTrue(itr.hasNext(), "This shouldn't be an empty iterator"); assertNotNull(itr.next()); assertNotNull(itr.next()); assertFalse(itr.hasNext(), "This should be the end of the iterator"); } }
public void canListPackages() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/packages/packages.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); try (CloudApiConnectionContext context = createMockContext(response)) { Collection<Package> packages = packagesApi.list(context); assertFalse(packages.isEmpty(), "This should not be an empty collection"); assertEquals(packages.size(), 70, "Expected 70 package types"); } }
public void canGetPackageById() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/domain/package.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); try (CloudApiConnectionContext context = createMockContext(response)) { Package pkg = packagesApi.findById(context, new UUID(1, 1)); assertNotNull(pkg); } }
public void canListImages() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/images/list_images.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); try (CloudApiConnectionContext context = createMockContext(response)) { Collection<Image> images = imagesApi.list(context); assertFalse(images.isEmpty(), "This should not be an empty collection"); assertEquals(images.size(), 405, "Expected 405 images"); } }
public void canGetImageById() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/domain/image.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); try (CloudApiConnectionContext context = createMockContext(response)) { Image pkg = imagesApi.findById(context, new UUID(1, 1)); assertNotNull(pkg); } }
public void canListOnlyTheLatestImages() throws IOException { final StatusLine statusLine = new BasicStatusLine(HTTP_1_1, HttpStatus.SC_OK, "OK"); final HttpResponse response = new BasicHttpResponse(statusLine); final File file = new File("src/test/data/images/list_images.json"); final HttpEntity entity = new FileEntity(file); response.setEntity(entity); try (CloudApiConnectionContext context = createMockContext(response)) { Collection<Image> images = imagesApi.listLatestVersions(context); assertFalse(images.isEmpty(), "This should not be an empty collection"); assertEquals(images.size(), 26, "Expected 405 images"); } }
/** * Upload the archive to Flurry * * @param file the archive to send * @param projectId the project's id * @param uploadId the the upload's id * @param token the Flurry auth token */ private static void sendToUploadService(File file, String projectId, String uploadId, String token) { String uploadServiceUrl = String.format("%s/upload/%s/%s", UPLOAD_BASE, projectId, uploadId); List<Header> requestHeaders = getUploadServiceHeaders(file.length(), token); HttpPost postRequest = new HttpPost(uploadServiceUrl); postRequest.setEntity(new FileEntity(file)); HttpResponse response = executeHttpRequest(postRequest, requestHeaders); expectStatus(response, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED); }
public void uploadVersion(Version version, int id) throws ZipException, IOException { HttpPost post = new HttpPost(url + "ai/" + id + "/upload_zip"); File file = new File(System.getProperty("java.io.tmpdir"), version.ai.title + "v" + version.number + System.currentTimeMillis() + ".zip"); ZipFile zip = new ZipFile(file); ZipParameters params = new ZipParameters(); params.setIncludeRootFolder(false); zip.createZipFileFromFolder(new File(Paths.versionSrc(version)), params, false, -1); FileEntity entity = new FileEntity(file); post.setEntity(entity); HttpResponse response = http.execute(post); byte[] output = getOutput(response.getEntity().getContent()); if (output == null) { throw new IOException("Konnte nicht zum Server verbinden"); } if (response.getStatusLine().getStatusCode() != 200) { if (response.getFirstHeader("Content-Type").getValue().contains("json")) { JSONObject json = new JSONObject(new String(output, UTF_8)); String error = json.getString("error"); throw new IllegalStateException(error); } else throw new IllegalStateException("Irgendetwas ist beim Hochladen schief gelaufen."); } File image = ((AiSimple) version.ai).getPictureFile(); changeImage(image, id); }
protected CloseableHttpResponse upload ( final URIBuilder uri, final File file ) throws IOException, URISyntaxException { final HttpPut http = new HttpPut ( uri.build () ); final String encodedAuth = Base64.getEncoder ().encodeToString ( uri.getUserInfo ().getBytes ( StandardCharsets.ISO_8859_1 ) ); http.setHeader ( HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth ); http.setEntity ( new FileEntity ( file ) ); return httpclient.execute ( http ); }
protected CloseableHttpResponse upload ( final URIBuilder uri, final File file ) throws IOException, URISyntaxException { final HttpPut httppost = new HttpPut ( uri.build () ); httppost.setEntity ( new FileEntity ( file ) ); return httpclient.execute ( httppost ); }
public static boolean putFileToServerFromLocal(String url, File fileManager, String fileType) { try { url = url.replaceAll(" ", "%20"); // if (ExoConnectionUtils.getResponseCode(url) != 1) { // if (!ExoConnectionUtils.onReLogin()) { // return false; // } // } HttpPut put = new HttpPut(url); FileEntity fileEntity = new FileEntity(fileManager, fileType); put.setEntity(fileEntity); fileEntity.setContentType(fileType); HttpResponse response = ExoConnectionUtils.httpClient.execute(put); int status = response.getStatusLine().getStatusCode(); if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) { return true; } else { return false; } } catch (IOException e) { return false; } finally { fileManager.delete(); } }
/** * * @throws IOException * if the test file cannot be found */ @Before public final void setUp() throws IOException { getResourceClient.setHttpClient(httpClient); httpResponse.setEntity(new FileEntity(content.getFile(), "application/zip")); }
/** * PUT request, with file request and JSON response * @param url URL to make request to * @param source Path to read for uploaded file * @param headers Extra headers to add. Even-numbered elements will be treated as header names, and odd-numbered elements will be treated as header values. * @return String array of length 2. Element 0 is the response status code. Element 1 is the response body * @throws java.io.IOException * @throws java.security.GeneralSecurityException * "application/octet-stream" is the Content-Type of the request. */ public static String[] filePut(String url, File source, String... headers) throws IOException, GeneralSecurityException { try (CloseableHttpClient client = getClient()) { HttpPut request = new HttpPut(url); // Set request body FileEntity requestEntity = new FileEntity(source, ContentType.APPLICATION_OCTET_STREAM); request.setEntity(requestEntity); // Set request headers request.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); if(headers != null) { for(int i = 0; i < headers.length; i+=2) { request.setHeader(headers[i], headers[i+1]); } } // Execute the request try (CloseableHttpResponse response = client.execute(request)) { // Parse the response int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String responseBody = ""; if (entity != null) responseBody = EntityUtils.toString(entity); // Package it up for MATLAB. String[] returnVal = {Integer.toString(statusCode), responseBody}; return returnVal; } } }
/** * * @throws IOException * if the test file cannot be found */ @Before public final void setUp() throws IOException { getResourceClient.setHttpClient(httpClient); httpResponse.setEntity(new FileEntity(content.getFile(), ContentType.create("application/zip"))); }