Java Code Examples for org.apache.commons.io.IOUtils#toByteArray()

The following examples show how to use org.apache.commons.io.IOUtils#toByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BomResource.java    From dependency-track with Apache License 2.0 7 votes vote down vote up
/**
 * Common logic that processes a BOM given a project and list of multi-party form objects containing decoded payloads.
 */
private Response process(Project project, List<FormDataBodyPart> artifactParts) {
    for (final FormDataBodyPart artifactPart: artifactParts) {
        final BodyPartEntity bodyPartEntity = (BodyPartEntity) artifactPart.getEntity();
        if (project != null) {
            try (InputStream in = bodyPartEntity.getInputStream()) {
                final byte[] content = IOUtils.toByteArray(in);
                // todo: make option to combine all the bom data so components are reconciled in a single pass.
                // todo: https://github.com/DependencyTrack/dependency-track/issues/130
                final BomUploadEvent bomUploadEvent = new BomUploadEvent(project.getUuid(), content);
                Event.dispatch(bomUploadEvent);
                return Response.ok(Collections.singletonMap("token", bomUploadEvent.getChainIdentifier())).build();
            } catch (IOException e) {
                return Response.status(Response.Status.BAD_REQUEST).build();
            }
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
        }
    }
    return Response.ok().build();
}
 
Example 2
Source File: JettyWebappTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testAdminUI() throws Exception
{
  // Currently not an extensive test, but it does fire up the JSP pages and make
  // sure they compile ok

  String adminPath = "http://127.0.0.1:"+port+context+"/";
  byte[] bytes = IOUtils.toByteArray( new URL(adminPath).openStream() );
  assertNotNull( bytes ); // real error will be an exception

  HttpClient client = HttpClients.createDefault();
  HttpRequestBase m = new HttpGet(adminPath);
  HttpResponse response = client.execute(m, HttpClientUtil.createNewHttpClientRequestContext());
  assertEquals(200, response.getStatusLine().getStatusCode());
  Header header = response.getFirstHeader("X-Frame-Options");
  assertEquals("DENY", header.getValue().toUpperCase(Locale.ROOT));
  m.releaseConnection();
}
 
Example 3
Source File: NotEmptyTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
    String vaadinPackagePrefix = getClass().getPackage().getName();
    vaadinPackagePrefix = vaadinPackagePrefix.substring(0,
            vaadinPackagePrefix.lastIndexOf('.'));
    if (name.equals(UnitTest.class.getName())) {
        super.loadClass(name);
    } else if (name.startsWith(NotEmpty.class.getPackage().getName())) {
        throw new ClassNotFoundException();
    } else if (name.startsWith(vaadinPackagePrefix)) {
        String path = name.replace('.', '/').concat(".class");
        URL resource = Thread.currentThread().getContextClassLoader()
                .getResource(path);
        InputStream stream;
        try {
            stream = resource.openStream();
            byte[] bytes = IOUtils.toByteArray(stream);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return super.loadClass(name);
}
 
Example 4
Source File: ActionCreateFormProcessPlatform.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private byte[] readAttachmentContent(String workId, String workAttachmentId) throws Exception {
	Application app = ThisApplication.context().applications()
			.randomWithWeight(x_processplatform_assemble_surface.class.getName());
	String address = app.getUrlJaxrsRoot() + "attachment/download/" + workAttachmentId + "/work/" + workId;
	HttpURLConnection connection = HttpConnection.prepare(address, CipherConnectionAction.cipher());
	connection.setRequestMethod("GET");
	connection.setDoOutput(false);
	connection.setDoInput(true);
	byte[] bytes = null;
	connection.connect();
	try (InputStream input = connection.getInputStream()) {
		bytes = IOUtils.toByteArray(input);
	}
	connection.disconnect();
	return bytes;
}
 
Example 5
Source File: ContractPOCMSendTxTest.java    From nuls-v2 with MIT License 6 votes vote down vote up
private String nrc20Locked(String alias, String name, String symbol, String totalSupply, String decimals) throws Exception {
    Log.info("begin create locked nrc20");
    String filePath = "/Users/pierreluo/IdeaProjects/NRC20-Locked-Token/target/nrc20-locked-token-test1.jar";
    //String filePath = ContractTest.class.getResource("/nrc20-locked-token.jar").getFile();
    InputStream in = new FileInputStream(filePath);
    byte[] contractCode = IOUtils.toByteArray(in);
    String remark = "create contract test - " + alias;
    Map params = this.makeCreateParams(sender, contractCode, alias, remark, name, symbol, totalSupply, decimals);
    Response cmdResp2 = ResponseMessageProcessor.requestAndResponse(ModuleE.SC.abbr, CREATE, params);
    Map result = (HashMap) (((HashMap) cmdResp2.getResponseData()).get(CREATE));
    assertTrue(cmdResp2, result);
    String hash = (String) result.get("txHash");
    String contractAddress = (String) result.get("contractAddress");
    Map map = waitGetContractTx(hash);
    Assert.assertTrue(JSONUtils.obj2PrettyJson(map), map != null && (Boolean) ((Map)(map.get("contractResult"))).get("success"));
    return contractAddress;
}
 
Example 6
Source File: Jsr303Test.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
    String vaadinPackagePrefix = VaadinServlet.class.getPackage()
            .getName();
    vaadinPackagePrefix = vaadinPackagePrefix.substring(0,
            vaadinPackagePrefix.lastIndexOf('.'));
    if (name.equals(UnitTest.class.getName())) {
        super.loadClass(name);
    } else if (name
            .startsWith(Validation.class.getPackage().getName())) {
        throw new ClassNotFoundException();
    } else if (name.startsWith(vaadinPackagePrefix)) {
        String path = name.replace('.', '/').concat(".class");
        URL resource = Thread.currentThread().getContextClassLoader()
                .getResource(path);
        InputStream stream;
        try {
            stream = resource.openStream();
            byte[] bytes = IOUtils.toByteArray(stream);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return super.loadClass(name);
}
 
Example 7
Source File: TofinoPipelineProgrammable.java    From onos with Apache License 2.0 6 votes vote down vote up
private ByteBuffer extensionBuffer(PiPipeconf pipeconf, ExtensionType extType) {
    if (!pipeconf.extension(extType).isPresent()) {
        log.warn("Missing extension {} in pipeconf {}", extType, pipeconf.id());
        throw new ExtensionException();
    }
    try {
        byte[] bytes = IOUtils.toByteArray(pipeconf.extension(extType).get());
        // Length of the extension + bytes.
        return ByteBuffer.allocate(Integer.BYTES + bytes.length)
                .order(ByteOrder.LITTLE_ENDIAN)
                .putInt(bytes.length)
                .put(bytes);
    } catch (IOException ex) {
        log.warn("Unable to read extension {} from pipeconf {}: {}",
                 extType, pipeconf.id(), ex.getMessage());
        throw new ExtensionException();
    }
}
 
Example 8
Source File: ContractNRC20TokenQueryTest.java    From nuls-v2 with MIT License 5 votes vote down vote up
/**
 * 验证创建合约
 */
@Test
public void validateCreate() throws Exception {
    InputStream in = new FileInputStream(ContractTest.class.getResource("/nrc20").getFile());
    byte[] contractCode = IOUtils.toByteArray(in);
    String name = "KQB";
    String symbol = "KongQiBi";
    String amount = BigDecimal.TEN.pow(10).toPlainString();
    String decimals = "2";
    Map params = this.makeValidateCreateParams(sender, contractCode, name, symbol, amount, decimals);
    Response cmdResp2 = ResponseMessageProcessor.requestAndResponse(ModuleE.SC.abbr, VALIDATE_CREATE, params);
    Log.info("validate_create-Response:{}", JSONUtils.obj2PrettyJson(cmdResp2));
    Assert.assertTrue(cmdResp2.isSuccess());
}
 
Example 9
Source File: RenderableTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenderableFileAsChunked() throws Exception {
    final File file = new File("target/test-classes/a_file.txt");
    RenderableFile body = new RenderableFile(file, false);
    assertThat(body.length()).isEqualTo(file.length());
    assertThat(body.content()).isEqualTo(file);
    assertThat(body.mimetype()).isEqualTo(MimeTypes.TEXT);
    assertThat(body.mustBeChunked()).isFalse();
    assertThat(body.requireSerializer()).isFalse();
    byte[] bytes = IOUtils.toByteArray(body.render(null, null));
    assertThat(new String(bytes, Charsets.UTF_8)).isEqualTo("Used as test data.");
}
 
Example 10
Source File: SsioIntegrationTest.java    From sep4j with Apache License 2.0 5 votes vote down vote up
private ByteArrayInputStream toByteArrayInputStreamAndClose(InputStream in) {
	try {
		byte[] bytes = IOUtils.toByteArray(in);
		return new ByteArrayInputStream(bytes);
	} catch (IOException e) {
		throw new IllegalStateException(e);
	} finally {
		IOUtils.closeQuietly(in);
	}

}
 
Example 11
Source File: PatchSplitter.java    From OptiFabric with Mozilla Public License 2.0 5 votes vote down vote up
public static ClassCache generateClassCache(File inputFile, File classCacheOutput, byte[] inputHash) throws IOException {
	boolean extractClasses = Boolean.parseBoolean(System.getProperty("optifabric.extract", "false"));
	File classesDir = new File(classCacheOutput.getParent(), "classes");
	if(extractClasses){
		classesDir.mkdir();
	}
	ClassCache classCache = new ClassCache(inputHash);
	try (JarFile jarFile = new JarFile(inputFile)) {
		Enumeration<JarEntry> entrys = jarFile.entries();
		while (entrys.hasMoreElements()) {
			JarEntry entry = entrys.nextElement();
			if ((entry.getName().startsWith("net/minecraft/") || entry.getName().startsWith("com/mojang/")) && entry.getName().endsWith(".class")) {
				try(InputStream inputStream = jarFile.getInputStream(entry)){
					String name = entry.getName();
					byte[] bytes = IOUtils.toByteArray(inputStream);
					classCache.addClass(name, bytes);
					if(extractClasses){
						File classFile = new File(classesDir, entry.getName());
						FileUtils.writeByteArrayToFile(classFile, bytes);
					}
				}
			}
		}
	}


	//Remove all the classes that are going to be patched in, we dont want theses on the classpath
	ZipUtil.removeEntries(inputFile, classCache.getClasses().stream().toArray(String[]::new));

	System.out.println("Found " + classCache.getClasses().size() + " patched classes");
	classCache.save(classCacheOutput);
	return classCache;
}
 
Example 12
Source File: HTMLImageElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"load;", "2"})
public void emptyMimeType() throws Exception {
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img")) {
        final byte[] directBytes = IOUtils.toByteArray(is);

        final URL urlImage = new URL(URL_SECOND, "img.jpg");
        final List<NameValuePair> emptyList = Collections.emptyList();
        getMockWebConnection().setResponse(urlImage, directBytes, 200, "ok", "", emptyList);
        getMockWebConnection().setDefaultResponse("Test");
    }

    final String html = "<html><head>\n"
        + "<script>\n"
        + "  function showInfo(text) {\n"
        + "    document.title += text + ';';\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body>\n"
        + "  <img id='myImage5' src='" + URL_SECOND + "img.jpg' onload='showInfo(\"load\")' "
                + "onerror='showInfo(\"error\")'>\n"
        + "</body></html>";

    final int count = getMockWebConnection().getRequestCount();
    final WebDriver driver = getWebDriver();
    if (driver instanceof HtmlUnitDriver) {
        ((HtmlUnitDriver) driver).setDownloadImages(true);
    }
    loadPage2(html);

    assertTitle(driver, getExpectedAlerts()[0]);
    assertEquals(Integer.parseInt(getExpectedAlerts()[1]), getMockWebConnection().getRequestCount() - count);
}
 
Example 13
Source File: YamlSequencePrintTest.java    From eo-yaml with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Read a test resource file's contents.
 * @param fileName File to read.
 * @return File's contents as String.
 * @throws FileNotFoundException If something is wrong.
 * @throws IOException If something is wrong.
 */
private String readExpected(final String fileName)
    throws FileNotFoundException, IOException {
    return new String(
        IOUtils.toByteArray(
            new FileInputStream(
                new File(
                    "src/test/resources/printing_tests/" + fileName
                )
            )
        )
    );
}
 
Example 14
Source File: RestFunctions.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Read bytes from a HDFS path.
 * @param inPath
 * @return
 * @throws IOException
 */
private static byte[] readBytes(Path inPath) throws IOException {
  FileSystem fs = FileSystem.get(inPath.toUri(), new Configuration());
  try (FSDataInputStream inputStream = fs.open(inPath)) {
    return IOUtils.toByteArray(inputStream);
  }
}
 
Example 15
Source File: HTMLImageElementTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
  * Test that image's width and height are numbers.
  * @throws Exception if the test fails
  */
@Test
@Alerts(DEFAULT = {"number: 300", "number: 200", "number: 24", "number: 24", "number: 24", "number: 24"},
        CHROME = {"number: 300", "number: 200", "number: 0", "number: 0", "number: 0", "number: 0"},
        IE = {"number: 300", "number: 200", "number: 28", "number: 30", "number: 28", "number: 30"})
public void widthHeightBlankSource() throws Exception {
    getMockWebConnection().setDefaultResponse("");

    final String html = "<html><head>\n"
        + "<script>\n"
        + "  function showInfo(imageId) {\n"
        + "    var img = document.getElementById(imageId);\n"
        + "    alert(typeof(img.width) + ': ' + img.width);\n"
        + "    alert(typeof(img.height) + ': ' + img.height);\n"
        + "  }\n"
        + "  function test() {\n"
        + "    showInfo('myImage1');\n"
        + "    showInfo('myImage2');\n"
        + "    showInfo('myImage3');\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "  <img id='myImage1' src=' ' width='300' height='200'>\n"
        + "  <img id='myImage2' src=' ' >\n"
        + "  <img id='myImage3' src=' ' width='hello' height='hello'>\n"
        + "</body></html>";

    final URL url = getClass().getClassLoader().getResource("testfiles/tiny-jpg.img");
    try (FileInputStream fis = new FileInputStream(new File(url.toURI()))) {
        final byte[] directBytes = IOUtils.toByteArray(fis);
        final MockWebConnection webConnection = getMockWebConnection();
        final List<NameValuePair> emptyList = Collections.emptyList();
        webConnection.setResponse(URL_SECOND, directBytes, 200, "ok", "image/jpg", emptyList);
    }

    loadPageWithAlerts2(html);
}
 
Example 16
Source File: TestHttpServerPushSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testAvroData() throws Exception {
  HttpSourceConfigs httpConfigs = new HttpSourceConfigs();
  httpConfigs.appIds = new ArrayList<>();
  httpConfigs.appIds.add(new CredentialValueBean("id"));
  httpConfigs.port = NetworkUtils.getRandomPort();
  httpConfigs.maxConcurrentRequests = 1;
  httpConfigs.tlsConfigBean.tlsEnabled = false;
  httpConfigs.appIdViaQueryParamAllowed = true;
  DataParserFormatConfig dataFormatConfig = new DataParserFormatConfig();
  dataFormatConfig.avroSchemaSource = OriginAvroSchemaSource.SOURCE;
  HttpServerPushSource source =
          new HttpServerPushSource(httpConfigs, 1, DataFormat.AVRO, dataFormatConfig);
  final PushSourceRunner runner =
          new PushSourceRunner.Builder(HttpServerDPushSource.class, source).addOutputLane("a").build();
  runner.runInit();
  try {
    final List<Record> records = new ArrayList<>();
    runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
      @Override
      public void processBatch(StageRunner.Output output) {
        records.clear();
        records.addAll(output.getRecords().get("a"));
      }
    });

    // wait for the HTTP server up and running
    HttpReceiverServer httpServer = (HttpReceiverServer)Whitebox.getInternalState(source, "server");
    await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

    String url = "http://localhost:" + httpConfigs.getPort() +
            "?" + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
    File avroDataFile = SdcAvroTestUtil.createAvroDataFile();
    InputStream in = new FileInputStream(avroDataFile);
    byte[] avroData = IOUtils.toByteArray(in);
    Response response = ClientBuilder.newClient()
            .target(url)
            .request()
            .post(Entity.entity(avroData, MediaType.APPLICATION_OCTET_STREAM_TYPE));
    Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
    Assert.assertEquals(3, records.size());
    Assert.assertEquals("a", records.get(0).get("/name").getValue());
    Assert.assertEquals("b", records.get(1).get("/name").getValue());
    Assert.assertEquals("c", records.get(2).get("/name").getValue());
    runner.setStop();
  } catch (Exception e) {
    Assert.fail(e.getMessage());
  } finally {
    runner.runDestroy();
  }
}
 
Example 17
Source File: CompressGzip.java    From opentest with MIT License 4 votes vote down vote up
@Override
public void run() {
    super.run();

    String sourceFile = readStringArgument("sourceFile", null);
    Object sourceBytesObj = this.readArgument("sourceBytes", null);
    String sourceString = this.readStringArgument("sourceString", null);
    String targetFile = readStringArgument("targetFile", null);

    try {
        byte[] sourceBytes;

        if (sourceFile != null) {
            InputStream sourceStream = new FileInputStream(sourceFile);
            sourceBytes = IOUtils.toByteArray(sourceStream);
        } else if (sourceBytesObj != null) {
            if (sourceBytesObj instanceof byte[]) {
                sourceBytes = (byte[]) sourceBytesObj;
            } else if (sourceBytesObj instanceof ScriptObjectMirror) {
                sourceBytes = TypeUtil.jsNumberArrayToJavaByteArray(
                        (ScriptObjectMirror) sourceBytesObj);
            } else {
                throw new RuntimeException(
                        "The \"sourceBytes\" argument must be either a Java "
                        + "native byte array or a JavaScript number array.");
            }
        } else if (sourceString != null) {
            sourceBytes = sourceString.getBytes("UTF-8");
        } else {
            throw new RuntimeException(
                    "You must either provide the \"sourceFile\" argument, the \"sourceBytes\" argument or the "
                    + "\"sourceString\" argument to indicate what is the source data to work with.");
        }

        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzOutputStream = new GZIPOutputStream(byteOutputStream);
        gzOutputStream.write(sourceBytes);
        gzOutputStream.close();

        byte[] compressedBytes = byteOutputStream.toByteArray();

        if (targetFile != null) {
            FileOutputStream outputStream
                    = new FileOutputStream(targetFile);
            IOUtils.copy(new ByteArrayInputStream(compressedBytes), outputStream);
            outputStream.close();
        }

        this.writeOutput("compressedBytes", compressedBytes);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 18
Source File: NotificationsServiceIT.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void badCertificate() throws Exception {


    // if we're not using real connections, then adding a notifier with bad cert is noop as certs don't exist
    // for the test adapter
    if(!USE_REAL_CONNECTIONS){
        return;
    }

    // create an apns notifier with the wrong certificate //
    app.clear();
    app.put("name", "prod_apns");
    app.put("provider", PROVIDER);
    app.put("environment", "development");

    InputStream fis = getClass().getClassLoader().getResourceAsStream("pushtest_dev_recent.p12");
    byte[] certBytes = IOUtils.toByteArray(fis);
    app.put("p12Certificate", certBytes);
    fis.close();

    Entity e = app.testRequest(ServiceAction.POST, 1, "notifiers")
            .getEntity();
    notifier = app.getEntityManager().get(e.getUuid(), Notifier.class);


    // create push notification //

    app.clear();
    String payload = getPayload();
    Map<String, String> payloads = new HashMap<String, String>(1);
    payloads.put(notifier.getUuid().toString(), payload);
    app.put("payloads", payloads);
    app.put("queued", System.currentTimeMillis());
    app.put("debug",true);

    e = app.testRequest(ServiceAction.POST, 1,"devices",device1.getUuid(), "notifications").getEntity();
    app.testRequest(ServiceAction.GET, 1, "notifications", e.getUuid());

    Notification notification = app.getEntityManager().get(e.getUuid(),
            Notification.class);
    assertEquals(
            notification.getPayloads().get(notifier.getUuid().toString()),
            payload);

    // perform push //
    try {
        notificationWaitForComplete(notification);
        fail("testConnection() should have failed");
    } catch (Exception ex) {
        // good, there should be an error
    }

    // verify Query for FAILED state
    Query query = Query.fromEquals("state", Notification.State.FAILED.toString());
    Results results = app.getEntityManager().searchCollection(
            app.getEntityManager().getApplicationRef(), "notifications", query);
    Entity entity = results.getEntitiesMap().get(notification.getUuid());
    assertNotNull(entity);
}
 
Example 19
Source File: DbUtilities.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public static int readoutInJsonOutputStream(DataSource dataSource, String statementString, List<String> dataColumns, OutputStream outputStream) throws Exception {
	try (final Connection connection = dataSource.getConnection()) {
		try (Statement statement = connection.createStatement()) {
			try (ResultSet resultSet = statement.executeQuery(statementString)) {
				try (JsonWriter jsonWriter = new JsonWriter(outputStream)) {
					ResultSetMetaData metaData = resultSet.getMetaData();
					int itemCount = 0;
					jsonWriter.openJsonArray();
					while (resultSet.next()) {
						itemCount++;
						JsonObject jsonObject = new JsonObject();
						for (int i = 1; i <= metaData.getColumnCount(); i++) {
							String propertyName = dataColumns.get(i -1);
							if (metaData.getColumnType(i) == Types.BLOB
									|| metaData.getColumnType(i) == Types.BINARY
									|| metaData.getColumnType(i) == Types.VARBINARY
									|| metaData.getColumnType(i) == Types.LONGVARBINARY) {
								Blob blob = resultSet.getBlob(i);
								if (resultSet.wasNull()) {
									jsonObject.add(propertyName, null);
								} else {
									try (InputStream input = blob.getBinaryStream()) {
										byte[] data = IOUtils.toByteArray(input);
										jsonObject.add(propertyName, Base64.getEncoder().encodeToString(data));
									}
								}
							} else if (metaData.getColumnType(i) == Types.DATE || metaData.getColumnType(i) == Types.TIMESTAMP) {
								String value = resultSet.getString(i);
								if ("0000-00-00 00:00:00".equals(value)) {
									value = null;
								}
								jsonObject.add(propertyName, value);
							} else {
								jsonObject.add(propertyName, resultSet.getString(i));
							}
						}
						jsonWriter.add(jsonObject);
					}
					jsonWriter.closeJsonArray();

					return itemCount;
				}
			}
		}
	}
}
 
Example 20
Source File: AssetResourceIT.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void multipartPutFormOnDynamicEntity() throws Exception {

    this.waitForQueueDrainAndRefreshIndex();

    // post an entity

    Map<String, String> payload = hashMap( "foo", "bar" );
    ApiResponse postResponse = pathResource( getOrgAppPath( "foos" ) ).post( payload );
    UUID assetId = postResponse.getEntities().get(0).getUuid();
    assertNotNull( assetId );

    // post asset to that entity

    byte[] data = IOUtils.toByteArray( this.getClass().getResourceAsStream( "/cassandra_eye.jpg" ) );
    FormDataMultiPart form = new FormDataMultiPart()
        .field( "foo", "bar2" )
        .field( "file", data, MediaType.MULTIPART_FORM_DATA_TYPE );
    ApiResponse putResponse = pathResource( getOrgAppPath( "foos/" + assetId ) ).put( form );
    this.waitForQueueDrainAndRefreshIndex();

    // get entity and check asset metadata

    ApiResponse getResponse = pathResource( getOrgAppPath( "foos/" + assetId ) ).get( ApiResponse.class );
    Entity entity = getResponse.getEntities().get( 0 );
    Map<String, Object> fileMetadata = (Map<String, Object>)entity.get("file-metadata");
    long lastModified = Long.parseLong( fileMetadata.get( AssetUtils.LAST_MODIFIED ).toString() );

    assertEquals( assetId,      entity.getUuid() );
    assertEquals( "bar2",       entity.get("foo") );
    assertEquals( "image/jpeg", fileMetadata.get( AssetUtils.CONTENT_TYPE ) );
    assertEquals( 7979,         fileMetadata.get( AssetUtils.CONTENT_LENGTH ));

    // get asset and check size

    InputStream is = pathResource( getOrgAppPath( "foos/" + assetId ) ).getAssetAsStream();
    byte[] foundData = IOUtils.toByteArray( is );
    assertEquals( 7979, foundData.length );

    // upload new asset to entity, then check that it was updated

    ApiResponse putResponse2 = pathResource( getOrgAppPath( "foos/" + assetId ) ).put( form );
    entity = putResponse2.getEntities().get( 0 );
    fileMetadata = (Map<String, Object>)entity.get("file-metadata");
    long justModified = Long.parseLong( fileMetadata.get( AssetUtils.LAST_MODIFIED ).toString() );
    assertNotEquals( lastModified, justModified );
}