org.apache.commons.io.output.ByteArrayOutputStream Java Examples

The following examples show how to use org.apache.commons.io.output.ByteArrayOutputStream. 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: S3TransportBuffer.java    From bender with Apache License 2.0 7 votes vote down vote up
public S3TransportBuffer(long maxBytes, boolean useCompression, S3TransportSerializer serializer)
    throws TransportException {
  this.maxBytes = maxBytes;
  this.serializer = serializer;

  baos = new ByteArrayOutputStream();
  cos = new CountingOutputStream(baos);

  if (useCompression) {
    this.isCompressed = true;
    try {
      os = new BZip2CompressorOutputStream(cos);
    } catch (IOException e) {
      throw new TransportException("unable to create BZip2CompressorOutputStream", e);
    }
  } else {
    this.isCompressed = false;
    os = cos;
  }
}
 
Example #2
Source File: CloverDataParserTest.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected byte[] getBytes(int compressLevel) {
	try {
		CloverDataFormatter formatter = new CloverDataFormatter();
		formatter.setCompressLevel(compressLevel);
		DataRecordMetadata metadata = getMetadata();
		formatter.init(metadata);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		formatter.setDataTarget(os);
		formatter.writeHeader();
		DataRecord record = DataRecordFactory.newRecord(metadata);
		CloverBuffer buffer = null;
		if (formatter.isDirect()) {
			buffer = CloverBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE);
		}
		record.getField(0).setValue("test1");
		writeRecord(formatter, record, buffer);
		record.getField(0).setValue("test2");
		writeRecord(formatter, record, buffer);
		formatter.writeFooter();
		formatter.flush();
		formatter.close();
		return os.toByteArray();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #3
Source File: CompressedXmiReader.java    From argument-reasoning-comprehension-task with Apache License 2.0 6 votes vote down vote up
@Override
public void getNext(CAS aCAS)
        throws IOException, CollectionException
{
    // nextTarEntry cannot be null here!
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int size = IOUtils.copy(tarArchiveInputStream, buffer);

    String entryName = nextTarEntry.getName();
    getLogger().debug("Loaded " + size + " bytes from " + entryName);

    // and move forward
    fastForwardToNextValidEntry();

    // and now create JCas
    InputStream inputStream = new ByteArrayInputStream(buffer.toByteArray());
    try {
        XmiCasDeserializer.deserialize(inputStream, aCAS, lenient);
    }
    catch (SAXException e) {
        throw new IOException(e);
    }
}
 
Example #4
Source File: MemoryJarClassLoader.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
public MemoryJarClassLoader(ClassLoader parentClassLoader, File jarFile) throws FileNotFoundException, IOException {
	super(parentClassLoader);
	this.jarFile = jarFile;
	try (FileInputStream fileInputStream = new FileInputStream(jarFile)) {
		try (JarInputStream jarInputStream = new JarInputStream(fileInputStream)) {
			JarEntry entry = jarInputStream.getNextJarEntry();
			while (entry != null) {
				if (entry.getName().endsWith(".jar")) {
					ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
					IOUtils.copy(jarInputStream, byteArrayOutputStream);
					
					// Not storing the original JAR, so future code will be unable to read the original
					loadSubJars(byteArrayOutputStream.toByteArray());
				} else {
					// Files are being stored deflated in memory because most of the time a lot of files are not being used (or the complete plugin is not being used)
					addDataToMap(jarInputStream, entry);
				}
				entry = jarInputStream.getNextJarEntry();
			}
		}
	}
}
 
Example #5
Source File: ESBJAVA_4572TestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.ALL})
@Test(groups = "wso2.esb", description = "disabling auto primitive option in synapse properties ", enabled = false)
public void testDisablingAutoConversionToScientificNotationInJsonStreamFormatter() throws Exception {
    String payload =
               "{\"state\":[{\"path\":\"user_programs_progress\",\"entry\":" +
               "[{\"value\":\"false\",\"key\":\"testJson14\"}]}]}";

    HttpResponse response = httpClient.doPost("http://localhost:8280/ESBJAVA4572abc/dd",
                                              null, payload, "application/json");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    response.getEntity().writeTo(bos);
    String exPayload = new String(bos.toByteArray());
    String val = "{\"state\":[{\"path\":\"user_programs_progress\",\"entry\":" +
                 "[{\"value\":\"false\",\"key\":\"testJson14\"}]}]}";
    Assert.assertEquals(val, exPayload);
}
 
Example #6
Source File: GraphServiceController.java    From android-java-connect-sample with MIT License 6 votes vote down vote up
/**
 * Converts a BufferedInputStream to a byte array
 *
 * @param inputStream
 * @param bufferLength
 * @return
 * @throws IOException
 */
private byte[] convertBufferToBytes(BufferedInputStream inputStream, int bufferLength) throws IOException {
    if (inputStream == null)
        return null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[bufferLength];
    int x = inputStream.read(buffer, 0, bufferLength);
    Log.i("GraphServiceController", "bytes read from picture input stream " + String.valueOf(x));

    int n = 0;
    try {
        while ((n = inputStream.read(buffer, 0, bufferLength)) >= 0) {
            outputStream.write(buffer, 0, n);
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    outputStream.close();
    return outputStream.toByteArray();
}
 
Example #7
Source File: BinaryDistributionControlServiceImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecureCopyFile() throws JSchException, IOException {
    final JschBuilder mockJschBuilder = mock(JschBuilder.class);
    final JSch mockJsch = mock(JSch.class);
    final Session mockSession = mock(Session.class);
    final ChannelExec mockChannelExec = mock(ChannelExec.class);
    final byte [] bytes = {0};
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    when(mockChannelExec.getInputStream()).thenReturn(new TestInputStream());
    when(mockChannelExec.getOutputStream()).thenReturn(out);
    when(mockSession.openChannel(eq("exec"))).thenReturn(mockChannelExec);
    when(mockJsch.getSession(anyString(), anyString(), anyInt())).thenReturn(mockSession);
    when(mockJschBuilder.build()).thenReturn(mockJsch);
    when(Config.mockSshConfig.getJschBuilder()).thenReturn(mockJschBuilder);
    when(Config.mockRemoteCommandExecutorService.executeCommand(any(RemoteExecCommand.class))).thenReturn(mock(RemoteCommandReturnInfo.class));
    final String source = BinaryDistributionControlServiceImplTest.class.getClassLoader().getResource("binarydistribution/copy.txt").getPath();
    binaryDistributionControlService.secureCopyFile("someHost", source, "./build/tmp");
    verify(Config.mockSshConfig).getJschBuilder();
    assertEquals("C0644 12 copy.txt\nsome content\0", out.toString(StandardCharsets.UTF_8));
}
 
Example #8
Source File: CommandUninstallTest.java    From minimesos with Apache License 2.0 6 votes vote down vote up
@Before
public void initTest() {
    outputStream = new ByteArrayOutputStream();
    ps = new PrintStream(outputStream, true);

    marathon = Mockito.mock(Marathon.class);

    mesosCluster = Mockito.mock(MesosCluster.class);
    when(mesosCluster.getMarathon()).thenReturn(marathon);

    repository = Mockito.mock(ClusterRepository.class);
    when(repository.loadCluster(Matchers.any(MesosClusterFactory.class))).thenReturn(mesosCluster);

    commandUninstall = new CommandUninstall(ps);
    commandUninstall.setRepository(repository);
}
 
Example #9
Source File: MacroHelper.java    From warp10-platform with Apache License 2.0 6 votes vote down vote up
public static WarpScriptStackFunction wrap(String name, InputStream in, boolean secure) {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  
  byte[] buf = new byte[1024];

  try {
    while(true) {
      int len = in.read(buf);
      
      if (len < 0) {
        break;
      }
      
      baos.write(buf, 0, len);
    }      
    
    in.close();
    
    String mc2 = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    
    return wrap(name, mc2, secure);
  } catch (IOException ioe) {
    throw new RuntimeException(ioe);
  }
}
 
Example #10
Source File: RequestBuilderImplTest.java    From datamill with ISC License 6 votes vote down vote up
@Test
public void body() {
    Request request = new RequestBuilderImpl()
            .body(new JsonObject().put("name", "value"))
            .build();

    assertEquals("value", request.body().asJson().toBlocking().last().get("name").asString());
    assertEquals("value", new JsonObject(request.body().asString().toBlocking().last()).get("name").asString());
    assertEquals("value", new JsonObject(new String(request.body().asBytes().toBlocking().last())).get("name").asString());
    assertEquals("value", new JsonObject(new String(request.body().asChunks()
            .collect(
                    () -> new ByteArrayOutputStream(),
                    (stream, chunk) -> {
                        try {
                            stream.write(chunk);
                        } catch (IOException e) { }
                    })
            .map(stream -> stream.toByteArray())
            .toBlocking().last())).get("name").asString());

    request = new RequestBuilderImpl()
            .body(new JsonArray("[{\"name\" : \"value\"}]"))
            .build();

    assertEquals("value", request.body().asJsonArray().toBlocking().last().get("name").asString());
}
 
Example #11
Source File: TinyMetricTest.java    From cubedb with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testSerDe() {
  TinyMetric metric = createMetric();
  for (int i = 1; i <= 10; i++) {
    metric.append(i);
  }
  Kryo kryo = new Kryo();
  ByteArrayOutputStream bao = new ByteArrayOutputStream();
  Output output = new Output(bao);
  kryo.writeObject(output, metric);
  output.close();
  TinyMetric deser =
      kryo.readObject(new Input(new ByteArrayInputStream(bao.toByteArray())), TinyMetric.class);
  assertEquals(metric.size(), deser.size());
  assertEquals(metric.getNumRecords(), deser.getNumRecords());
  for (int i = 0; i < metric.getNumRecords(); i++) {
    assertEquals(metric.get(i), deser.get(i));
  }
}
 
Example #12
Source File: ObjectSerializer.java    From java-license-manager with Apache License 2.0 6 votes vote down vote up
/**
 * Serializes the {@link Serializable} object passed and returns it as a byte array.
 *
 * @param object The object to serialize
 *
 * @return the byte stream with the object serialized in it.
 *
 * @throws ObjectSerializationException if an I/O exception occurs while serializing the object.
 */
public final byte[] writeObject(final Serializable object) throws ObjectSerializationException
{
    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    try(final ObjectOutputStream stream = new ObjectOutputStream(bytes))
    {
        stream.writeObject(object);
    }
    catch(final IOException e)
    {
        throw new ObjectSerializationException(e);
    }

    return bytes.toByteArray();
}
 
Example #13
Source File: JSONDisableAutoPrimitiveNumericTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = "wso2.esb", description = "disabling auto primitive option with a given regex pattern in synapse "
        + "properties  ")
public void testDisablingAutoConversionToScientificNotationInJsonStreamFormatter() throws Exception {
    String payload = "<coordinates>\n" + "   <location>\n" + "       <name>Bermuda Triangle</name>\n"
            + "       <n>25e1</n>\n" + "       <w>7.1e1</w>\n" + "   </location>\n" + "   <location>\n"
            + "       <name>Eiffel Tower</name>\n" + "       <n>4.8e3</n>\n" + "       <e>1.8e2</e>\n"
            + "   </location>\n" + "</coordinates>";
    HttpResponse response = httpClient
            .doPost(getProxyServiceURLHttp("JSONDisableAutoPrimitiveNumericTestProxy"), null, payload,
                    "application/xml");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    response.getEntity().writeTo(bos);
    String actualResult = new String(bos.toByteArray());
    String expectedPayload = "{\"coordinates\":{\"location\":[{\"name\":\"Bermuda Triangle\",\"n\":\"25e1\""
            + ",\"w\":\"7.1e1\"},{\"name\":\"Eiffel Tower\",\"n\":\"4.8e3\",\"e\":\"1.8e2\"}]}}";
    Assert.assertEquals(actualResult, expectedPayload);
}
 
Example #14
Source File: Gzip.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
@Override
public DataBuffer compress(DataBuffer buffer) {
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(stream);
        DataOutputStream dos = new DataOutputStream(gzip);

        buffer.write(dos);
        dos.flush();
        dos.close();

        byte[] bytes = stream.toByteArray();
        //            logger.info("Bytes: {}", Arrays.toString(bytes));
        BytePointer pointer = new BytePointer(bytes);
        CompressionDescriptor descriptor = new CompressionDescriptor(buffer, this);
        descriptor.setCompressedLength(bytes.length);

        CompressedDataBuffer result = new CompressedDataBuffer(pointer, descriptor);

        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: XLSXDataParserTest.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected byte[] getBytes() {
	if (bytes == null) {
		try {
			XLSXDataFormatter formatter = new XLSXDataFormatter(false, false);
			formatter.init(getMetadata());
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			formatter.setDataTarget(Channels.newChannel(os));
			formatter.prepareSheet();
			formatter.writeHeader();
			formatter.writeFooter();
			formatter.close();
			bytes = os.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	return bytes;
}
 
Example #16
Source File: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
public int getVersion() throws Exception {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
	executor.setStreamHandler(streamHandler);
	executor.execute(cmdLine);

	int version = 0;
	for (String line : outputStream.toString().split("\\n")) {
		if (line.startsWith("Rev. P4D")) {
			Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
			Matcher m = p.matcher(line);
			while (m.find()) {
				String found = m.group();
				found = found.replace(".", ""); // strip "."
				version = Integer.parseInt(found);
			}
		}
	}
	logger.info("P4D Version: " + version);
	return version;
}
 
Example #17
Source File: GPGFileEncryptorTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt a test string with an asymmetric key and check that it can be decrypted
 * @throws IOException
 * @throws PGPException
 */
@Test
public void encryptAsym() throws IOException, PGPException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  OutputStream os = GPGFileEncryptor.encryptFile(baos, getClass().getResourceAsStream(PUBLIC_KEY),
      Long.parseUnsignedLong(KEY_ID, 16), "CAST5");

  os.write(EXPECTED_FILE_CONTENT_BYTES);
  os.close();
  baos.close();

  byte[] encryptedBytes = baos.toByteArray();

  try (InputStream is = GPGFileDecryptor.decryptFile(new ByteArrayInputStream(encryptedBytes),
      getClass().getResourceAsStream(PRIVATE_KEY), PASSPHRASE)) {
    byte[] decryptedBytes = IOUtils.toByteArray(is);

    Assert.assertNotEquals(EXPECTED_FILE_CONTENT_BYTES, encryptedBytes);
    Assert.assertEquals(EXPECTED_FILE_CONTENT_BYTES, decryptedBytes);
  }
}
 
Example #18
Source File: GraphServiceController.java    From console-java-connect-sample with MIT License 6 votes vote down vote up
/**
 * Converts an inputStream to a byte array. The input stream should be a stream of profile
 * picture bytes that comes in the response to a GET request on the  Microsoft Graph API
 *
 * @param inputStream
 * @return
 */
private byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
    byte[] pictureBytes = null;
    try {
        BufferedInputStream bufferedInputStream = (BufferedInputStream) inputStream;
        byte[]              buff                = new byte[8000];


        ByteArrayOutputStream bao       = new ByteArrayOutputStream();
        int                   bytesRead = 0;

        //This seems to be executing on the main thread!!!
        while ((bytesRead = bufferedInputStream.read(buff)) != -1) {
            bao.write(buff, 0, bytesRead);
        }
        pictureBytes = bao.toByteArray();

        bao.close();
    } catch (IOException ex) {
        DebugLogger.getInstance().writeLog(Level.SEVERE,
                                           "Attempting to read buffered network resource",
                                           ex);
    }

    return pictureBytes;
}
 
Example #19
Source File: AvroOneM2MDataPublish.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 데이타 전송
 * @param event
 * @throws Exception
 * @return void
 */
public void send(COL_ONEM2M event) throws Exception {
	EncoderFactory avroEncoderFactory = EncoderFactory.get();
	SpecificDatumWriter<COL_ONEM2M> avroEventWriter = new SpecificDatumWriter<COL_ONEM2M>(COL_ONEM2M.SCHEMA$);
	
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream,null);

	try {
		avroEventWriter.write(event, binaryEncoder);
		binaryEncoder.flush();
	} catch (IOException e) {
		e.printStackTrace();
		throw e;
	}
	IOUtils.closeQuietly(stream);

	KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>(
			TOPIC, stream.toByteArray());

	producer.send(data);
}
 
Example #20
Source File: ActionGetBase64.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Attachment2 attachment = emc.find(id, Attachment2.class, ExceptionWhen.not_found);
		/* 判断文件的当前用户是否是管理员或者文件创建者 或者当前用户在分享或者共同编辑中 */
		if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
			throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} access attachment{id:"
					+ id + "} denied.");
		}
		OriginFile originFile = emc.find(attachment.getOriginFile(),OriginFile.class);
		if (null == originFile) {
			throw new ExceptionAttachmentNotExist(id,attachment.getOriginFile());
		}
		StorageMapping mapping = ThisApplication.context().storageMappings().get(OriginFile.class,
				originFile.getStorage());
		try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
			originFile.readContent(mapping, output);
			String value = Base64.encodeBase64String(output.toByteArray());
			Wo wo = new Wo();
			wo.setValue(value);
			result.setData(wo);
		}
		return result;
	}
}
 
Example #21
Source File: LogDataListPersistanceVer2Test.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogMessagesWithEmptyLastParams() throws IOException {
  List<LogData> list = new ArrayList<>();
  LogData ld1 = new LogDataBuilder().withId(1).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message1").build();
  LogData ld2 = new LogDataBuilder().withId(2).withDate(new Date()).withLevel(Level.INFO).withMessage("My Message2").build();
  list.add(ld1);
  list.add(ld2);
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  ver2.saveLogsList(out, list);

  ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
  List<LogData> loadLogsList = ver2.loadLogsList(in);

  AssertJUnit.assertEquals(2, loadLogsList.size());
  AssertJUnit.assertEquals(ld1.getMessage(), loadLogsList.get(0).getMessage());
  AssertJUnit.assertEquals(ld2.getMessage(), loadLogsList.get(1).getMessage());
  AssertJUnit.assertEquals(ld1, loadLogsList.get(0));
  AssertJUnit.assertEquals(ld2, loadLogsList.get(1));
}
 
Example #22
Source File: BytesBodyTest.java    From datamill with ISC License 6 votes vote down vote up
@Test
public void entityTests() {
    assertEquals("test", new BytesBody("test".getBytes()).asString().toBlocking().last());
    assertEquals("test", new String(new BytesBody("test".getBytes()).asBytes().toBlocking().last()));
    assertEquals("test", new String(new BytesBody("test".getBytes())
            .asChunks()
            .collect(
                    () -> new ByteArrayOutputStream(),
                    (stream, chunk) -> {
                        try {
                            stream.write(chunk);
                        } catch (IOException e) {
                        }
                    })
            .map(stream -> stream.toByteArray()).toBlocking().last()));
    Assert.assertEquals("value", new BytesBody("{\"name\":\"value\"}".getBytes())
            .asJson().toBlocking().last().get("name").asString());
    assertEquals("value", new BytesBody("[{\"name\":\"value\"}]".getBytes())
            .asJsonArray().toBlocking().last().get("name").asString());
}
 
Example #23
Source File: ZipMetaDir.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public void sync() throws IOException {
    if (entries != null) {
        if (entries.isDirty()) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            entries.save(out);
            zip.update(ENTRIES_FILE_NAME, out.toByteArray());
        }
    }
    zip.sync();
}
 
Example #24
Source File: Version.java    From steem-java-api-wrapper with GNU General Public License v3.0 5 votes vote down vote up
@Override
public byte[] toByteArray() throws SteemInvalidTransactionException {
    try (ByteArrayOutputStream serializedVersion = new ByteArrayOutputStream()) {
        serializedVersion.write(SteemJUtils.transformIntToByteArray(versionNumber));

        return serializedVersion.toByteArray();
    } catch (IOException e) {
        throw new SteemInvalidTransactionException(
                "A problem occured while transforming the version object into a byte array.", e);
    }
}
 
Example #25
Source File: ActionGetImageScaleBase64.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id, Integer scale) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Attachment2 attachment = emc.find(id, Attachment2.class, ExceptionWhen.not_found);
		/* 判断文件的当前用户是否是管理员或者文件创建者 或者当前用户在分享或者共同编辑中 */
		if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
			throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} access attachment{id:"
					+ id + "} denied.");
		}
		if (!ArrayUtils.contains(IMAGE_EXTENSIONS, attachment.getExtension())) {
			throw new Exception("attachment not image file.");
		}
		if (scale < 0 || scale > 100) {
			throw new Exception("invaild scale:" + scale + ".");
		}
		OriginFile originFile = emc.find(attachment.getOriginFile(),OriginFile.class);
		if (null == originFile) {
			throw new ExceptionAttachmentNotExist(id,attachment.getOriginFile());
		}
		StorageMapping mapping = ThisApplication.context().storageMappings().get(OriginFile.class,
				originFile.getStorage());
		try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
			originFile.readContent(mapping, output);
			try (ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray())) {
				BufferedImage src = ImageIO.read(input);
				int width = (src.getWidth() * scale) / (int) 100;
				int height = (src.getHeight() * scale) / (int) 100;
				BufferedImage scalrImage = Scalr.resize(src, width, height);
				try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
					ImageIO.write(scalrImage, "png", baos);
					String str = Base64.encodeBase64String(baos.toByteArray());
					Wo wo = new Wo();
					wo.setValue(str);
					result.setData(wo);
				}
			}
		}
		return result;
	}
}
 
Example #26
Source File: ActionGetImageScaleBase64.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id, Integer scale) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Attachment2 attachment = emc.find(id, Attachment2.class, ExceptionWhen.not_found);
		/* 判断文件的当前用户是否是管理员或者文件创建者 或者当前用户在分享或者共同编辑中 */
		if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
			throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} access attachment{id:"
					+ id + "} denied.");
		}
		if (!ArrayUtils.contains(IMAGE_EXTENSIONS, attachment.getExtension())) {
			throw new Exception("attachment not image file.");
		}
		if (scale < 0 || scale > 100) {
			throw new Exception("invaild scale:" + scale + ".");
		}
		OriginFile originFile = emc.find(attachment.getOriginFile(),OriginFile.class);
		if (null == originFile) {
			throw new ExceptionAttachmentNotExist(id,attachment.getOriginFile());
		}
		StorageMapping mapping = ThisApplication.context().storageMappings().get(OriginFile.class,
				originFile.getStorage());
		try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
			originFile.readContent(mapping, output);
			try (ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray())) {
				BufferedImage src = ImageIO.read(input);
				int width = (src.getWidth() * scale) / (int) 100;
				int height = (src.getHeight() * scale) / (int) 100;
				BufferedImage scalrImage = Scalr.resize(src, width, height);
				try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
					ImageIO.write(scalrImage, "png", baos);
					String str = Base64.encodeBase64String(baos.toByteArray());
					Wo wo = new Wo();
					wo.setValue(str);
					result.setData(wo);
				}
			}
		}
		return result;
	}
}
 
Example #27
Source File: MemorySegementingOutputStreamTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testCopy1() throws Exception {
    final ByteArrayOutputStream proxy = new ByteArrayOutputStream(20);
    final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768);
    final byte[] content = RandomUtils.nextBytes(40500);
    out.write(content, 0, 32800);
    assertEquals(32768, proxy.toByteArray().length);
    out.write(content, 32800, 7700);
    out.close();
    assertArrayEquals(content, proxy.toByteArray());
}
 
Example #28
Source File: PlaylistServiceTestExport.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testExportToM3U() throws Exception {

    when(mediaFileDao.getFilesInPlaylist(eq(23))).thenReturn(getPlaylistFiles());
    when(settingsService.getPlaylistExportFormat()).thenReturn("m3u");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    playlistService.exportPlaylist(23, outputStream);
    String actual = outputStream.toString();
    Assert.assertEquals(IOUtils.toString(getClass().getResourceAsStream("/PLAYLISTS/23.m3u")), actual);
}
 
Example #29
Source File: TestSdcIpcRequestFragmenter.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testFragmentWithSDCData() throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  Source.Context context =
      ContextInfoCreator.createSourceContext("foo", false, OnRecordError.TO_ERROR, Arrays.asList("a"));
  ContextExtensions ext = (ContextExtensions) context;
  RecordWriter rw = ext.createRecordWriter(baos);
  Record r1 = RecordCreator.create();
  r1.set(Field.create(true));
  Record r2 = RecordCreator.create();
  r2.set(Field.create(1));
  Record r3 = RecordCreator.create();
  r3.set(Field.create("a"));
  List<Record> records = Arrays.asList(r1, r2 , r3);
  for (Record record : records) {
    rw.write(record);
  }
  rw.close();
  List<byte[]> fragments =
      new SdcIpcRequestFragmenter().fragmentInternal(new ByteArrayInputStream(baos.toByteArray()), 1000, 2000);
  Assert.assertEquals(2, fragments.size());
  List<Record> got = new ArrayList<>();
  for (byte[] fragment : fragments) {
    InputStream is = new ByteArrayInputStream(fragment);
    RecordReader rr = ext.createRecordReader(is, 0, 500);
    Record r = rr.readRecord();
    while (r != null) {
      got.add(r);
      r = rr.readRecord();
    }
    rr.close();
  }
  Assert.assertEquals(records, got);
}
 
Example #30
Source File: GraphServiceController.java    From android-java-connect-sample with MIT License 5 votes vote down vote up
@TargetApi(21)
private byte[] getTestPicture() {
    byte[] bytes = new byte[1024];
    int resId = Connect.getInstance().getResources().getIdentifier("test","drawable",Connect.getInstance().getPackageName());
    Drawable image = Connect.getInstance().getDrawable(resId);
    Bitmap bitmap = ((BitmapDrawable)image).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
    bytes = stream.toByteArray();
    return bytes;
}