當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。