@Test public void test_1_UpdateItem_2_WithFile_Fetched() throws ImejiException, IOException { initCollection(); initItem(); final String fileURL = target().getUri() + STATIC_CONTEXT_PATH.substring(1) + "/test2.jpg"; FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.field( "json", getStringFromPath(UPDATE_ITEM_FILE_JSON) .replace("___FILE_NAME___", UPDATED_FILE_NAME) .replace("___FETCH_URL___", fileURL) .replaceAll("\"id\"\\s*:\\s*\"__ITEM_ID__\",", "") .replace("___REFERENCE_URL___", "")); Response response = target(PATH_PREFIX) .path("/" + itemId) .register(authAsUser) .register(MultiPartFeature.class) .register(JacksonFeature.class) .request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(multiPart, multiPart.getMediaType())); assertEquals(OK.getStatusCode(), response.getStatus()); DefaultItemTO itemWithFileTO = response.readEntity(DefaultItemTO.class); assertThat( "Checksum of stored file deos not match the source file", itemWithFileTO.getChecksumMd5(), equalTo(calculateChecksum(ATTACHED_FILE))); // LOGGER.info(RestProcessUtils.buildJSONFromObject(itemWithFileTO)); }
@Test public void test_1_UpdateItem_1_WithFile_Attached() throws IOException { FileDataBodyPart filePart = new FileDataBodyPart("file", ATTACHED_FILE); FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.bodyPart(filePart); multiPart.field( "json", getStringFromPath(UPDATE_ITEM_FILE_JSON) .replace("___FILE_NAME___", ATTACHED_FILE.getName()) .replace("___FETCH_URL___", "") .replaceAll("\"id\"\\s*:\\s*\"__ITEM_ID__\",", "") .replace("___REFERENCE_URL___", "")); Response response = target(PATH_PREFIX) .path("/" + itemId) .register(authAsUser) .register(MultiPartFeature.class) .register(JacksonFeature.class) .request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(multiPart, multiPart.getMediaType())); assertEquals(OK.getStatusCode(), response.getStatus()); DefaultItemTO itemWithFileTO = response.readEntity(DefaultItemTO.class); assertThat("Wrong file name", itemWithFileTO.getFilename(), equalTo(ATTACHED_FILE.getName())); storedFileURL = target().getUri() + itemWithFileTO.getFileUrl().getPath().substring(1); assertEquals(ATTACHED_FILE.length(), itemWithFileTO.getFileSize()); // LOGGER.info(RestProcessUtils.buildJSONFromObject(itemWithFileTO)); }
@Test public void test_2_UpdateItem_1_TypeDetection_JPG() throws IOException { FileDataBodyPart filePart = new FileDataBodyPart("file", ATTACHED_FILE); FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.bodyPart(filePart); multiPart.field( "json", getStringFromPath(UPDATE_ITEM_FILE_JSON) .replace("___FILE_NAME___", ATTACHED_FILE.getName()) .replace("___FETCH_URL___", "") .replaceAll("\"id\"\\s*:\\s*\"__ITEM_ID__\",", "") .replace("___REFERENCE_URL___", "")); Response response = target(PATH_PREFIX) .path("/" + itemId) .register(authAsUser) .register(MultiPartFeature.class) .register(JacksonFeature.class) .request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(multiPart, multiPart.getMediaType())); assertEquals(OK.getStatusCode(), response.getStatus()); DefaultItemTO itemWithFileTO = response.readEntity(DefaultItemTO.class); assertThat("Wrong file name", itemWithFileTO.getFilename(), equalTo(ATTACHED_FILE.getName())); }
public Response postSequenceFile( String url, String recordId, EntryType entryType, String sequence) { WebTarget target = client.target("https://" + url).path("/rest/file/sequence"); Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE); final FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.field("file", IOUtils.toInputStream(sequence), MediaType.TEXT_PLAIN_TYPE); multiPart.field("entryRecordId", recordId); multiPart.field("entryType", entryType.name()); return invocationBuilder.post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); }
@Test public void testPart() { final WebTarget target = target().path("form/part"); final FormDataMultiPart mp = new FormDataMultiPart(); final FormDataBodyPart p = new FormDataBodyPart(FormDataContentDisposition.name("part").build(), "CONTENT"); mp.bodyPart(p); final String s = target.request().post(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE), String.class); assertEquals("CONTENT", s); }
@Test public void test_1_UpdateItem_7_WithFile_Attached_Fetched_Referenced() throws IOException, ImejiException { initCollection(); initItem(); File newFile = new File(STATIC_CONTEXT_STORAGE + "/test1.jpg"); FileDataBodyPart filePart = new FileDataBodyPart("file", newFile); final String fileURL = target().getUri() + STATIC_CONTEXT_PATH.substring(1) + "/test1.jpg"; FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.bodyPart(filePart); multiPart.field( "json", getStringFromPath(UPDATE_ITEM_FILE_JSON) .replaceAll("\"id\"\\s*:\\s*\"__ITEM_ID__\",", "") .replace("___FILE_NAME___", newFile.getName()) .replace("___FETCH_URL___", fileURL) .replace("___REFERENCE_URL___", storedFileURL)); Response response = target(PATH_PREFIX) .path("/" + itemId) .register(authAsUser) .register(MultiPartFeature.class) .register(JacksonFeature.class) .request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(multiPart, multiPart.getMediaType())); assertEquals(OK.getStatusCode(), response.getStatus()); DefaultItemTO itemWithFileTO = response.readEntity(DefaultItemTO.class); assertThat( "Checksum of stored file does not match the source file", itemWithFileTO.getChecksumMd5(), equalTo(calculateChecksum(newFile))); assertThat(itemWithFileTO.getFileUrl().toString(), not(equalTo(fileURL))); assertThat(itemWithFileTO.getFileUrl().toString(), not(equalTo(storedFileURL))); assertThat( itemWithFileTO.getThumbnailUrl().toString(), not(containsString(ItemController.NO_THUMBNAIL_URL))); assertThat( itemWithFileTO.getWebResolutionUrlUrl().toString(), not(containsString(ItemController.NO_THUMBNAIL_URL))); }
/** * Sets the connection params. * * @param key the key * @param value the value * @return the API result */ public APIResult setConnectionParams(String key, String value) { WebTarget target = getSessionWebTarget(); FormDataMultiPart mp = new FormDataMultiPart(); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("sessionid").build(), this.sessionHandle, MediaType.APPLICATION_XML_TYPE)); mp.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("key").build(), key)); mp.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("value").build(), value)); LOG.debug("Setting connection params " + key + "=" + value); APIResult result = target .path("params") .request() .put(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE), APIResult.class); return result; }
/** * Removes the resource from connection. * * @param type the type * @param resourcePath the resource path * @return the API result */ public APIResult removeResourceFromConnection(String type, String resourcePath) { WebTarget target = getSessionWebTarget(); FormDataMultiPart mp = new FormDataMultiPart(); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("sessionid").build(), this.sessionHandle, MediaType.APPLICATION_XML_TYPE)); mp.bodyPart(new FormDataBodyPart(FormDataContentDisposition.name("type").build(), type)); mp.bodyPart( new FormDataBodyPart(FormDataContentDisposition.name("path").build(), resourcePath)); APIResult result = target .path("resources/delete") .request() .put(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE), APIResult.class); return result; }
@Test public void testXmlJAXBPart() { final WebTarget target = target().path("form/xml-jaxb-part"); final FormDataMultiPart mp = new FormDataMultiPart(); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("bean").fileName("bean").build(), new Bean("BEAN"), MediaType.APPLICATION_XML_TYPE)); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("string").fileName("string").build(), "STRING")); final String s = target.request().post(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE), String.class); assertEquals("STRING:string,BEAN:bean", s); }
/** * Open. * * @param password the password * @return the lens session handle */ public LensSessionHandle open(String password) { WebTarget target = getSessionWebTarget(); FormDataMultiPart mp = new FormDataMultiPart(); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("username").build(), params.getUser())); mp.bodyPart( new FormDataBodyPart(FormDataContentDisposition.name("password").build(), password)); String database = params.getDbName(); mp.bodyPart( new FormDataBodyPart(FormDataContentDisposition.name("database").build(), database)); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("sessionconf").fileName("sessionconf").build(), params.getSessionConf(), MediaType.APPLICATION_XML_TYPE)); try { Response response = target.request().post(Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() != 200) { throw new LensClientServerConnectionException(response.getStatus()); } final LensSessionHandle handle = response.readEntity(LensSessionHandle.class); if (handle != null) { sessionHandle = handle; LOG.debug("Created a new session " + sessionHandle.getPublicId()); } else { throw new IllegalStateException( "Unable to connect to lens " + "server with following paramters" + params); } } catch (ProcessingException e) { if (e.getCause() != null && e.getCause() instanceof ConnectException) { throw new LensClientServerConnectionException(e.getCause().getMessage(), e); } } LOG.debug("Successfully switched to database " + params.getDbName()); open.set(true); return sessionHandle; }
public String uploadImage(Part file) throws IOException { String imageURL = null; final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); final StreamDataBodyPart stream = new StreamDataBodyPart("file", file.getInputStream()); FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); final MultiPart multiPart = formDataMultiPart.field("fileName", file.getSubmittedFileName()).bodyPart(stream); if (multiPart instanceof FormDataMultiPart) { final FormDataMultiPart dataMultiPart = (FormDataMultiPart) multiPart; final WebTarget target = client.target(configuration.getFileUploadServiceEP()); LOGGER.info("Connecting to file service on " + configuration.getFileUploadServiceEP()); final Response response = target .request() .header(LoginBean.X_JWT_ASSERTION, getJWTToken()) .post(Entity.entity(dataMultiPart, dataMultiPart.getMediaType())); LOGGER.info("Returned from file service " + configuration.getFileUploadServiceEP()); if (Response.Status.OK.getStatusCode() == response.getStatus()) { imageURL = response.readEntity(String.class); } else { LOGGER.log( Level.SEVERE, "TXN service return code is " + response.getStatus() + " , " + "hence can't proceed with the response"); } formDataMultiPart.close(); dataMultiPart.close(); return imageURL; } return imageURL; }
@Test public void test_1_UpdateItem_9_FetchURL_NoFile() throws IOException { FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.field( "json", getStringFromPath(UPDATE_ITEM_FILE_JSON) .replaceAll("\"id\"\\s*:\\s*\"__ITEM_ID__\",", "") .replace("___FETCH_URL___", "www.google.de")); Response response = target(PATH_PREFIX) .path("/" + itemId) .register(authAsUser) .register(MultiPartFeature.class) .register(JacksonFeature.class) .request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(multiPart, multiPart.getMediaType())); assertEquals(HttpStatus.SC_UNPROCESSABLE_ENTITY, response.getStatus()); }
@Test public void test_1_UpdateItem_3_WithFile_Referenced() throws IOException { FormDataMultiPart multiPart = new FormDataMultiPart(); multiPart.field( "json", getStringFromPath(UPDATE_ITEM_FILE_JSON) .replace("___FILE_NAME___", UPDATED_FILE_NAME) .replace("___FETCH_URL___", "") .replaceAll("\"id\"\\s*:\\s*\"__ITEM_ID__\",", "") .replace("___REFERENCE_URL___", storedFileURL)); Response response = target(PATH_PREFIX) .path("/" + itemId) .register(authAsUser) .register(MultiPartFeature.class) .register(JacksonFeature.class) .request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(multiPart, multiPart.getMediaType())); assertEquals(OK.getStatusCode(), response.getStatus()); DefaultItemTO itemWithFileTO = response.readEntity(DefaultItemTO.class); assertThat( "Reference URL does not match", storedFileURL, equalTo(itemWithFileTO.getFileUrl().toString())); assertThat( "Should be link to NO_THUMBNAIL image:", itemWithFileTO.getWebResolutionUrlUrl().toString(), endsWith(ItemController.NO_THUMBNAIL_URL)); assertThat( "Should be link to NO_THUMBNAIL image:", itemWithFileTO.getThumbnailUrl().toString(), endsWith(ItemController.NO_THUMBNAIL_URL)); }
/** * uploads zip file using the input HTTP URL * * @param httpURL * @param filePath * @param filename * @return * @throws Exception */ public static String testUploadService(String httpURL, File filePath) throws Exception { // local variables ClientConfig clientConfig = null; Client client = null; WebTarget webTarget = null; Invocation.Builder invocationBuilder = null; Response response = null; FileDataBodyPart fileDataBodyPart = null; FormDataMultiPart formDataMultiPart = null; int responseCode; String responseMessageFromServer = null; String responseString = null; try { // invoke service after setting necessary parameters clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); client = ClientBuilder.newClient(clientConfig); webTarget = client.target(httpURL); // set file upload values fileDataBodyPart = new FileDataBodyPart("uploadFile", filePath, MediaType.APPLICATION_OCTET_STREAM_TYPE); formDataMultiPart = new FormDataMultiPart(); formDataMultiPart.bodyPart(fileDataBodyPart); StreamDataBodyPart bodyPart = new StreamDataBodyPart(); // invoke service invocationBuilder = webTarget.request(); // invocationBuilder.header("Authorization", "Basic " + authorization); response = invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA)); // get response code responseCode = response.getStatus(); System.out.println("Response code: " + responseCode); if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + responseCode); } // get response message responseMessageFromServer = response.getStatusInfo().getReasonPhrase(); System.out.println("ResponseMessageFromServer: " + responseMessageFromServer); // get response string responseString = response.readEntity(String.class); } catch (Exception ex) { ex.printStackTrace(); } finally { // release resources, if any fileDataBodyPart.cleanup(); formDataMultiPart.cleanup(); formDataMultiPart.close(); response.close(); client.close(); } return responseString; }
/** * Test result formatter. * * @param conf the conf * @param status the status * @param isDir the is dir * @param reDirectUrl the re direct url * @throws InterruptedException the interrupted exception * @throws IOException Signals that an I/O exception has occurred. */ private void testResultFormatter(LensConf conf, Status status, boolean isDir, String reDirectUrl) throws InterruptedException, IOException { // test post execute op final WebTarget target = target().path("queryapi/queries"); final FormDataMultiPart mp = new FormDataMultiPart(); conf.addProperty(LensConfConstants.QUERY_PERSISTENT_RESULT_SET, "true"); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("sessionid").build(), lensSessionId, MediaType.APPLICATION_XML_TYPE)); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("query").build(), "select ID, IDSTR, IDARR, IDSTRARR from " + testTable)); mp.bodyPart( new FormDataBodyPart(FormDataContentDisposition.name("operation").build(), "execute")); mp.bodyPart( new FormDataBodyPart( FormDataContentDisposition.name("conf").fileName("conf").build(), conf, MediaType.APPLICATION_XML_TYPE)); QueryHandle handle = target .request() .post( Entity.entity(mp, MediaType.MULTIPART_FORM_DATA_TYPE), new GenericType<LensAPIResult<QueryHandle>>() {}) .getData(); Assert.assertNotNull(handle); // Get query LensQuery ctx = target .path(handle.toString()) .queryParam("sessionid", lensSessionId) .request() .get(LensQuery.class); // wait till the query finishes QueryStatus stat = ctx.getStatus(); while (!stat.finished()) { ctx = target .path(handle.toString()) .queryParam("sessionid", lensSessionId) .request() .get(LensQuery.class); stat = ctx.getStatus(); Thread.sleep(1000); } Assert.assertEquals(ctx.getStatus().getStatus(), status); if (status.equals(QueryStatus.Status.SUCCESSFUL)) { QueryContext qctx = queryService.getQueryContext(handle); if (qctx == null) { // This shouldn't occur. It is appearing when query gets purged. So adding extra logs // for debugging in the future. log.info("successful query's QueryContext is null"); log.info("query handle: {}", handle); log.info("allQueries: {}", queryService.allQueries); // not doing formatter validation if qctx is null } else if (!isDir) { // isDir is true if the formatter is skipped due to result being the max size allowed if (qctx.isDriverPersistent()) { Assert.assertTrue(qctx.getQueryOutputFormatter() instanceof PersistedOutputFormatter); } else { Assert.assertTrue(qctx.getQueryOutputFormatter() instanceof InMemoryOutputFormatter); } } else { Assert.assertNull(qctx.getQueryOutputFormatter()); } // fetch results TestQueryService.validatePersistedResult( handle, target(), lensSessionId, new String[][] { {"ID", "INT"}, {"IDSTR", "STRING"}, {"IDARR", "ARRAY"}, {"IDSTRARR", "ARRAY"}, }, isDir); if (!isDir) { TestQueryService.validateHttpEndPoint(target(), lensSessionId, handle, reDirectUrl); } } else { assertTrue(ctx.getSubmissionTime() > 0); assertTrue(ctx.getLaunchTime() > 0); assertTrue(ctx.getDriverStartTime() > 0); assertTrue(ctx.getDriverFinishTime() > 0); assertTrue(ctx.getFinishTime() > 0); Assert.assertEquals(ctx.getStatus().getStatus(), QueryStatus.Status.FAILED); } }