Java Examples for java.io.ByteArrayInputStream

The following java examples will help you to understand the usage of java.io.ByteArrayInputStream. These source code samples are taken from different open source projects.

Example 1
Project: android_libcore-master  File: ByteArrayInputStreamTest.java View source code
/**
     * @tests java.io.ByteArrayInputStream#ByteArrayInputStream(byte[])
     */
@TestTargetNew(level = TestLevel.COMPLETE, method = "ByteArrayInputStream", args = { byte[].class })
public void test_Constructor$B() {
    // Test for method java.io.ByteArrayInputStream(byte [])
    java.io.InputStream bis = new java.io.ByteArrayInputStream(fileString.getBytes());
    try {
        assertTrue("Unable to create ByteArrayInputStream", bis.available() == fileString.length());
    } catch (Exception e) {
        System.out.println("Exception during Constructor test");
    }
}
Example 2
Project: Onosendai-master  File: IoHelperTest.java View source code
@Test
public void itToStringsInputStreamWithMaxLength() throws Exception {
    assertEquals("12345", IoHelper.toString(new ByteArrayInputStream("1234567890".getBytes()), 5));
    assertEquals("1234567890", IoHelper.toString(new ByteArrayInputStream("1234567890".getBytes()), 10));
    assertEquals("1234567890", IoHelper.toString(new ByteArrayInputStream("1234567890".getBytes()), 15));
}
Example 3
Project: android-disk-multi-cache-master  File: Utils.java View source code
/**
     * Executes a download syncronously from a remote server
     *
     * @param urlname the remote url file to fetch
     * @return The downloaded stream as {@link java.io.ByteArrayInputStream}
     * @throws java.io.IOException
     */
public static ByteArrayInputStream download(String urlname) throws IOException {
    URL url = new URL(urlname);
    HttpURLConnection conn = null;
    InputStream stream = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        stream = conn.getInputStream();
        final byte[] bytes = IOUtils.toByteArray(stream);
        return new ByteArrayInputStream(bytes);
    } finally {
        if (null != conn) {
            conn.disconnect();
        }
        if (null != stream) {
            IOUtils.closeQuietly(stream);
        }
    }
}
Example 4
Project: Aspose_Cells_Java-master  File: KeepPrecisionOfLargeNumbers.java View source code
public static void main(String[] args) throws Exception {
    // The path to the documents directory.
    String dataDir = Utils.getSharedDataDir(KeepPrecisionOfLargeNumbers.class) + "articles/";
    // Sample Html containing large number with digits greater than 15
    String html = "<html>" + "<body>" + "<p>1234567890123456</p>" + "</body>" + "</html>";
    // Convert Html to byte array
    byte[] byteArray = html.getBytes();
    // Set Html load options and keep precision true
    HTMLLoadOptions loadOptions = new HTMLLoadOptions(LoadFormat.HTML);
    loadOptions.setKeepPrecision(true);
    // Convert byte array into stream
    java.io.ByteArrayInputStream stream = new java.io.ByteArrayInputStream(byteArray);
    // Create workbook from stream with Html load options
    Workbook workbook = new Workbook(stream, loadOptions);
    // Access first worksheet
    Worksheet worksheet = workbook.getWorksheets().get(0);
    // Auto fit the sheet columns
    worksheet.autoFitColumns();
    // Save the workbook
    workbook.save(dataDir + "KPOfLargeNumbers_out.xlsx", SaveFormat.XLSX);
    System.out.println("File saved");
}
Example 5
Project: highway-to-urhell-master  File: ParsingUtilTest.java View source code
@Test
public void should_extract_method() throws Exception {
    String source = "import org.junit.Test;\n" + "\n" + "public class JPTest {\n" + "\n" + "    @Test\n" + "    public void should_extract_method() {\n" + "        System.out.println(\"toto\");\n" + "    }\n" + "}\n";
    String should_extract_method = ParsingUtil.extractBody(new ByteArrayInputStream(source.getBytes()), "should_extract_method");
    assertThat(should_extract_method).isEqualTo("{\n" + "    System.out.println(\"toto\");\n" + "}");
}
Example 6
Project: archive-commons-master  File: ZipNumBlockIterator.java View source code
public CloseableIterator<String> iterator() throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
    OpenJDK7GZIPInputStream gzis = new OpenJDK7GZIPInputStream(bais);
    InputStreamReader isr = new InputStreamReader(gzis);
    BufferedReader br = new BufferedReader(isr);
    return AbstractPeekableIterator.wrapReader(br);
}
Example 7
Project: boon-master  File: JavaDeserializerBytes.java View source code
@Override
public V apply(byte[] value) {
    V v = null;
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(value);
    try {
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        v = (V) objectInputStream.readObject();
    } catch (Exception e) {
        Exceptions.handle(e);
    }
    return v;
}
Example 8
Project: btrbck-master  File: BlockTransferServiceTest.java View source code
@Test
public void test() throws IOException, ClassNotFoundException {
    BlockTransferService service = new BlockTransferService();
    String in = "Hello World, I like it!";
    ByteArrayInputStream inStream = new ByteArrayInputStream(in.getBytes("UTF-8"));
    ByteArrayOutputStream outStream1 = new ByteArrayOutputStream();
    ByteArrayOutputStream outStream2 = new ByteArrayOutputStream();
    service.sendBlocks(inStream, outStream1, 3);
    service.readBlocks(new ByteArrayInputStream(outStream1.toByteArray()), outStream2);
    assertEquals(in, outStream2.toString("UTF-8"));
}
Example 9
Project: cascading.utils-master  File: AbstractPlatformTest.java View source code
public void testSerialization(BasePlatform platform) throws Exception {
    platform.setJobPollingInterval(666);
    platform.setNumReduceTasks(23);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(platform);
    out.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bais);
    BasePlatform newPlatform = (BasePlatform) in.readObject();
    assertEquals(platform, newPlatform);
    assertEquals(platform.getDefaultLogDir(), newPlatform.getDefaultLogDir());
}
Example 10
Project: com.idega.cxf-master  File: HelloSpringImpl.java View source code
public String sendNode(byte[] node) {
    System.out.println("send Node called");
    try {
        /*ByteArrayInputStream is =*/
        new ByteArrayInputStream(node);
    //Document doc = DOMUtils.readXml(is);
    //			System.out.println("doc: "+doc);
    //			System.out.println("fword: "+doc.getDocumentElement().getNodeName());
    //			
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "Node got: " + node;
}
Example 11
Project: Europeana-Cloud-master  File: StreamCompressorTest.java View source code
@Test
public void shouldCompressAndDecompressContent() throws Exception {
    //given
    byte[] bytes = "Test content".getBytes();
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    //when
    byte[] compressedBytes = instance.compress(is);
    instance.decompress(compressedBytes, os);
    //then
    assertThat(os.toByteArray(), is(bytes));
}
Example 12
Project: featurehouse_fstcomp_examples-master  File: MusicAlbumData.java View source code
/** 
 * @param recordStore
 * @param musicName
 * @return
 * @throws ImageNotFoundException
 * @throws PersistenceMechanismException
 */
public InputStream getMusicFromRecordStore(String recordStore, String musicName) throws ImageNotFoundException, PersistenceMechanismException {
    MediaData mediaInfo = null;
    mediaInfo = mediaAccessor.getMediaInfo(musicName);
    int mediaId = mediaInfo.getForeignRecordId();
    String album = mediaInfo.getParentAlbumName();
    byte[] musicData = (mediaAccessor).loadMediaBytesFromRMS(album, mediaId);
    return new ByteArrayInputStream(musicData);
}
Example 13
Project: Java-ECOM-Project-master  File: Util.java View source code
public static ShellBuilder createShellBuilderWithInput(String input, OutputStream output, OutputStream error) throws UnsupportedEncodingException {
    input = input + "\n";
    ByteArrayInputStream inputStream = new ByteArrayInputStream(input.getBytes("UTF-8"));
    BaseContext c = new BaseContext();
    ShellBuilder sb = new ShellBuilder();
    sb.createNewShell(c, inputStream, new PrintStream(output), new PrintStream(error));
    return sb;
}
Example 14
Project: jeboorker-master  File: TrueZipUtilsTest.java View source code
public void test1() throws Exception {
    byte[] data = "INHALT_NEU".getBytes();
    File file = new File("/tmp/test1.cbz");
    IResourceHandler resourceHandler = ResourceHandlerFactory.getResourceHandler(file);
    TrueZipUtils.add(resourceHandler, "eintragPÄ2.txt", new ByteArrayInputStream(data));
    List<String> list = TrueZipUtils.list(resourceHandler);
    System.out.println(list);
    file.delete();
}
Example 15
Project: jerlang-master  File: StringTableChunkReaderTest.java View source code
@Test
public void testStringTableChunkReader() throws Throwable {
    File file = new File("src/test/resources/pid.beam");
    byte[] bytes = Files.readAllBytes(file.toPath());
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
    Chunk chunk = new Chunk(ChunkId.STRT, 228, 0);
    dis.skipBytes(chunk.offset());
    StringTableChunkReader stringTableChunkReader = new StringTableChunkReader(chunk, dis);
    StringTableChunk stringTableChunk = stringTableChunkReader.read();
    assertNotNull(stringTableChunk);
    assertNotNull(stringTableChunk.strings());
    assertEquals(0, stringTableChunk.strings().length());
}
Example 16
Project: JPaxos-master  File: AbstractMessageTestCase.java View source code
@SuppressWarnings("unchecked")
protected void verifySerialization(T message) {
    byte[] bytes = MessageFactory.serialize(message);
    assertEquals(bytes.length, message.byteSize());
    T deserialized = (T) MessageFactory.readByteArray(bytes);
    compare(message, deserialized);
    DataInputStream stream = new DataInputStream(new ByteArrayInputStream(bytes));
    deserialized = (T) MessageFactory.create(stream);
    compare(message, deserialized);
}
Example 17
Project: loopy-sdk-android-master  File: IOUtilsTest.java View source code
public void testRead() throws IOException {
    String testData = "the quick brown fox jumps over the lazy dog";
    ByteArrayInputStream in0 = new ByteArrayInputStream(testData.getBytes());
    ByteArrayInputStream in1 = new ByteArrayInputStream(testData.getBytes());
    String out0 = IOUtils.read(in0, 1024);
    String out1 = IOUtils.read(in1, 4);
    assertEquals(testData, out0);
    assertEquals(testData, out1);
}
Example 18
Project: ocr-tools-master  File: TextMergerTest.java View source code
@Test
public void shouldMergeTwo() throws Exception {
    InputStream stream1 = new ByteArrayInputStream(input1.getBytes());
    InputStream stream2 = new ByteArrayInputStream(input2.getBytes());
    List<InputStream> inputs = Arrays.asList(stream1, stream2);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Merger mergerSut = new TextMerger();
    mergerSut.mergeBuffered(inputs, output);
    String result = output.toString();
    assertThat(result, containsString("test1"));
    assertThat(result, containsString("test2"));
}
Example 19
Project: oddjob-master  File: SerializeWithBytes.java View source code
public Object fromBytes(byte[] bytes, ClassLoader classLoader) {
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    try {
        ObjectInput oi = new OddjobObjectInputStream(is, classLoader);
        Object o = oi.readObject();
        oi.close();
        return o;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 20
Project: SabdroidEx-master  File: IOUtil.java View source code
public static InputStream copy(InputStream inputStream) throws IOException {
    inputStream.reset();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    while ((len = inputStream.read(buffer)) > -1) {
        byteArrayOutputStream.write(buffer, 0, len);
    }
    byteArrayOutputStream.flush();
    inputStream.reset();
    return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
Example 21
Project: slumberdb-master  File: JavaDeserializerBytes.java View source code
@Override
public V apply(byte[] value) {
    V v = null;
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(value);
    try {
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        v = (V) objectInputStream.readObject();
    } catch (Exception e) {
        Exceptions.handle(e);
    }
    return v;
}
Example 22
Project: Steamshots-master  File: ChannelEncryptRequestIncoming.java View source code
@Override
void fromRaw(byte[] data) throws IncomingException {
    try {
        @SuppressWarnings("resource") LittleEndianDataInputStream stream = new LittleEndianDataInputStream(new ByteArrayInputStream(data));
        mProtocolVersion = stream.readInt();
        mUniverse = stream.readInt();
    } catch (IOException e) {
        throw new IncomingException();
    }
}
Example 23
Project: Tapestry-5-Portlet-master  File: Contact.java View source code
public Object onActivate() {
    return new StreamResponse() {

        public String getContentType() {
            // TODO Auto-generated method stub
            return "application/zip";
        }

        public InputStream getStream() throws IOException {
            return new ByteArrayInputStream(new String("hellohello").getBytes());
        }

        public void prepareResponse(Response arg0) {
        // TODO Auto-generated method stub
        }
    };
}
Example 24
Project: titl-master  File: TestInputImpl.java View source code
@Test
public void getPositionReflectsReading() throws IOException {
    Input in = new InputImpl(new ByteArrayInputStream(new byte[1024]));
    assertEquals(0, in.getPosition());
    in.readUnsignedByte();
    assertEquals(1, in.getPosition());
    in.readShort();
    assertEquals(3, in.getPosition());
    in.readInt();
    assertEquals(7, in.getPosition());
    in.readFully(new byte[1]);
    assertEquals(8, in.getPosition());
    in.skipBytes(1);
    assertEquals(9, in.getPosition());
}
Example 25
Project: tjungblut-online-ml-master  File: TestBayesianProbabilityModel.java View source code
@Test
public void testSerDe() throws Exception {
    BayesianProbabilityModel model = TestNaiveBayesLearner.getTrainedModel();
    TestNaiveBayesLearner.checkModel(model);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    model.serialize(dos);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DataInputStream dis = new DataInputStream(bais);
    model = new BayesianProbabilityModel();
    BayesianProbabilityModel deserialized = model.deserialize(dis);
    TestNaiveBayesLearner.checkModel(deserialized);
}
Example 26
Project: tradeinbooks-master  File: XMLUnmarshaller.java View source code
public ISBNdb unmarshall(String xmlString) {
    //i added
    ISBNdb jaxbObject = null;
    try {
        ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes());
        JAXBContext jc = JAXBContext.newInstance("com.isbndb.beans");
        Unmarshaller u = jc.createUnmarshaller();
        jaxbObject = (ISBNdb) u.unmarshal(input);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    //i added
    return jaxbObject;
}
Example 27
Project: triaina-master  File: DigestUtilsTest.java View source code
public void testDigestStringInputStream() {
    byte[] digest = DigestUtils.digest(DigestUtils.SHA256, new ByteArrayInputStream("aaa".getBytes()));
    assertEquals(32, digest.length);
    StringBuilder builder = new StringBuilder();
    for (byte b : digest) {
        builder.append(String.format("%02x", b));
    }
    assertEquals("9834876dcfb05cb167a5c24953eba58c4ac89b1adf57f28f2f9d09af107ee8f0", builder.toString());
}
Example 28
Project: updates-r-simple-master  File: DataImporterTest.java View source code
@Test
public void closesStreamAfterOperation() throws Exception {
    ByteArrayInputStream stream = spy(new ByteArrayInputStream("Hallo".getBytes()));
    InputStreamFactory factory = mock(InputStreamFactory.class);
    when(factory.openStream()).thenReturn(stream);
    new DataImporter(factory).importTo(folder.getRoot(), "Test");
    verify(stream).close();
}
Example 29
Project: url-scheme-registry-master  File: Handler.java View source code
@Override
protected URLConnection openConnection(URL u) throws IOException {
    final String breakfast = u.getHost();
    return new URLConnection(u) {

        @Override
        public void connect() throws IOException {
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(breakfast.getBytes());
        }
    };
}
Example 30
Project: wayback-machine-master  File: GZIPMemberWriterTest.java View source code
public void testWrite() throws IOException {
    String outPath = "/tmp/tmp.gz";
    GZIPMemberWriter gzw = new GZIPMemberWriter(new FileOutputStream(new File(outPath)));
    gzw.write(new ByteArrayInputStream("Here is record 1".getBytes(IAUtils.UTF8)));
    gzw.write(new ByteArrayInputStream("Here is record 2".getBytes(IAUtils.UTF8)));
}
Example 31
Project: webarchive-commons-master  File: GZIPMemberWriterTest.java View source code
public void testWrite() throws IOException {
    File outFile = File.createTempFile("tmp", ".gz");
    GZIPMemberWriter gzw = new GZIPMemberWriter(new FileOutputStream(outFile));
    gzw.write(new ByteArrayInputStream("Here is record 1".getBytes(IAUtils.UTF8)));
    gzw.write(new ByteArrayInputStream("Here is record 2".getBytes(IAUtils.UTF8)));
}
Example 32
Project: android-libcore64-master  File: OldByteArrayInputStreamTest.java View source code
public void test_Constructor$B() {
    // Test for method java.io.ByteArrayInputStream(byte [])
    java.io.InputStream bis = new java.io.ByteArrayInputStream(fileString.getBytes());
    try {
        assertTrue("Unable to create ByteArrayInputStream", bis.available() == fileString.length());
    } catch (Exception e) {
        System.out.println("Exception during Constructor test");
    }
}
Example 33
Project: android_platform_libcore-master  File: OldByteArrayInputStreamTest.java View source code
public void test_Constructor$B() {
    // Test for method java.io.ByteArrayInputStream(byte [])
    java.io.InputStream bis = new java.io.ByteArrayInputStream(fileString.getBytes());
    try {
        assertTrue("Unable to create ByteArrayInputStream", bis.available() == fileString.length());
    } catch (Exception e) {
        System.out.println("Exception during Constructor test");
    }
}
Example 34
Project: ARTPart-master  File: OldByteArrayInputStreamTest.java View source code
public void test_Constructor$B() {
    // Test for method java.io.ByteArrayInputStream(byte [])
    java.io.InputStream bis = new java.io.ByteArrayInputStream(fileString.getBytes());
    try {
        assertTrue("Unable to create ByteArrayInputStream", bis.available() == fileString.length());
    } catch (Exception e) {
        System.out.println("Exception during Constructor test");
    }
}
Example 35
Project: j2objc-master  File: OldByteArrayInputStreamTest.java View source code
public void test_Constructor$B() {
    // Test for method java.io.ByteArrayInputStream(byte [])
    java.io.InputStream bis = new java.io.ByteArrayInputStream(fileString.getBytes());
    try {
        assertTrue("Unable to create ByteArrayInputStream", bis.available() == fileString.length());
    } catch (Exception e) {
        System.out.println("Exception during Constructor test");
    }
}
Example 36
Project: robovm-master  File: OldByteArrayInputStreamTest.java View source code
public void test_Constructor$B() {
    // Test for method java.io.ByteArrayInputStream(byte [])
    java.io.InputStream bis = new java.io.ByteArrayInputStream(fileString.getBytes());
    try {
        assertTrue("Unable to create ByteArrayInputStream", bis.available() == fileString.length());
    } catch (Exception e) {
        System.out.println("Exception during Constructor test");
    }
}
Example 37
Project: alien4cloud-master  File: UpdateFileContentProcessor.java View source code
@Override
public void process(UpdateFileContentOperation operation) {
    if (operation.getTempFileId() == null) {
        operation.setArtifactStream(new ByteArrayInputStream(operation.getContent().getBytes(StandardCharsets.UTF_8)));
    }
    super.process(operation);
    // content is store in a temp file on disk, no need to keep data in memory.
    operation.setContent(null);
}
Example 38
Project: android-google-spreadsheets-api-master  File: WorksheetEntryRequest.java View source code
@Override
protected Response<WorksheetEntry> parseNetworkResponse(NetworkResponse response) {
    try {
        WorksheetEntry entry = parser.parseAndClose(new InputStreamReader(new ByteArrayInputStream(response.data)), WorksheetEntry.class);
        return Response.success(entry, HttpHeaderParser.parseCacheHeaders(response));
    } catch (IOException e) {
        return Response.error(new ParseError(e));
    }
}
Example 39
Project: aorra-master  File: FileTest.java View source code
@Test
public void createDigest() {
    final String name = "test.txt";
    final String mime = "text/plain";
    final InputStream data = new ByteArrayInputStream("Test content.".getBytes());
    final String expectedSHA512 = "4e166f63a5a427c0c76c756642a4743f13635a575cd990f11069295a55785d49" + "b9a3cc0e5ee1bafa79d5252d03abcc19548d00ae0db20af391fc1e8e3156d606";
    File f = new File(null, name, mime, data);
    assertThat(f.getDigest()).isEqualTo(expectedSHA512);
}
Example 40
Project: apps-android-wikipedia-master  File: OkHttpWebViewClientTest.java View source code
@Test
public void testTransformSvgFile() throws Throwable {
    String badSVG = TestFileUtil.readRawFile("emc2_with_ex_units.svg");
    String goodSVG = TestFileUtil.readRawFile("emc2_with_em_units.svg");
    String transformedBadSVG = TestFileUtil.readStream(OkHttpWebViewClient.transformSvgFile(new ByteArrayInputStream(badSVG.getBytes())));
    String transformedGoodSVG = TestFileUtil.readStream(OkHttpWebViewClient.transformSvgFile(new ByteArrayInputStream(goodSVG.getBytes())));
    assertThat(transformedBadSVG, is(transformedGoodSVG));
}
Example 41
Project: archistar-core-master  File: CustomSerializer.java View source code
@Override
public FSObject deserialize(byte[] data) {
    if (data == null) {
        return null;
    }
    try (ObjectInputStream reader = new ObjectInputStream(new ByteArrayInputStream(data))) {
        return (FSObject) reader.readObject();
    } catch (IOExceptionClassNotFoundException |  e) {
        assert (false);
    }
    return null;
}
Example 42
Project: Aspose_Words_Java-master  File: LoadDocFromDatabase.java View source code
public static void main(String[] args) throws Exception {
    // Retrieve the blob from database
    byte[] buffer = new byte[100];
    // Now we have the document in a byte array buffer
    // Create an input steam which uses byte array to read data
    ByteArrayInputStream bin = new ByteArrayInputStream(buffer);
// Open the doucment from input stream
//Document doc = new Document(bin);
}
Example 43
Project: azazello-master  File: TikaFunction.java View source code
@Override
public Document call(Document doc) throws Exception {
    // enrich the behemoth document by adding its text + other metadata
    // obtained from Tika
    String mimeType = tika.detect(doc.getBinaryContent(), doc.getUri());
    InputStream is = new ByteArrayInputStream(doc.getBinaryContent());
    doc.setText(tika.parseToString(is));
    is.close();
    return doc;
}
Example 44
Project: bootique-master  File: JsonNodeYamlParserTest.java View source code
@Test
public void testApply() {
    InputStream in = new ByteArrayInputStream("a: b\nb: c".getBytes());
    ObjectMapper mapper = new ObjectMapper();
    Optional<JsonNode> node = new JsonNodeYamlParser(mapper).apply(in);
    assertTrue(node.isPresent());
    assertEquals("b", node.get().get("a").asText());
    assertEquals("c", node.get().get("b").asText());
}
Example 45
Project: brigen-base-master  File: ZxingUtilsTest.java View source code
@Test
public void test() throws IOException {
    ZxingBuilder builder = ZxingUtils.builder();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    builder.buildEncoder("hoge").encode(bao);
    assertTrue(builder.buildEncoder("hoge").encode() instanceof BufferedImage);
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bao.toByteArray()));
    BufferedImageDecodeArguments arg = new BufferedImageDecodeArguments(image);
    assertNotEquals("foo", builder.buildDecoder().decode(arg));
    assertEquals("hoge", builder.buildDecoder().decode(arg));
}
Example 46
Project: cistern-master  File: Copy.java View source code
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T object) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    try {
        ObjectInputStream ois = new ObjectInputStream(bais);
        return (T) ois.readObject();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
Example 47
Project: cobertura-plugin-master  File: CoveragePaintTest.java View source code
public void testSerializable() throws Exception {
    CoveragePaint instance = new CoveragePaint(CoverageElement.JAVA_FILE);
    instance.paint(5, 7, 4, 5);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(instance);
    oos.flush();
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bis);
    CoveragePaint copy = (CoveragePaint) ois.readObject();
    assertEquals(instance.getLineCoverage(), copy.getLineCoverage());
    assertEquals(instance.getConditionalCoverage(), copy.getConditionalCoverage());
}
Example 48
Project: com.idega.content-master  File: ThemesEntityResolver.java View source code
public InputSource resolveEntity(String publicID, String systemID) throws SAXException, IOException {
    if (publicID == null || systemID == null) {
        return null;
    }
    for (int i = 0; i < ThemesConstants.DOCUMENT_PUBLIC_IDS.size(); i++) {
        if (publicID.indexOf(ThemesConstants.DOCUMENT_PUBLIC_IDS.get(i)) != -1 && systemID.indexOf(ThemesConstants.DOCUMENT_SYSTEM_IDS.get(i)) != -1) {
            return new InputSource(new ByteArrayInputStream(ThemesConstants.DOCUMENT_HEADER.getBytes()));
        }
    }
    return null;
}
Example 49
Project: cotta-master  File: InputTest.java View source code
public void testWStaticFactorySupportsPath() throws TIoException {
    InputStream stream = new ByteArrayInputStream(new byte[0]);
    Input.with(stream).read(new InputProcessor() {

        public void process(InputManager inputManager) throws IOException {
            try {
                inputManager.reader("aoeuaoeuaoeu");
                fail("should have thrown exception for wrong encoding");
            } catch (TIoException e) {
                ensure.that(e).message().contains("input stream");
            }
        }
    });
}
Example 50
Project: craken-master  File: TestSerializeJson.java View source code
public void testWrite() throws Exception {
    PropertyValue sjson = PropertyValue.createPrimitive(new Date());
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(bout);
    oout.writeObject(sjson);
    ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
    PropertyValue read = (PropertyValue) oin.readObject();
    Debug.line(read.value());
}
Example 51
Project: Crawer-master  File: ParseXML.java View source code
public static String ParsingXML(String in) throws Exception {
    //校验
    if (in == null || "".equals(in))
        return "";
    //获�顶级element
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document document = builder.parse(new ByteArrayInputStream(in.getBytes()));
    return "";
}
Example 52
Project: cruisecontrol-master  File: CommandExecutorTest.java View source code
public Process execute() throws IOException {
    MockProcess returnNonZeroProcess = new MockProcess(new ByteArrayOutputStream());
    returnNonZeroProcess.setExitValue(-1);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[0]);
    returnNonZeroProcess.setErrorStream(inputStream);
    returnNonZeroProcess.setInputStream(inputStream);
    return returnNonZeroProcess;
}
Example 53
Project: dashreports-master  File: GetLogo.java View source code
@Override
public String execute() throws Exception {
    byte[] imageData = configurationService.getConfigurationItem(ConfigurationType.LOGO).getBinaryValue();
    if (imageData != null) {
        this.inputStream = new ByteArrayInputStream(imageData);
    } else {
        this.inputStream = new ByteArrayInputStream(new byte[0]);
    }
    return SUCCESS;
}
Example 54
Project: databus-master  File: CompressUtil.java View source code
public static String uncompress(String str) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
    GZIPInputStream gunzip = new GZIPInputStream(in);
    byte[] buffer = new byte[256];
    int n;
    while ((n = gunzip.read(buffer)) >= 0) {
        out.write(buffer, 0, n);
    }
    return out.toString(Charset.defaultCharset().name());
}
Example 55
Project: DocBleach-master  File: OLE2BleachTest.java View source code
@Test
void handlesMagic() throws IOException {
    Charset charset = Charset.defaultCharset();
    // Check that empty does not trigger an error
    InputStream invalidInputStream = new ByteArrayInputStream("".getBytes(charset));
    assertFalse(instance.handlesMagic(invalidInputStream));
    // Check that this bleach is sane
    invalidInputStream = new ByteArrayInputStream("Anything".getBytes(charset));
    assertFalse(instance.handlesMagic(invalidInputStream));
}
Example 56
Project: ebean-master  File: ModifyAwareFlagTest.java View source code
@Test
public void serialise() throws IOException, ClassNotFoundException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    ModifyAwareFlag flag = new ModifyAwareFlag();
    flag.markAsModified();
    oos.writeObject(flag);
    oos.flush();
    oos.close();
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(is);
    ModifyAwareFlag read = (ModifyAwareFlag) ois.readObject();
    assertThat(read.isMarkedDirty()).isTrue();
}
Example 57
Project: eureka-master  File: AmazonInfoTest.java View source code
@Test
public void testExtractAccountId() throws Exception {
    String json = "{\n" + "  \"imageId\" : \"ami-someId\",\n" + "  \"instanceType\" : \"m1.small\",\n" + "  \"version\" : \"2000-00-00\",\n" + "  \"architecture\" : \"x86_64\",\n" + "  \"accountId\" : \"1111111111\",\n" + "  \"instanceId\" : \"i-someId\",\n" + "  \"billingProducts\" : null,\n" + "  \"pendingTime\" : \"2000-00-00T00:00:00Z\",\n" + "  \"availabilityZone\" : \"us-east-1c\",\n" + "  \"region\" : \"us-east-1\",\n" + "  \"kernelId\" : \"aki-someId\",\n" + "  \"ramdiskId\" : null,\n" + "  \"privateIp\" : \"1.1.1.1\"\n" + "}";
    InputStream inputStream = new ByteArrayInputStream(json.getBytes());
    String accountId = AmazonInfo.MetaDataKey.accountId.read(inputStream);
    assertEquals("1111111111", accountId);
}
Example 58
Project: fast-http-master  File: TestJsonDeserializer.java View source code
@Test
public void testReadingMap() throws Exception {
    InputStream in = new ByteArrayInputStream("{\"firstkey\":1,\"secondkey\":2}".getBytes("UTF-8"));
    JsonDeserializer d = new JsonDeserializer(new JsonFactory(new ObjectMapper()), in);
    Map<String, Object> deserialized = d.readMap();
    assertThat(deserialized.containsKey("firstkey"), is(true));
    assertThat(deserialized.containsKey("secondkey"), is(true));
    assertThat((Integer) deserialized.get("firstkey"), is(1));
    assertThat((Integer) deserialized.get("secondkey"), is(2));
}
Example 59
Project: fastcatsearch-master  File: DataIOTest.java View source code
@Test
public void test() throws IOException {
    String str = "abcdefghijk1234567한글입니다.1111日本語 ( ��ん�";
    System.out.println(str);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutput output = new OutputStreamDataOutput(baos);
    output.writeString(str);
    output.flush();
    byte[] buffer = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
    DataInput input = new InputStreamDataInput(bais);
    String actual = input.readString();
    System.out.println(actual);
    assertTrue(actual.equals(str));
}
Example 60
Project: flashback-master  File: AbstractDecompressor.java View source code
public byte[] decompress(byte[] encodedBytes) throws IOException {
    byte[] decompressedBytes;
    try (InputStream stream = getInputStream(new ByteArrayInputStream(encodedBytes));
        ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        int bytesRead;
        byte[] decodedData = new byte[1024];
        while ((bytesRead = stream.read(decodedData)) != -1) {
            out.write(decodedData, 0, bytesRead);
        }
        out.flush();
        decompressedBytes = out.toByteArray();
    }
    return decompressedBytes;
}
Example 61
Project: framework-master  File: InnerClassDesignReadWriteTest.java View source code
@Test
public void testWritingAndReadingBackInnerClass() throws IOException {
    VerticalLayout vl = new VerticalLayout();
    vl.addComponent(new StaticInner());
    vl.addComponent(new StaticInnerInner());
    vl.addComponent(new InUpperCasePackage());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Design.write(vl, baos);
    Design.read(new ByteArrayInputStream(baos.toByteArray()));
}
Example 62
Project: Fudan-Sakai-master  File: PortletStateTest.java View source code
public void testSerialization() throws IOException, ClassNotFoundException {
    PortletState state = new PortletState("id");
    state.setPortletMode(PortletMode.VIEW);
    state.setWindowState(WindowState.MAXIMIZED);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bao);
    out.writeObject(state);
    ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bai);
    PortletState alter = (PortletState) in.readObject();
    assertEquals(state, alter);
}
Example 63
Project: geoserver-old-master  File: NativeTypeParsingTest.java View source code
public void testParse() throws Exception {
    Parser p = new Parser(getXmlConfiguration11());
    NativeType nativ = (NativeType) p.parse(new ByteArrayInputStream("<wfs:Native safeToIgnore='true' xmlns:wfs='http://www.opengis.net/wfs'>here is some text</wfs:Native>".getBytes()));
    assertEquals("here is some text", nativ.getValue());
}
Example 64
Project: geoserver_trunk-master  File: NativeTypeParsingTest.java View source code
public void testParse() throws Exception {
    Parser p = new Parser(getXmlConfiguration11());
    NativeType nativ = (NativeType) p.parse(new ByteArrayInputStream("<wfs:Native safeToIgnore='true' xmlns:wfs='http://www.opengis.net/wfs'>here is some text</wfs:Native>".getBytes()));
    assertEquals("here is some text", nativ.getValue());
}
Example 65
Project: ggp-base-master  File: BaseHashing.java View source code
// Computes the SHA1 hash of a given input string, and represents
// that hash as a hexadecimal string.
public static String computeSHA1Hash(String theData) {
    try {
        MessageDigest SHA1 = MessageDigest.getInstance("SHA1");
        DigestInputStream theDigestStream = new DigestInputStream(new BufferedInputStream(new ByteArrayInputStream(theData.getBytes("UTF-8"))), SHA1);
        while (theDigestStream.read() != -1) ;
        byte[] theHash = SHA1.digest();
        Formatter hexFormat = new Formatter();
        for (byte x : theHash) {
            hexFormat.format("%02x", x);
        }
        String theHex = hexFormat.toString();
        hexFormat.close();
        return theHex;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Example 66
Project: ggpserver-master  File: LengthInputStreamTest.java View source code
/*
     * Test method for 'camembert.util.LengthInputStream.read()'
     */
public void testRead() throws IOException {
    String buffer = "Hello this is a very friendly little buffer";
    ByteArrayInputStream input = new ByteArrayInputStream(buffer.getBytes());
    LengthInputStream lis = new LengthInputStream(input, 20);
    StringBuilder result = new StringBuilder();
    int c;
    while ((c = lis.read()) != -1) {
        result.append((char) c);
    }
    assertEquals(buffer.substring(0, 20), result.toString());
}
Example 67
Project: graylog-plugin-output-webhdfs-master  File: Main.java View source code
public static void main(String args[]) throws Exception {
    WebHDFSConnection connection = new WebHDFSConnection("http://localhost:50070", "hadoopuser", "anything", AuthenticationType.PSEUDO);
    //System.out.println(connection.listStatus("user/hadoopuser"));
    System.out.print(connection.getHomeDirectory());
    ByteArrayInputStream stream = new ByteArrayInputStream("India is my Country".getBytes());
    System.out.println(connection.append("tmp/india2.txt", stream));
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    System.out.println(connection.open("tmp/india2.txt", os));
    System.out.println(new String(os.toByteArray()));
}
Example 68
Project: hive-hll-udf-master  File: UDFHyperLogLogValue.java View source code
public LongWritable evaluate(BytesWritable bw) throws HiveException {
    if (bw == null) {
        return new LongWritable(0);
    }
    ByteArrayInputStream input = new ByteArrayInputStream(bw.getBytes(), 0, bw.getLength());
    final HyperLogLog hll;
    try {
        hll = HyperLogLogUtils.deserializeHLL(input);
    } catch (IOException ioe) {
        throw new HiveException(ioe);
    }
    return new LongWritable(hll.count());
}
Example 69
Project: hudson_plugins-master  File: CoveragePaintTest.java View source code
public void testSerializable() throws Exception {
    CoveragePaint instance = new CoveragePaint(CoverageElement.JAVA_FILE);
    instance.paint(5, 7, 4, 5);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(instance);
    oos.flush();
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bis);
    CoveragePaint copy = (CoveragePaint) ois.readObject();
    assertEquals(instance.getLineCoverage(), copy.getLineCoverage());
    assertEquals(instance.getConditionalCoverage(), copy.getConditionalCoverage());
}
Example 70
Project: i2p.i2p-master  File: RateTest.java View source code
@Test
public void testRate() throws Exception {
    Rate rate = new Rate(5000);
    for (int i = 0; i < 50; i++) {
        Thread.sleep(20);
        rate.addData(i * 100, 20);
    }
    rate.coalesce();
    StringBuilder buf = new StringBuilder(1024);
    rate.store("rate.test", buf);
    byte data[] = DataHelper.getUTF8(buf.toString());
    Properties props = new Properties();
    props.load(new ByteArrayInputStream(data));
    Rate r = new Rate(props, "rate.test", true);
    assertEquals(r, rate);
}
Example 71
Project: ia-hadoop-tools-master  File: ZipNumBlockIterator.java View source code
public CloseableIterator<String> iterator() throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
    OpenJDK7GZIPInputStream gzis = new OpenJDK7GZIPInputStream(bais);
    InputStreamReader isr = new InputStreamReader(gzis);
    BufferedReader br = new BufferedReader(isr);
    return AbstractPeekableIterator.wrapReader(br);
}
Example 72
Project: ImageTools-master  File: SetImageFromDatabase.java View source code
/**
	 * Gets an image from the Database
	 */
private void getImagefromDB() {
    //TODO get from the database
    try {
        //the byte array to be retrieved from the database
        byte[] imgbytes = new byte[10];
        //perform the select
        //the byte array input stream
        InputStream bis = new ByteArrayInputStream(imgbytes);
        image.setImage(ImageIO.read(bis));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 73
Project: infinispan-master  File: SignedNumericTest.java View source code
private void encodeDecode(int value, int expectedSize) throws IOException {
    try (ByteArrayOutputStream os = new ByteArrayOutputStream(5)) {
        SignedNumeric.writeSignedInt(os, value);
        byte[] bytes = os.toByteArray();
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            int read = SignedNumeric.readSignedInt(is);
            assertEquals(read, value);
        }
        assertEquals(bytes.length, expectedSize);
    }
}
Example 74
Project: InSpider-master  File: Handler.java View source code
@Override
protected URLConnection openConnection(URL u) throws IOException {
    incrementCounter();
    return new URLConnection(u) {

        @Override
        public void connect() throws IOException {
            if (url.getFile().toLowerCase().contains("404")) {
                throw new IOException();
            }
        }

        @Override
        public InputStream getInputStream() throws IOException {
            connect();
            if (url.getFile().toLowerCase().contains("empty")) {
                return new ByteArrayInputStream("".getBytes("utf-8"));
            }
            return new ByteArrayInputStream(url.toExternalForm().getBytes("utf-8"));
        }
    };
}
Example 75
Project: iterator-master  File: TestBoolean.java View source code
@org.junit.experimental.categories.Category(StreamingCategory.class)
public void test_streaming() throws IOException {
    JsonIterator iter = JsonIterator.parse(new ByteArrayInputStream("[true,false,null,true]".getBytes()), 3);
    iter.readArray();
    assertTrue(iter.readBoolean());
    iter.readArray();
    assertFalse(iter.readBoolean());
    iter.readArray();
    assertTrue(iter.readNull());
    iter.readArray();
    assertTrue(iter.readBoolean());
}
Example 76
Project: jaudiotagger-master  File: ContentBrandingData.java View source code
public void testContentBrandingWriteRead() throws IOException {
    ContentBranding cb = new ContentBranding();
    cb.setCopyRightURL("CP URL");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    cb.writeInto(bos);
    assertEquals(cb.getCurrentAsfChunkSize(), bos.toByteArray().length);
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    assertEquals(GUID.GUID_CONTENT_BRANDING, Utils.readGUID(bis));
    ContentBranding read = (ContentBranding) new ContentBrandingReader().read(GUID.GUID_CONTENT_BRANDING, bis, 0);
    MetadataContainerUtils.equals(cb, read);
}
Example 77
Project: java-core-learning-example-master  File: FormatteMemoryInput.java View source code
public static void main(String[] args) throws IOException {
    String filePath = "src" + File.separator + "org" + File.separator + "javacore" + File.separator + "io" + File.separator + "FormatteMemoryInput.java";
    try {
        DataInputStream in = new DataInputStream(// 缓冲区字节输入
        new ByteArrayInputStream(BufferedInputFileT.read(filePath).getBytes()));
        while (true) System.out.println((char) in.readByte());
    } catch (EOFException e) {
        System.out.println("End of Stream");
    }
}
Example 78
Project: java-core-test-master  File: TestXMLMarshalling.java View source code
public static void main(String[] args) throws Exception {
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(1000);
    JAXBContext context = JAXBContext.newInstance(TestObject.class);
    Marshaller marshaller = context.createMarshaller();
    TestObject marshalledObject = new TestObject();
    marshalledObject.setObjectName("Hoang loves Trang very much");
    marshaller.marshal(marshalledObject, arrayOutputStream);
    System.out.println(arrayOutputStream.toString());
    Unmarshaller unmarshaller = context.createUnmarshaller();
    ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());
    TestObject object = (TestObject) unmarshaller.unmarshal(arrayInputStream);
    System.out.println("Test object: " + object.getObjectName());
}
Example 79
Project: jbosstools-maven-plugins-master  File: XsltTest.java View source code
@Test
public void testSiteProperties() throws Exception {
    InputStream siteXsl = GenerateRepositoryFacadeMojo.class.getResourceAsStream("/xslt/site.properties.xsl");
    Source xsltSource = new StreamSource(siteXsl);
    Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Result res = new StreamResult(out);
    transformer.transform(new StreamSource(new ByteArrayInputStream("<site/>".getBytes())), res);
    siteXsl.close();
    out.close();
}
Example 80
Project: jdroid-master  File: CopyUtils.java View source code
@SuppressWarnings("unchecked")
public static <T extends Serializable> T cloneSerializable(T object) {
    T cloneObject;
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oout = new ObjectOutputStream(bout);
        oout.writeObject(object);
        byte[] bytes = bout.toByteArray();
        oout.close();
        ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
        ObjectInputStream oin = new ObjectInputStream(bin);
        cloneObject = (T) oin.readObject();
        oin.close();
    } catch (IOExceptionClassNotFoundException |  e) {
        throw new UnexpectedException("Failed to clone " + object.getClass().getSimpleName() + " using serialization", e);
    }
    return cloneObject;
}
Example 81
Project: JECommons-master  File: StringInputHandler.java View source code
//input is List<List<String>>
@Override
public void convertInput() {
    System.out.println("--convertiere String input--");
    List<String> input = (List<String>) _rawInput;
    for (String o : input) {
        //            List tmp = (List) o;
        //            for (Object m : tmp) {
        //                String s = (String) m;
        //            System.out.println("Value beim convert "+m);
        _inputStream.add(new ByteArrayInputStream(o.getBytes()));
    //            }
    }
    System.out.println("Inputstream size " + _inputStream.size());
}
Example 82
Project: Kaspar-master  File: ParseTemplatesRequest.java View source code
@Override
public Document request(MediaWikiConnection c) throws Exception {
    MediaWikiPostRequest p = new MediaWikiPostRequest(c);
    p.putData(getProperties());
    p.putData("action", "expandtemplates");
    p.putData("includecomments", "0");
    p.putData("prop", "parsetree");
    Document d = p.requestDocument();
    String t = d.getRootElement().getChildren("expandtemplates").get(0).getChildren("parsetree").get(0).getText();
    Document d2 = Document.load(new ByteArrayInputStream(t.getBytes()));
    return d2;
}
Example 83
Project: LEADT-master  File: MusicAlbumData.java View source code
public InputStream getMusicFromRecordStore(String recordStore, String musicName) throws ImageNotFoundException, PersistenceMechanismException {
    MediaData mediaInfo = null;
    mediaInfo = mediaAccessor.getMediaInfo(musicName);
    //Find the record ID and store name of the image to retrieve
    int mediaId = mediaInfo.getForeignRecordId();
    String album = mediaInfo.getParentAlbumName();
    //Now, load the image (on demand) from RMS and cache it in the hashtable
    byte[] musicData = (mediaAccessor).loadMediaBytesFromRMS(album, mediaId);
    return new ByteArrayInputStream(musicData);
}
Example 84
Project: LGA-master  File: ZipUtils.java View source code
public static void writeByteArrayToZipEntry(ZipOutputStream zipOutputStream, ZipEntry zipEntry, byte[] bytesToWrite) throws IOException {
    zipOutputStream.putNextEntry(zipEntry);
    byte[] buffer = new byte[1024];
    ByteArrayInputStream bis = new ByteArrayInputStream(bytesToWrite);
    int length;
    while ((length = bis.read(buffer)) > 0) {
        zipOutputStream.write(buffer, 0, length);
    }
    zipOutputStream.closeEntry();
}
Example 85
Project: LGame-master  File: ZipUtils.java View source code
public static void writeByteArrayToZipEntry(ZipOutputStream zipOutputStream, ZipEntry zipEntry, byte[] bytesToWrite) throws IOException {
    zipOutputStream.putNextEntry(zipEntry);
    byte[] buffer = new byte[1024];
    ByteArrayInputStream bis = new ByteArrayInputStream(bytesToWrite);
    int length;
    while ((length = bis.read(buffer)) > 0) {
        zipOutputStream.write(buffer, 0, length);
    }
    zipOutputStream.closeEntry();
}
Example 86
Project: login-server-master  File: ConfigMetadataProvider.java View source code
@Override
protected XMLObject doGetMetadata() throws MetadataProviderException {
    InputStream stream = new ByteArrayInputStream(metadata.getBytes(StandardCharsets.UTF_8));
    try {
        return unmarshallMetadata(stream);
    } catch (UnmarshallingException e) {
        log.error("Unable to unmarshall metadata", e);
        throw new MetadataProviderException(e);
    }
}
Example 87
Project: lzo-index-master  File: LzoIndexerTestCase.java View source code
public void testShouldCreateIndex() throws IOException, DataFormatException {
    String[] resources = new String[] { "100.txt.lzo", "1000.txt.lzo", "100000.txt.lzo" };
    for (String resource : resources) {
        InputStream lzo = getClass().getClassLoader().getResourceAsStream(resource);
        InputStream index_expected = getClass().getClassLoader().getResourceAsStream(resource + ".index");
        ByteArrayOutputStream index = new ByteArrayOutputStream();
        LzoIndexer indexer = new LzoIndexer();
        indexer.createIndex(lzo, index);
        index.close();
        lzo.close();
        InputStream index_actual = new ByteArrayInputStream(index.toByteArray());
        IOUtils.contentEquals(index_expected, index_actual);
    }
}
Example 88
Project: map-engine-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    Engine engine = new Engine(Engine.class.getClassLoader().getResourceAsStream("create_catalog_directives.xml"));
    StringBuilder xml = new StringBuilder();
    byte[] buffer = new byte[4096];
    int readed = 0;
    try (BufferedInputStream bis = new BufferedInputStream(Main.class.getClassLoader().getResourceAsStream("in.xml"))) {
        while ((readed = bis.read(buffer)) != -1) {
            xml.append(new String(buffer, 0, readed));
        }
    }
    @SuppressWarnings("unchecked") List<Catalog> result = (List<Catalog>) engine.run(new ByteArrayInputStream(xml.toString().getBytes()));
    for (Catalog catalog : result) {
        System.out.println(catalog);
    }
    engine.shutdown();
}
Example 89
Project: maplets-master  File: TestGeoNameFactory.java View source code
public void testParseXML() throws Exception {
    String xml = "<geonames><geoname>" + "<name>Rathgar</name>" + "<lat>53.3145699871472</lat>" + "<lng>-6.27499580383301</lng>" + "<geonameId>3315287</geonameId>" + "<countryCode>IE</countryCode>" + "<countryName>Ireland</countryName>" + "<fcl>P</fcl>" + "<fcode>PPL</fcode>" + "<distance>0.3725</distance>" + "</geoname></geonames>";
    ByteArrayInputStream input = new ByteArrayInputStream(xml.getBytes());
    GeoName name = fact.fromXML(input);
    assertNotNull(name);
    assertEquals("Rathgar", name.getName());
    assertEquals("53.3145699871472", name.getLatitude());
    assertEquals("-6.27499580383301", name.getLongitude());
    assertEquals("3315287", name.getGeoNameId());
    assertEquals("IE", name.getCountryCode());
    assertEquals("Ireland", name.getCountryName());
    assertEquals("P", name.getFeatureClass());
    assertEquals("PPL", name.getFeatureCode());
    assertEquals("0.3725", name.getDistance());
}
Example 90
Project: marytts-master  File: PropertiesTrimTrailingWhitespace.java View source code
/**
	 * removes trailing whitespace
	 */
public void load(InputStream fis) throws IOException {
    Scanner in = new Scanner(fis);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while (in.hasNext()) {
        out.write(in.nextLine().trim().getBytes());
        out.write("\n".getBytes());
    }
    in.close();
    InputStream is = new ByteArrayInputStream(out.toByteArray());
    super.load(is);
}
Example 91
Project: mbit-cloud-platform-master  File: ConfigMetadataProvider.java View source code
@Override
protected XMLObject doGetMetadata() throws MetadataProviderException {
    InputStream stream = new ByteArrayInputStream(metadata.getBytes(StandardCharsets.UTF_8));
    try {
        return unmarshallMetadata(stream);
    } catch (UnmarshallingException e) {
        log.error("Unable to unmarshall metadata", e);
        throw new MetadataProviderException(e);
    }
}
Example 92
Project: Mint-master  File: EDM2RDFTransform.java View source code
@Override
public String transform(String input) {
    String edmxml = input;
    String rdf = null;
    try {
        byte[] bytes = edmxml.getBytes();
        InputStream inputStream = new ByteArrayInputStream(bytes);
        gr.ntua.ivml.mint.rdf.edm.EDM2RDF xml2rdf = new gr.ntua.ivml.mint.rdf.edm.EDM2RDF(inputStream);
        ByteArrayOutputStream outputStream = xml2rdf.convertToRDF();
        String edmrdf = outputStream.toString();
        rdf = edmrdf;
    } catch (Exception e) {
        rdf = e.getMessage();
    }
    return rdf;
}
Example 93
Project: miracle-framework-master  File: AsyncEncodeAndDecodeCallable.java View source code
@Override
public Integer call() throws Exception {
    KryoSerialization kryoSerialization = new KryoSerialization(kyroFactory);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    kryoSerialization.serialize(byteArrayOutputStream, value);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return (Integer) kryoSerialization.deserialize(byteArrayInputStream);
}
Example 94
Project: molgenis-master  File: SchemaLoaderTest.java View source code
@Test
public void getSchemaFromInputStream() throws IOException {
    String schemaStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"></xs:schema>";
    InputStream bis = new ByteArrayInputStream(schemaStr.getBytes("UTF-8"));
    try {
        SchemaLoader schemaLoader = new SchemaLoader(bis);
        assertNotNull(schemaLoader.getSchema());
    } finally {
        bis.close();
    }
}
Example 95
Project: msgpack-java-0.7-master  File: TestUnpackerIterator.java View source code
@Test
public void testSample() throws Exception {
    MessagePack msgpack = new MessagePack();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Packer packer = msgpack.createPacker(out);
    packer.write(1);
    packer.write(2);
    packer.write(3);
    byte[] bytes = out.toByteArray();
    Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes));
    UnpackerIterator iter = unpacker.iterator();
    unpacker.resetReadByteCount();
    iter.hasNext();
    iter.next();
    assertEquals(1, unpacker.getReadByteCount());
    unpacker.resetReadByteCount();
    iter.hasNext();
    iter.next();
    assertEquals(1, unpacker.getReadByteCount());
    unpacker.resetReadByteCount();
    iter.hasNext();
    iter.next();
    assertEquals(1, unpacker.getReadByteCount());
}
Example 96
Project: msgpack-java-master  File: TestUnpackerIterator.java View source code
@Test
public void testSample() throws Exception {
    MessagePack msgpack = new MessagePack();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Packer packer = msgpack.createPacker(out);
    packer.write(1);
    packer.write(2);
    packer.write(3);
    byte[] bytes = out.toByteArray();
    Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes));
    UnpackerIterator iter = unpacker.iterator();
    unpacker.resetReadByteCount();
    iter.hasNext();
    iter.next();
    assertEquals(1, unpacker.getReadByteCount());
    unpacker.resetReadByteCount();
    iter.hasNext();
    iter.next();
    assertEquals(1, unpacker.getReadByteCount());
    unpacker.resetReadByteCount();
    iter.hasNext();
    iter.next();
    assertEquals(1, unpacker.getReadByteCount());
}
Example 97
Project: nextprot-api-master  File: StatementsExtractorLocalMockImpl.java View source code
@Override
public Set<Statement> getStatementsForSourceForGeneName(NextProtSource notUsed, String release, String geneName) {
    StatementDictionary sd = new StatementDictionary();
    String content = sd.getStatements(geneName);
    String removedComments = content.replaceAll("((['\"])(?:(?!\\2|\\\\).|\\\\.)*\\2)|\\/\\/[^\\n]*|\\/\\*(?:[^*]|\\*(?!\\/))*\\*\\/", "$1");
    return deserialize(new ByteArrayInputStream(removedComments.getBytes(StandardCharsets.UTF_8)));
}
Example 98
Project: nosql-unit-master  File: WhenInsertOperationIsExecuted.java View source code
@Test
public void insert_operations_should_be_executed() {
    InsertLoadStrategyOperation insertLoadStrategyOperation = new InsertLoadStrategyOperation(databaseOperation);
    InputStream[] contents = new InputStream[] { new ByteArrayInputStream("My name is".getBytes()), new ByteArrayInputStream("Jimmy Pop".getBytes()) };
    insertLoadStrategyOperation.executeScripts(contents);
    verify(databaseOperation, times(2)).insert(any(InputStream.class));
}
Example 99
Project: ode-master  File: SerializerTest.java View source code
@Test
public void testBasicSerialize() throws IOException {
    OmSerdeFactory serdeFactory = new OmSerdeFactory();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OProcess original = new OProcess("0");
    original.setProcessName("process1");
    DeSerializer serializer = new DeSerializer();
    serializer.serialize(baos, original);
    InputStream is = new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray()));
    DeSerializer deSerializer = new DeSerializer(is);
    OProcess desered = deSerializer.deserialize();
    assertEquals(original.getFieldContainer(), desered.getFieldContainer());
}
Example 100
Project: opennaas-routing-nfv-master  File: ObjectCopier.java View source code
public static Object deepCopy(Object original) throws IOException {
    ObjectInputStream ois;
    ObjectOutputStream oos;
    ByteArrayInputStream bais;
    ByteArrayOutputStream baos;
    byte[] data;
    Object copy = null;
    // write object to bytes
    baos = new ByteArrayOutputStream();
    oos = new ObjectOutputStream(baos);
    oos.writeObject(original);
    oos.close();
    // get the bytes
    data = baos.toByteArray();
    // construct an object from the bytes
    bais = new ByteArrayInputStream(data);
    ois = new ObjectInputStream(bais);
    try {
        copy = ois.readObject();
    } catch (Exception e) {
    }
    ois.close();
    return copy;
}
Example 101
Project: openrocket-master  File: TestFileIterator.java View source code
@Test
public void testFileIterator() {
    final Pair<String, InputStream> one = new Pair<String, InputStream>("one", new ByteArrayInputStream(new byte[] { 1 }));
    final Pair<String, InputStream> two = new Pair<String, InputStream>("two", new ByteArrayInputStream(new byte[] { 2 }));
    FileIterator iterator = new FileIterator() {

        private int count = 0;

        @Override
        protected Pair<String, InputStream> findNext() {
            count++;
            switch(count) {
                case 1:
                    return one;
                case 2:
                    return two;
                default:
                    return null;
            }
        }
    };
    assertTrue(iterator.hasNext());
    assertEquals(one, iterator.next());
    assertEquals(two, iterator.next());
    assertFalse(iterator.hasNext());
}