List of usage examples for org.apache.commons.io IOUtils toByteArray
public static byte[] toByteArray(String input) throws IOException
String
as a byte[]
using the default character encoding of the platform. From source file:com.difference.historybook.proxy.ProxyTest.java
@Test public void testSmallFetch() { String body = "<html><head></head><body>Hello World!</body></html>"; stubFor(get(urlEqualTo("/some/page")) .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "text/html").withBody(body))); Proxy proxy = getProxy().setPort(PROXY_PORT); try {/*ww w.j a v a 2s. c o m*/ proxy.start(); java.net.Proxy proxyServer = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", PROXY_PORT)); HttpURLConnection connection = (HttpURLConnection) new URL( "http://localhost:" + DUMMY_SERVER_PORT + "/some/page").openConnection(proxyServer); byte[] fetchedContent = IOUtils.toByteArray(connection.getInputStream()); assertArrayEquals(body.getBytes(Charsets.UTF_8), fetchedContent); proxy.stop(); } catch (Exception e) { fail(e.getLocalizedMessage()); } }
From source file:com.bt.download.android.gui.DiskCrawlCache.java
@Override public byte[] get(String key) { byte[] data = null; if (cache != null) { try {/* w ww. java 2 s.co m*/ Entry e = cache.get(key); if (e != null) { try { data = IOUtils.toByteArray(e.getInputStream()); } finally { e.close(); } } } catch (Throwable e) { // ignore } } return data; }
From source file:com.javacreed.examples.lang.DynamicClassLoader.java
public void loadJar(final InputStream in) throws IOException { try (BufferedInputStream bis = new BufferedInputStream(in); ZipInputStream zis = new ZipInputStream(bis)) { for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) { if (ze.isDirectory()) { continue; }// www . j av a 2s . c o m final String name = ze.getName(); final String canonicalName = StringUtils.removeEnd(name, ".class").replaceAll("[\\/]", "."); final byte[] classBytes = IOUtils.toByteArray(zis); if (loadedClasses.putIfAbsent(canonicalName, classBytes) == null) { DynamicClassLoader.LOGGER.debug("Loading class: {} of {} bytes", canonicalName, classBytes.length); } else { DynamicClassLoader.LOGGER.debug("Skipping class: {} of {} bytes as onle already exists", canonicalName, classBytes.length); } } } }
From source file:com.talis.storage.ItemFactoryTest.java
@Test public void createItemWithCorrectEntity() throws Exception { SubmittedItem item = factory.newSubmittedItem(MediaType.APPLICATION_XML_TYPE, new ByteArrayInputStream(entityBytes)); assertTrue(Arrays.equals(entityBytes, IOUtils.toByteArray(item.getEntity()))); }
From source file:com.cloudant.sync.datastore.SavedHttpAttachment.java
/** * Creates a SavedHttpAttachment (a fully initialised attachment) * with the provided properties//from w w w.j a va 2 s . co m * @param name The name of the attachment eg bonsai-boston.jpg * @param attachmentData The json attachment data from a couchDB instance * @param attachmentURI The URI at which the attachment can be downloaded * @throws IOException if there is an error decoding the attachment data */ public SavedHttpAttachment(String name, Map<String, Object> attachmentData, URI attachmentURI) throws IOException { super(name, (String) attachmentData.get("content_type"), Encoding.Plain); Boolean stub = (Boolean) attachmentData.get("stub"); Number length = (Number) attachmentData.get("length"); String data = (String) attachmentData.get("data"); String encoding = (String) attachmentData.get("encoding"); this.encoding = Attachment.getEncodingFromString(encoding); if (!stub) { byte[] dataArray = data.getBytes(); InputStream is = Base64InputStreamFactory.get(new ByteArrayInputStream(dataArray)); this.data = IOUtils.toByteArray(is); } this.attachmentURI = attachmentURI; this.size = length.intValue(); }
From source file:com.jayway.restassured.itest.java.MultiPartUploadITest.java
@Test public void multiPartUploadingWorksForByteArrays() throws Exception { // Given/*from w w w . j a va 2 s. com*/ final byte[] bytes = IOUtils.toByteArray(getClass().getResourceAsStream("/car-records.xsd")); // When given().multiPart("file", "myFile", bytes).expect().statusCode(200).body(is(new String(bytes))).when() .post("/multipart/file"); }
From source file:eu.ggnet.dwoss.util.FileJacket.java
/** * Constructur with read in logic.//from w w w. j a v a 2 s . c om * Creates a new DataFile with the content of the supplied file * <p/> * @param head the head of the filename * @param suffix the suffix of the file * @param file the file to read * @throws RuntimeException if something while reading the file fails. */ public FileJacket(String head, String suffix, File file) throws RuntimeException { this.head = head; this.suffix = suffix; content = new byte[0]; if (file == null) throw new NullPointerException("File is null"); if (!file.exists() || !file.canRead()) throw new IllegalStateException(file + " dosn't exist or cannot be read"); try (FileInputStream is = new FileInputStream(file)) { content = IOUtils.toByteArray(is); } catch (IOException ex) { throw new RuntimeException("Exception during Read File", ex); } }
From source file:com.multiimages.insertmultiimg.InsertMultiImg.java
@Transactional(value = "EmployeesDBTransactionManager") public void uploadFile(Integer relativePath, MultipartFile[] files, HttpServletRequest httpServletRequest) { /* Note: relativePath here maps to the id of the related Object to be saved in the transaction */ File outputFile = null;//from w w w.j av a 2s . com Session session = sessionFactory.getObject().openSession(); for (MultipartFile file : files) { try { Image image = new Image(); image.setEmployee(employeeService.findById(relativePath)); byte[] byteArray = IOUtils.toByteArray(file.getInputStream()); Blob blob = Hibernate.getLobCreator(session).createBlob(new ByteArrayInputStream(byteArray), new Long(byteArray.length)); image.setImgdate(blob); imageService.create(image); } catch (Exception e) { } } }
From source file:gobblin.converter.avro.AvroToBytesConverterTest.java
@Test public void testSerialization() throws DataConversionException, IOException, SchemaConversionException { Schema inputSchema = new Schema.Parser().parse( getClass().getClassLoader().getResourceAsStream("converter/bytes_to_avro/test_record_schema.avsc")); AvroToBytesConverter converter = new AvroToBytesConverter(); WorkUnitState state = new WorkUnitState(); converter.init(state);//from w w w .ja v a 2 s .c om String outputSchema = converter.convertSchema(inputSchema, state); // Write a record twice to make sure nothing goes wrong with caching for (int i = 0; i < 2; i++) { GenericRecord testRecord = new GenericData.Record(inputSchema); testRecord.put("testStr", "testing12" + ((i == 0) ? "3" : "4")); testRecord.put("testInt", -2); Iterator<byte[]> records = converter.convertRecord(outputSchema, testRecord, state).iterator(); byte[] record = records.next(); Assert.assertFalse(records.hasNext()); byte[] expectedRecord = IOUtils.toByteArray(getClass().getClassLoader() .getResourceAsStream("converter/bytes_to_avro/test_record_binary.avro")); // the serialized record was serialized with testing123 as the string; if we write testing124 out // contents should be the same except for the 10th byte which will be '4' instead of '3' if (i == 1) { expectedRecord[10] = 52; } Assert.assertEquals(outputSchema, inputSchema.toString()); Assert.assertEquals(record, expectedRecord); } }
From source file:gobblin.converter.avro.BytesToAvroConverterTest.java
@Test public void testCanParseBinary() throws DataConversionException, SchemaConversionException, IOException { InputStream schemaIn = getClass().getClassLoader() .getResourceAsStream(RESOURCE_PATH_PREFIX + "test_record_schema.avsc"); InputStream recordIn = getClass().getClassLoader() .getResourceAsStream(RESOURCE_PATH_PREFIX + "test_record_binary.avro"); Assert.assertNotNull("Could not load test schema from resources", schemaIn); Assert.assertNotNull("Could not load test record from resources", recordIn); BytesToAvroConverter converter = new BytesToAvroConverter(); WorkUnitState state = new WorkUnitState(); converter.init(state);//from www. ja v a 2s . c om Schema schema = converter.convertSchema(IOUtils.toString(schemaIn, StandardCharsets.UTF_8), state); Assert.assertEquals(schema.getName(), "testRecord"); Iterator<GenericRecord> records = converter.convertRecord(schema, IOUtils.toByteArray(recordIn), state) .iterator(); GenericRecord record = records.next(); Assert.assertFalse("Expected only 1 record", records.hasNext()); Assert.assertEquals(record.get("testStr").toString(), "testing123"); Assert.assertEquals(record.get("testInt"), -2); }