当前位置: 首页>>代码示例>>Java>>正文


Java IOUtils.toByteArray方法代码示例

本文整理汇总了Java中org.apache.commons.compress.utils.IOUtils.toByteArray方法的典型用法代码示例。如果您正苦于以下问题:Java IOUtils.toByteArray方法的具体用法?Java IOUtils.toByteArray怎么用?Java IOUtils.toByteArray使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.compress.utils.IOUtils的用法示例。


在下文中一共展示了IOUtils.toByteArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testSign

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
@Test
@Ignore
// TODO need to regen key now that we're using CryptoSuite
public void testSign() {

    byte[] plainText = "123456".getBytes(UTF_8);
    byte[] signature;
    try {
        PrivateKey key = (PrivateKey) crypto.getTrustStore().getKey("key", "123456".toCharArray());
        signature = crypto.sign(key, plainText);

        BufferedInputStream bis = new BufferedInputStream(
                this.getClass().getResourceAsStream("/keypair-signed.crt"));
        byte[] cert = IOUtils.toByteArray(bis);
        bis.close();

        assertTrue(crypto.verify(cert, SIGNING_ALGORITHM, signature, plainText));
    } catch (KeyStoreException | CryptoException | IOException | UnrecoverableKeyException
            | NoSuchAlgorithmException e) {
        fail("Could not verify signature. Error: " + e.getMessage());
    }
}
 
开发者ID:hyperledger,项目名称:fabric-sdk-java,代码行数:23,代码来源:CryptoPrimitivesTest.java

示例2: generateFromTemplateTo

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
/**
 * Generate from template to output dir with replaceMaterials.
 *
 * @param templateName template name
 * @param packageName package name in template to be replaced
 * @param outputDir output dir
 * @param replaceMaterials replace materials
 * @param overwrite overwrite
 * @throws IOException IOException
 */
public void generateFromTemplateTo(
        final String templateName, final String packageName,
        final String outputDir, final Map<String, String> replaceMaterials, final boolean overwrite
) throws IOException {
    try (InputStream inputStream = getClass().getResourceAsStream("/templates/" + templateName)) {
        String template = new String(IOUtils.toByteArray(inputStream));
        String output = template.replace("{packageName}", packageName);
        for (Map.Entry<String, String> replaceEntry : replaceMaterials.entrySet()) {
            output = output.replace(replaceEntry.getKey(), replaceEntry.getValue());
        }

        fileUtils.checkAndCreateDirectory(outputDir);
        fileUtils.writeResourceToFile(
                new ByteArrayInputStream(output.getBytes()),
                outputDir + "/" + templateName,
                overwrite
        );
    } catch (IOException e) {
        throw e;
    }
}
 
开发者ID:yahoo,项目名称:parsec,代码行数:32,代码来源:ParsecGeneratorUtil.java

示例3: getFileContent

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
/**
 * Reads content of the file from ZIP archive.
 *
 * @param zipFile ZIP file
 * @param path path of the file to read content
 * @return content of the file with the given path
 * @throws IOException if error occurs while reading
 * @throws IllegalArgumentException if file not found in ZIP archive
 */
public static String getFileContent(ZipFile zipFile, String path) throws IOException {
  Enumeration<? extends ZipEntry> entries = zipFile.entries();

  while (entries.hasMoreElements()) {
    ZipEntry entry = entries.nextElement();

    if (path.equals(entry.getName())) {
      try (InputStream in = zipFile.getInputStream(entry)) {
        byte[] bytes = IOUtils.toByteArray(in);

        return new String(bytes);
      }
    }
  }

  throw new IllegalArgumentException(
      format("Cannot find file '%s' in '%s'", path, zipFile.getName()));
}
 
开发者ID:eclipse,项目名称:che,代码行数:28,代码来源:Utils.java

示例4: unserializeData

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
private <T> T unserializeData(InputStream inputStream) {
    T object = null;
    try {
        if (dataFormat.equals(DataFormat.CBOR)) {
                object = (T) cborMapper.readValue(inputStream, TargetModelCbor.class);
        } else if (dataFormat.equals(DataFormat.JSON)) {
            object = (T) jsonMapper.readValue(inputStream, TargetModelJson.class);
        } else if (dataFormat.equals(DataFormat.HTML)) {
            byte[] fileData = IOUtils.toByteArray(inputStream);
            object = (T) new String(fileData);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to unserialize object.", e);
    }
    return object;
}
 
开发者ID:ViDA-NYU,项目名称:ache,代码行数:18,代码来源:FileSystemTargetRepository.java

示例5: shouldStoreContentCompressed

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
@Test
public void shouldStoreContentCompressed() throws IOException {
    // given
 boolean compressData = true;
 String folder = tempFolder.newFolder().toString();
    Page target = new Page(new URL(url), html);
    FileSystemTargetRepository repository = new FileSystemTargetRepository(Paths.get(folder), DataFormat.HTML, false, compressData);
    
    // when
    repository.insert(target);
    
    // then
    Path path = Paths.get(folder, "example.com", "http%3A%2F%2Fexample.com");
    assertThat(path.toFile().exists(), is(true));
    
    byte[] fileBytes = Files.readAllBytes(path);
    assertThat(fileBytes, is(notNullValue()));
    assertThat(fileBytes.length < html.getBytes().length, is(true));
    
    InputStream gzip = new InflaterInputStream(new ByteArrayInputStream(fileBytes));
    byte[] uncompressedBytes = IOUtils.toByteArray(gzip);
    String content = new String(uncompressedBytes);
    assertThat(content, is(html));
}
 
开发者ID:ViDA-NYU,项目名称:ache,代码行数:25,代码来源:FileSystemTargetRepositoryTest.java

示例6: readPictureForId

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
public byte[] readPictureForId(Context context, String id) {
    Log.i(TAG, "readPictureForId: " + id);
    try {
        //create FileInputStream object
        FileInputStream fin = new FileInputStream(new File(context.getFilesDir().getAbsolutePath() + "/pictures/" + id + ".jpeg"));

        //create string from byte array
        return IOUtils.toByteArray(fin);

    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found " + e);
    } catch (IOException ioe) {
        Log.e(TAG, "Exception while reading the file " + ioe);
    }
    return null;
}
 
开发者ID:breadwallet,项目名称:breadwallet-android,代码行数:17,代码来源:CameraPlugin.java

示例7: sshagent

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
@Issue({ "JENKINS-47225", "JENKINS-42582" })
@Test
public void sshagent() throws Exception {
    PrivateKeySource source = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(
            new String(IOUtils.toByteArray(getClass().getResourceAsStream("id_rsa"))));
    BasicSSHUserPrivateKey credentials = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL,
            "ContainerExecDecoratorPipelineTest-sshagent", "bob", source, "secret_passphrase", "test credentials");
    SystemCredentialsProvider.getInstance().getCredentials().add(credentials);

    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "sshagent");
    p.setDefinition(new CpsFlowDefinition(loadPipelineScript("sshagent.groovy"), true));
    WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    assertNotNull(b);
    r.waitForCompletion(b);
    r.assertLogContains("Identity added:", b);
    //check that we don't accidentally start exporting sensitive info to the log
    r.assertLogNotContains("secret_passphrase", b);
}
 
开发者ID:carlossg,项目名称:jenkins-kubernetes-plugin,代码行数:19,代码来源:ContainerExecDecoratorPipelineTest.java

示例8: pullUrl

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
private String pullUrl(String msg) {
	try {
        URL url = new URL("http://" +  modulesApi.getVersionHostname("digidoc-service-adapter","v1") + "/proxy");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
           connection.setDoOutput(true);
           connection.setConnectTimeout(20 * 1000);
           connection.setRequestMethod("POST");
           IOUtils.copy(new ByteArrayInputStream(msg.getBytes("utf-8")), connection.getOutputStream());
   
           if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
           	return new String(IOUtils.toByteArray(connection.getInputStream()));
           } else {
           	LOG.warning("digidoc-service-adapter returned " + connection.getResponseCode() + " -> " + connection.getResponseMessage());
           	return null;
           }
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
开发者ID:aleksz,项目名称:driveddoc,代码行数:21,代码来源:MobileIdService.java

示例9: createContainer

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
public SignedDoc createContainer(String fileName, String mimeType, InputStream content) {

		try {
			SignedDoc signedDoc = DigiDocGenFactory.createSignedDoc(
					SignedDoc.FORMAT_DIGIDOC_XML, null, null);
			
			DataFile dataFile = new DataFile(
					signedDoc.getNewDataFileId(), 
					DataFile.CONTENT_EMBEDDED_BASE64, 
					fileName, 
					mimeType, 
					signedDoc);
			
			byte[] contentBytes = IOUtils.toByteArray(content);
			dataFile.setBase64Body(contentBytes);
			dataFile.calcHashes(new ByteArrayInputStream(contentBytes));//hack to make DigiDoc save file content
			signedDoc.addDataFile(dataFile);
			return signedDoc;

		} catch (DigiDocException | IOException e) {
			throw new RuntimeException(e);
		}
	}
 
开发者ID:aleksz,项目名称:driveddoc,代码行数:24,代码来源:DigiDocService.java

示例10: pullUrl

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
public String pullUrl(InputStream msg, long length) {

		HttpPost request = new HttpPost(SERVICE_URL);
		request.setHeader("Content-Type", "text/xml; charset=utf-8");
		request.setHeader("User-Agent",  "JDigiDoc /3.8.0.3 ");
		request.setHeader("SOAPAction", "");
		
		try {
			String msgString = new String(IOUtils.toByteArray(msg));
			LOG.info(msgString);
			request.setEntity(new StringEntity(msgString));
			String result = new String(IOUtils.toByteArray(httpClient.execute(request, httpContext).getEntity().getContent()));
			LOG.info(result);
			return result;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
 
开发者ID:aleksz,项目名称:driveddoc,代码行数:19,代码来源:DigiDocServiceAccessor.java

示例11: loadResource

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
protected String loadResource(String name) {
    try {
        return new String(IOUtils.toByteArray(getClass().getResourceAsStream(name)));
    } catch (Throwable t) {
        throw new RuntimeException("Could not read resource:[" + name + "].");
    }
}
 
开发者ID:maxlaverse,项目名称:kubernetes-cli-plugin,代码行数:8,代码来源:KubectlTestBase.java

示例12: fileItemStreamToByteArray

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
public static byte[] fileItemStreamToByteArray(FileItemStream item, int docType) throws IOException, FileUploadException {
    if (item != null && docType > 0) {
        byte[] array = IOUtils.toByteArray(item.openStream());
        String[] types = new String[0];
        boolean returnVal = false;

        if (docType == 1) {
            types = new String[]{".jpg", ".jpeg", ".png"};
        } else if (docType == 2) {
            types = new String[]{".pdf", ".doc", ".docx"};
        } else if (docType == 3) {
            types = new String[]{".pdf", ".jpg", ".jpeg", ".png"};
        }

        for (String type : types) {
            if (getFileType(item).contains(type)) {
                returnVal = true;
            }
        }

        if (item.getName() != null && returnVal) {
            return array;
        }


    }
    throw new InvalidFormatException();
}
 
开发者ID:faizan-ali,项目名称:full-javaee-app,代码行数:29,代码来源:CustomUtilities.java

示例13: deflate

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
/**
 * uncompress data with a compression algorithm
 * 
 * @param data
 *            the compressed bytes
 * @return the uncompressed bytes
 */
public byte[] deflate(byte[] data) {
	ByteArrayInputStream in = new ByteArrayInputStream(data);
	try (InputStream depressor = createInputStream(in)) {
		return IOUtils.toByteArray(depressor);
	} catch (IOException | CompressorException e) {
		throw new RuntimeException(e);
	}
}
 
开发者ID:shilongdai,项目名称:vsDiaryWriter,代码行数:16,代码来源:Compressor.java

示例14: testLoadCACerts

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
@Test
public void testLoadCACerts() {
    try {
        File certsFolder = new File("cacerts").getAbsoluteFile();
        Collection<File> certFiles = FileUtils.listFiles(certsFolder, new String[] {"pem"}, false);
        int numFiles = certFiles.size();
        int numStore = crypto.getTrustStore().size();

        BufferedInputStream bis;
        ArrayList<byte[]> certBytesList = new ArrayList<>();
        ArrayList<String> certIDs = new ArrayList<>();
        byte[] certB;
        for (File certFile : certFiles) {
            certB = IOUtils.toByteArray(new FileInputStream(certFile));
            certBytesList.add(certB);
            bis = new BufferedInputStream(new ByteArrayInputStream(certB));
            certIDs.add(Integer.toString(cf.generateCertificate(bis).hashCode()));
        }
        crypto.loadCACertificatesAsBytes(certBytesList);
        assertEquals(crypto.getTrustStore().size(), numStore + numFiles);
        for (String cID : certIDs) {
            assertTrue(crypto.getTrustStore().containsAlias(cID));
        }
    } catch (KeyStoreException | CryptoException | IOException | CertificateException e) {
        fail("testLoadCACerts should not have thrown exception. Error: " + e.getMessage());
        e.printStackTrace();
    }
}
 
开发者ID:hyperledger,项目名称:fabric-sdk-java,代码行数:29,代码来源:CryptoPrimitivesTest.java

示例15: testValidateBadCertificateByteArray

import org.apache.commons.compress.utils.IOUtils; //导入方法依赖的package包/类
@Test
public void testValidateBadCertificateByteArray() {
    try {
        BufferedInputStream bis = new BufferedInputStream(this.getClass().getResourceAsStream("/notsigned.crt"));
        byte[] certBytes = IOUtils.toByteArray(bis);

        assertFalse(crypto.validateCertificate(certBytes));
    } catch (IOException e) {
        Assert.fail("cannot read cert file");
    }
}
 
开发者ID:hyperledger,项目名称:fabric-sdk-java,代码行数:12,代码来源:CryptoPrimitivesTest.java


注:本文中的org.apache.commons.compress.utils.IOUtils.toByteArray方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。