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:it.greenvulcano.gvesb.datahandling.dbo.utils.ResultSetTransformer.java
private static Object parseValue(Object object) { try {// w ww. j a v a 2 s . com if (object instanceof Blob) { byte[] blob = IOUtils.toByteArray(Blob.class.cast(object).getBinaryStream()); object = Base64.getEncoder().encodeToString(blob); } } catch (Exception e) { LOG.error("Something goes wrong parsing BLOB field", e); object = "Unparsable BLOB"; } try { if (object instanceof Clob) { byte[] clob = IOUtils.toByteArray(Clob.class.cast(object).getAsciiStream()); object = new String(clob, "UTF-8"); } } catch (Exception e) { LOG.error("Something goes wrong parsing CLOB field", e); object = "Unparsable CLOB"; } if (object instanceof String) { String value = String.class.cast(object).trim(); try { if (value.startsWith("{") && value.endsWith("}")) { return new JSONObject(value); } else if (value.startsWith("[") && value.endsWith("]")) { return new JSONArray(value); } } catch (JSONException e) { LOG.warn("Something goes wrong parsing " + value + " as JSON"); } } return object; }
From source file:com.shmsoft.dmass.print.Html2Pdf.java
/** * Bad rendering, perhaps used only for Windows *//*w ww. j a v a 2 s . c o m*/ @SuppressWarnings({ "rawtypes", "unchecked" }) private static void convertHtml2Pdf(Reader htmlReader, String outputFile) throws Exception { Document pdfDocument = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(pdfDocument, baos); pdfDocument.open(); StyleSheet styles = new StyleSheet(); styles.loadTagStyle("body", "font", "Times New Roman"); ImageProvider imageProvider = new ImageProvider() { @Override public Image getImage(String src, HashMap arg1, ChainedProperties arg2, DocListener arg3) { try { Image image = Image.getInstance(IOUtils.toByteArray( getClass().getClassLoader().getResourceAsStream(ParameterProcessing.NO_IMAGE_FILE))); return image; } catch (Exception e) { System.out.println("Problem with html->pdf imaging, image provider fault"); } return null; } }; HashMap interfaceProps = new HashMap(); interfaceProps.put("img_provider", imageProvider); ArrayList arrayElementList = HTMLWorker.parseToList(htmlReader, styles, interfaceProps); for (int i = 0; i < arrayElementList.size(); ++i) { Element e = (Element) arrayElementList.get(i); pdfDocument.add(e); } pdfDocument.close(); byte[] bs = baos.toByteArray(); File pdfFile = new File(outputFile); FileOutputStream out = new FileOutputStream(pdfFile); out.write(bs); out.close(); }
From source file:com.platform.BRHTTPHelper.java
public static byte[] getBody(HttpServletRequest request) { if (request == null) return null; byte[] rawData = null; try {// ww w . j ava 2 s . c om InputStream body = request.getInputStream(); rawData = IOUtils.toByteArray(body); } catch (IOException e) { e.printStackTrace(); } return rawData; }
From source file:com.esri.geoportal.harvester.unc.UncFile.java
/** * Reads content./*from www .ja va2s . co m*/ * @return content reference * @throws IOException if reading content fails * @throws URISyntaxException if file url is an invalid URI */ public SimpleDataReference readContent() throws IOException, URISyntaxException { Date lastModifiedDate = readLastModifiedDate(); MimeType contentType = readContentType(); try (InputStream input = new FileInputStream(file)) { return new SimpleDataReference(broker.getBrokerUri(), broker.getEntityDefinition().getLabel(), file.getAbsolutePath(), lastModifiedDate, file.toURI(), IOUtils.toByteArray(input), contentType); } }
From source file:io.lightlink.types.BlobConverter.java
@Override public Object convertToJdbc(Connection connection, RunnerContext runnerContext, String name, Object value) throws IOException { if (value == null) return null; if (value instanceof InputStream && StringUtils.isBlank(encoding)) { return value; } else {//from ww w .j a v a 2 s . co m byte[] array; if (value instanceof byte[]) { array = (byte[]) value; } else if (value instanceof InputStream) { array = IOUtils.toByteArray((InputStream) value); } else if (value instanceof String) { String str = (String) value; if (encoding.equalsIgnoreCase("base64")) array = DatatypeConverter.parseBase64Binary(str); else try { array = str.getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( "Cannot convert value:" + value + " to Blob. Specified encoding:" + encoding + " not recognised. (note:default encoding for String is base64)"); } } else { throw new IllegalArgumentException("Cannot convert value:" + value + " of type:" + value.getClass().getName() + " to Blob. int[] or String expected. (note:default encoding for String is base64)"); } return new ByteArrayInputStream(array); } }
From source file:eionet.gdem.utils.HttpUtils.java
/** * Downloads remote file/*from w w w. jav a 2 s . c om*/ * @param url URL * @return Downloaded file * @throws DCMException If an error occurs. * @throws IOException If an error occurs. */ public static byte[] downloadRemoteFile(String url) throws DCMException, IOException { byte[] responseBody = null; CloseableHttpClient client = HttpClients.createDefault(); // Create a method instance. HttpGet method = new HttpGet(url); // Execute the method. CloseableHttpResponse response = null; try { response = client.execute(method); HttpEntity entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + response.getStatusLine().getReasonPhrase()); throw new DCMException(BusinessConstants.EXCEPTION_SCHEMAOPEN_ERROR, response.getStatusLine().getReasonPhrase()); } // Read the response body. InputStream instream = entity.getContent(); responseBody = IOUtils.toByteArray(instream); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data // System.out.println(new String(responseBody)); /*catch (HttpException e) { LOGGER.error("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); throw e;*/ } catch (IOException e) { LOGGER.error("Fatal transport error: " + e.getMessage()); e.printStackTrace(); throw e; } finally { // Release the connection. response.close(); method.releaseConnection(); client.close(); } return responseBody; }
From source file:com.linkedin.pinot.broker.routing.RandomRoutingTableTest.java
@Test public void testHelixExternalViewBasedRoutingTable() throws Exception { URL resourceUrl = getClass().getClassLoader().getResource("SampleExternalView.json"); Assert.assertNotNull(resourceUrl);// w w w . j av a 2s .co m String fileName = resourceUrl.getFile(); byte[] externalViewBytes = IOUtils.toByteArray(new FileInputStream(fileName)); ExternalView externalView = new ExternalView( (ZNRecord) new ZNRecordSerializer().deserialize(externalViewBytes)); String tableName = externalView.getResourceName(); List<InstanceConfig> instanceConfigs = getInstanceConfigs(externalView); int numSegmentsInEV = externalView.getPartitionSet().size(); int numServersInEV = instanceConfigs.size(); HelixExternalViewBasedRouting routing = new HelixExternalViewBasedRouting(null, null, new BaseConfiguration()); routing.markDataResourceOnline(generateTableConfig(tableName), externalView, instanceConfigs); for (int i = 0; i < NUM_ROUNDS; i++) { Map<String, List<String>> routingTable = routing .getRoutingTable(new RoutingTableLookupRequest(tableName)); Assert.assertEquals(routingTable.size(), numServersInEV); int numSegments = 0; for (List<String> segmentsForServer : routingTable.values()) { int numSegmentsForServer = segmentsForServer.size(); Assert.assertTrue(numSegmentsForServer >= MIN_NUM_SEGMENTS_PER_SERVER && numSegmentsForServer <= MAX_NUM_SEGMENTS_PER_SERVER); numSegments += numSegmentsForServer; } Assert.assertEquals(numSegments, numSegmentsInEV); } }
From source file:edu.stanford.mobisocial.dungbeetle.ui.adapter.ObjectListCursorAdapter.java
private static int getBestBatchSize() { Runtime runtime = Runtime.getRuntime(); if (runtime.availableProcessors() > 1) return 100; try {//from w w w. j av a 2s.c o m File max_cpu_freq = new File("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"); byte[] freq_bytes = IOUtils.toByteArray(new FileInputStream(max_cpu_freq)); String freq_string = new String(freq_bytes); double freq = Double.valueOf(freq_string); if (freq > 950000) { return 50; } } catch (IOException e) { e.printStackTrace(); } return 15; }
From source file:com.google.code.ddom.commons.cl.ClassRef.java
/** * Load the definition of the class identified by this object. * //from w w w .j av a2s. c o m * @return the class definition, i.e. the content of the corresponding class file * @throws ClassNotFoundException * if the class was not found or an error occurred when loading the class definition */ public byte[] getClassDefinition() throws ClassNotFoundException { InputStream in = getClassDefinitionAsStream(); try { try { return IOUtils.toByteArray(in); } finally { in.close(); } } catch (IOException ex) { throw new ClassNotFoundException(className, ex); } }
From source file:net.sf.sripathi.ws.mock.util.FileUtil.java
public static void createFilesAndFolder(String root, ZipFile zip) { @SuppressWarnings("unchecked") Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries(); Set<String> files = new TreeSet<String>(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".wsdl") || entry.getName().toLowerCase().endsWith(".xsd")) files.add(entry.getName());//from w w w . java 2 s . c om } File rootFolder = new File(root); if (!rootFolder.exists()) { throw new MockException("Unable to create file - " + root); } for (String fileStr : files) { String folder = root; String[] split = fileStr.split("/"); if (split.length > 1) { for (int i = 0; i < split.length - 1; i++) { folder = folder + "/" + split[i]; File f = new File(folder); if (!f.exists()) { f.mkdir(); } } } File file = new File(folder + "/" + split[split.length - 1]); FileOutputStream fos = null; InputStream zipStream = null; try { fos = new FileOutputStream(file); zipStream = zip.getInputStream(zip.getEntry(fileStr)); fos.write(IOUtils.toByteArray(zipStream)); } catch (Exception e) { throw new MockException("Unable to create file - " + fileStr); } finally { try { fos.close(); } catch (Exception e) { } try { zipStream.close(); } catch (Exception e) { } } } }