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

The following are Jave code examples for showing how to use toByteArray() of the org.apache.commons.io.IOUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: selenium-testng-template   File: HttpUtils.java   View Source Code Vote up 7 votes
public static final byte[] get(String url, Map<String, String> headers) {
	try {
		URLConnection conn = new URL(url).openConnection();
		if (headers != null) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}
		}
		InputStream is = conn.getInputStream();
		byte[] result = IOUtils.toByteArray(is);
		is.close();
		List<String> header = conn.getHeaderFields().get("Content-Disposition");
		if (header != null && header.size() > 0) {
			headers.put("Content-Disposition", header.get(0));
		}
		return result;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 2
Project: nest-spider   File: ContentDownloader.java   View Source Code Vote up 6 votes
protected String getContent(String charset, HttpResponse response) throws IOException {
	if(charset == null) {
		long contentLength = response.getEntity().getContentLength();
		if(response.getFirstHeader("Content-Type") != null 
				&& !response.getFirstHeader("Content-Type").getValue().toLowerCase().contains("text/html")) 
			throw new IllegalArgumentException("此链接为非html内容,不下载,内容类型:" + response.getFirstHeader("Content-Type"));
		else if(contentLength>value.getMaxDownloadLength())
			throw new IllegalArgumentException("网页内容长度超过最大限制,要求最大长度:" + value.getMaxDownloadLength() + ",实际长度:" + contentLength);
		byte[] contentBytes = IOUtils.toByteArray(response.getEntity().getContent());
		String htmlCharset = UrlUtils.getCharset(response.getEntity().getContentType().getValue());
		if (htmlCharset != null) {
               return new String(contentBytes, htmlCharset);
           } else {
               LOG.warn("自动探测字符集失败, 使用 {} 作为字符集。请在Site.setCharset()指定字符集", Charset.defaultCharset());
               return new String(contentBytes);
           }
	} else 
		return IOUtils.toString(response.getEntity().getContent(), charset);
}
 
Example 3
Project: similarity-uniform-fuzzy-hash   File: UniformFuzzyHash.java   View Source Code Vote up 6 votes
/**
 * Builds a Uniform Fuzzy Hash from an input stream of data and a factor.
 * 
 * @param data Input stream of data.
 * @param factor Relation between data length and the hash mean number of blocks.
 *        Must be greater than 2 and must be odd.
 * @throws IOException If an IOException occurs reading the input stream of data.
 */
public UniformFuzzyHash(
        InputStream data,
        int factor)
        throws IOException {

    this();

    if (data == null) {
        throw new NullPointerException("Data is null.");
    }

    byte[] byteArray = IOUtils.toByteArray(data);
    computeUniformFuzzyHash(byteArray, factor);

}
 
Example 4
Project: nifi-registry   File: FileSystemFlowPersistenceProvider.java   View Source Code Vote up 6 votes
@Override
public synchronized byte[] getFlowContent(final String bucketId, final String flowId, final int version) throws FlowPersistenceException {
    final File snapshotFile = getSnapshotFile(bucketId, flowId, version);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Retrieving snapshot with filename {}", new Object[] {snapshotFile.getAbsolutePath()});
    }

    if (!snapshotFile.exists()) {
        return null;
    }

    try (final InputStream in = new FileInputStream(snapshotFile)){
        return IOUtils.toByteArray(in);
    } catch (IOException e) {
        throw new FlowPersistenceException("Error reading snapshot file: " + snapshotFile.getAbsolutePath(), e);
    }
}
 
Example 5
Project: Jar2Java   File: JarAnalyzer.java   View Source Code Vote up 6 votes
public Map<String, String> getReproguardMapping(String jarPath) {
        Map<String, String> renameMap = new HashMap<>();
        try {
            JarFile file = new JarFile(new File(jarPath));
            Enumeration<JarEntry> enumeration = file.entries();
            while (enumeration.hasMoreElements()) {
                JarEntry jarEntry = enumeration.nextElement();
                InputStream inputStream = file.getInputStream(jarEntry);
                String entryName = jarEntry.getName();
                String className;
                byte[] sourceClassBytes = IOUtils.toByteArray(inputStream);
                if (entryName.endsWith(".class")) {
                    className = Utils.path2Classname(entryName);
                    String newClassname = getReproguardClassname(className);
                    TextFileWritter.getDefaultWritter().println(className + (newClassname != null ? " -> " + newClassname : ""));
//                    analyzeClassNames(className, sourceClassBytes);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        TextFileWritter.getDefaultWritter().close();
        return renameMap;
    }
 
Example 6
Project: uflo   File: DesignerServletHandler.java   View Source Code Vote up 6 votes
public void openFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String name=req.getParameter("name");
	name=decode(name);
	ProcessProvider targetProvider=ProcessProviderUtils.getProcessProvider(name);
	if(targetProvider==null){
		throw new RuntimeException("Unsupport file : "+name);
	}
	InputStream inputStream=targetProvider.loadProcess(name);
	try{
		byte[] bytes=IOUtils.toByteArray(inputStream);
		ProcessDefinition process=ProcessParser.parseProcess(bytes, 0, true);
		writeObjectToJson(resp, process);
	}catch(Exception ex){
		throw new RuntimeException(ex);
	}finally{
		IOUtils.closeQuietly(inputStream);
	}
}
 
Example 7
Project: crates-io-android   File: Utility.java   View Source Code Vote up 6 votes
public static void getSSL(String url, AsyncHttpResponseHandler responseHandler) {
    try {
        URL page = new URL(url); // Process the URL far enough to find the right handler
        HttpURLConnection urlConnection = (HttpURLConnection) page.openConnection();
        String token = Utility.loadData("token", String.class);
        if (token != null) {
            urlConnection.setRequestProperty("Authorization", token);
        }
        urlConnection.setUseCaches(false); // Don't look at possibly cached data
        // Read it all and print it out
        InputStream stream = urlConnection.getInputStream();
        byte[] bytes = IOUtils.toByteArray(stream);
        int code = urlConnection.getResponseCode();
        if (code >= 200 && code < 400) {
            responseHandler.sendSuccessMessage(code, null, bytes);
        } else {
            responseHandler.sendFailureMessage(code, null, bytes, new IOException());
        }
    } catch (IOException e) {
        e.printStackTrace();
        responseHandler.sendFailureMessage(0, null, new byte[1], e);
    }
}
 
Example 8
Project: lighthouse   File: PodcastSplashAsyncTaskTest.java   View Source Code Vote up 5 votes
@Test
    public void shouldGetImageData() throws IOException {
        String url = "http://cdn-st4.rtr-vesti.ru/vh/pictures/bq/128/712/3.jpg";
//        ImageDataResponse response = task.doInBackground(url);
//        Assert.assertNotNull(response);
//        Assert.assertEquals(url, response.getUrl());
        try (InputStream resource = getClass().getClassLoader().getResourceAsStream("podcasts/image-1.jpg")) {
            byte[] bytes = IOUtils.toByteArray(resource);
//            Assert.assertArrayEquals(bytes, Base64.decodeBase64(response.getData()));
        }
    }
 
Example 9
Project: plumdo-work   File: ProcessInstanceImageResource.java   View Source Code Vote up 5 votes
@RequestMapping(value = "/process-instance/{processInstanceId}/image", method = RequestMethod.GET, name="流程实例流程图")
public ResponseEntity<byte[]> getProcessInstanceImage(@PathVariable String processInstanceId) {
	ProcessInstance processInstance = getProcessInstanceFromRequest(processInstanceId);

	ProcessDefinition pde = repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

	if (pde != null && pde.hasGraphicalNotation()) {
		BpmnModel bpmnModel = repositoryService.getBpmnModel(pde.getId());
		ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
		InputStream resource = diagramGenerator.generateDiagram(bpmnModel,"png", runtimeService.getActiveActivityIds(processInstance.getId()), 
				Collections.<String> emptyList(),
				processEngineConfiguration.getActivityFontName(),
				processEngineConfiguration.getLabelFontName(),
				processEngineConfiguration.getAnnotationFontName(),
				processEngineConfiguration.getClassLoader(), 1.0);

		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setContentType(MediaType.IMAGE_PNG);
		try {
			return new ResponseEntity<byte[]>(IOUtils.toByteArray(resource), responseHeaders,HttpStatus.OK);
		} catch (Exception e) {
			throw new FlowableIllegalArgumentException("Error exporting diagram", e);
		}

	} else {
		throw new FlowableIllegalArgumentException("Process instance with id '" + processInstance.getId()+ "' has no graphical notation defined.");
	}
}
 
Example 10
Project: GitHub   File: ResponseKotlin2Test.java   View Source Code Vote up 5 votes
public ExtClassLoader() throws IOException {
    super(Thread.currentThread().getContextClassLoader());

    {
        byte[] bytes;
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ResponseKotlin2.clazz");
        bytes = IOUtils.toByteArray(is);
        is.close();

        super.defineClass("ResponseKotlin2", bytes, 0, bytes.length);
    }
}
 
Example 11
Project: GitHub   File: ClassWithPairMixedTypesTest.java   View Source Code Vote up 5 votes
public ExtClassLoader() throws IOException {
    super(Thread.currentThread().getContextClassLoader());

    {
        byte[] bytes;
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("kotlin/ClassWithPairMixedTypes.clazz");
        bytes = IOUtils.toByteArray(is);
        is.close();

        super.defineClass("ClassWithPairMixedTypes", bytes, 0, bytes.length);
    }
}
 
Example 12
Project: sling-org-apache-sling-launchpad-integration-tests   File: EmbeddedModelTest.java   View Source Code Vote up 5 votes
@Before
public void setup() throws IOException {
    final InputStream modelStream = teleporter.getService(LaunchpadContentProvider.class).getResourceAsStream(MODEL_RESOURCE_PATH);
    assertNotNull("Expecting embedded model resource at " + MODEL_RESOURCE_PATH, modelStream);
    try {
        modelContent = new String(IOUtils.toByteArray(modelStream));
    } finally {
        modelStream.close();
    }
}
 
Example 13
Project: camel   File: RtYamlMappingTest.java   View Source Code Vote up 5 votes
/**
 * Read a test resource file's contents.
 * @param fileName File to read.
 * @return File's contents as String.
 * @throws FileNotFoundException If somethig is wrong.
 * @throws IOException If somethig is wrong.
 */
private String readTestResource(final String fileName)
    throws FileNotFoundException, IOException {
    return new String(
        IOUtils.toByteArray(
            new FileInputStream(
                new File("src/test/resources/" + fileName)
            )    
        )
    );
}
 
Example 14
Project: stvs   File: ImporterFacade.java   View Source Code Vote up 5 votes
/**
 * Imports a file of unknown type.
 *
 * @param file The file to open
 * @param globalConfig The current global config
 * @param currentHistory history of the opened files to this point
 * @param importHybridSpecificationHandler A file handler (invoked if the file is a Specification)
 * @param importStvsRootModelHandler A file handler (invoked if the file is a Session)
 * @param codeConsumer A file handler (invoked if the file is a code file)
 * @throws IOException general io exception
 * @throws ImportException general importing exception
 */
public static void importFile(File file, GlobalConfig globalConfig, History currentHistory,
    ImportHybridSpecificationHandler importHybridSpecificationHandler,
    ImportStvsRootModelHandler importStvsRootModelHandler, ImportCodeHandler codeConsumer)
    throws IOException, ImportException {
  StringWriter writer = new StringWriter();
  byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file));
  IOUtils.copy(new ByteArrayInputStream(byteArray), writer, "utf8");
  String inputString = writer.toString();
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setNamespaceAware(true);
  try {
    Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(inputString)));
    if (doc != null && doc.getFirstChild() != null) {
      Node rootNode = doc.getFirstChild();
      switch (rootNode.getNodeName()) {
        case "session":
          importStvsRootModelHandler
              .accept(importSession(file, ImportFormat.XML, globalConfig, currentHistory));
          return;
        case "specification":
          importHybridSpecificationHandler.accept(importHybridSpec(file, ImportFormat.XML));
          return;
        default:
          codeConsumer.accept(importStCode(file));
          return;
      }
    }
  } catch (SAXException | ParserConfigurationException | ImportException e) {
    // ignore, because it might have been code
  }
  codeConsumer.accept(importStCode(file));
}
 
Example 15
Project: TapIn   File: HubMain.java   View Source Code Vote up 5 votes
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hub_main);

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    setTitle("Tap In Hub");


    yeeid = (TextView)findViewById(R.id.yeeid);
    spinner = (ProgressBar)findViewById(R.id.progressBar);
    gifImageView = (GifImageView)findViewById(R.id.gifImageView);

    try
    {
        InputStream inputStream = getAssets().open("nfc.gif");

        byte[] bytes = IOUtils.toByteArray(inputStream);
        gifImageView.setBytes(bytes);
        gifImageView.startAnimation();
    }
    catch (IOException e)
    {}
    gifImageView.setVisibility(View.VISIBLE);
    spinner.setVisibility(View.INVISIBLE);

}
 
Example 16
Project: careconnect-reference-implementation   File: TerminologyLoaderTest.java   View Source Code Vote up 5 votes
/**
 * This is just for trying stuff, it won't run without
 * local files external to the git repo
 */
@Ignore
@Test
public void testLoadSnomedCtAgainstRealFile() throws Exception {
    byte[] bytes = IOUtils.toByteArray(new FileInputStream("/Users/james/Downloads/SnomedCT_Release_INT_20160131_Full.zip"));

    RequestDetails details = mock(RequestDetails.class);
    mySvc.loadSnomedCt(list(bytes), details);
}
 
Example 17
Project: s3-inventory-usage-examples   File: InventoryReportLineWriterTest.java   View Source Code Vote up 4 votes
@Test
public void writeObjectToCsvSuccess() throws IOException{
    String testSrcBucket = "testSrcBucket";
    String testDestBucketName = "testDestBucketName";
    String testDestPrefix = "testDestPrefix";
    String testFileSchema = "Bucket, Key, Versionid, IsLatest, IsDeleteMaker, Size, LastModifiedDate," +
            "ETag, StorageClass, IsMultipartUploaded, ReplicationStatus";
    InventoryManifest testInventoryManifest = buildInventoryManifest(testFileSchema);
    List<InventoryReportLine> testInventoryReportLine = buildInventoryReportStorgaeList();
    InventoryReportLineWriter testCsvWriter = new InventoryReportLineWriter(mockS3Client, testDestBucketName, testDestPrefix,
            testSrcBucket, testInventoryManifest);
    when(mockS3Client.putObject(putObjectRequestCaptor.capture())).thenReturn(null);
    InventoryManifest.Locator testLocator = testCsvWriter.writeCsvFile(testInventoryReportLine);
    PutObjectRequest request = putObjectRequestCaptor.getValue();

    // Test if bucketName and outputInventoryReportKey match in args
    assertThat(request.getBucketName(), is("testDestBucketName"));
    String actualKey = request.getKey();
    List<String> keyList = Arrays.asList(actualKey.split("\\s*/\\s*"));
    assertThat(keyList.get(0), is("testDestPrefix"));
    assertThat(keyList.get(1), is("testSrcBucket"));
    assertThat(keyList.get(2), is("data"));

    // Test if the inputStream match when put object to S3
    byte[] actualByteArray = IOUtils.toByteArray(request.getInputStream());
    String actualInventoryReportString = IOUtils.toString(new GZIPInputStream(
            new ByteArrayInputStream(actualByteArray)));
    String expectedInventoryReportString =
            "testBucket1,testKey1,testVersionId1,testIsLatest1,testIsDeleteMaker1,testSize1,testLastModifiedDate1," +
            "testETag1,testStorage1,testMultiPartUploaded1,testReplicationStatus1\n" +
            "testBucket2,testKey2,testVersionId2,testIsLatest2,testIsDeleteMaker2,testSize2,testLastModifiedDate2," +
            "testETag2,testStorage2,testMultiPartUploaded2,testReplicationStatus2\n";
    assertThat(actualInventoryReportString, is(expectedInventoryReportString));

    // Test if the metaData match when put object to S3
    long expectedMetaDataLength = actualByteArray.length;
    assertThat(request.getMetadata().getContentLength(), is(expectedMetaDataLength));

    // Test if the return result of writeCsvFile() match the expected one
    InventoryManifest.Locator expectedLocator = new InventoryManifest.Locator();
    expectedLocator.setKey(actualKey);
    long expectedSize = actualByteArray.length;
    expectedLocator.setSize(expectedSize);
    String expectedChecksum = DigestUtils.md5Hex(actualByteArray);
    expectedLocator.setMD5checksum(expectedChecksum);
    assertThat(testLocator, is(expectedLocator));
}
 
Example 18
Project: fake-smtp-server   File: TestResourceUtil.java   View Source Code Vote up 4 votes
public static byte[] getTestFileContentBytes(String testFilename) throws IOException {
    return IOUtils.toByteArray(getTestFile(testFilename));
}
 
Example 19
Project: AI-Powered-Intelligent-Banking-Platform   File: AvsSpeakItem.java   View Source Code Vote up 4 votes
public AvsSpeakItem(String token, String cid, ByteArrayInputStream audio) throws IOException {
    this(token, cid, IOUtils.toByteArray(audio));
    audio.close();
}
 
Example 20
Project: syndesis   File: DefaultProjectGenerator.java   View Source Code Vote up 4 votes
private void addResource(TarArchiveOutputStream tos, String destination, String resource) throws IOException {
    final URL url = getClass().getResource(resource);
    final byte[] bytes = IOUtils.toByteArray(url);

    addTarEntry(tos, destination, bytes);
}