Java Code Examples for java.nio.file.Files#newInputStream()

The following examples show how to use java.nio.file.Files#newInputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceAccountCredentialsWithAccessToken() throws IOException, GeneralSecurityException {
  Assume.assumeNotNull(credentials);
  final GoogleCredentials serviceAccountCredentials;
  final URI keyUri = URI.create("gs://styx-oss-test/styx-test-user.json");
  try (InputStream is = Files.newInputStream(Paths.get(keyUri))) {
    serviceAccountCredentials = GoogleCredentials.fromStream(is)
        .createScoped(ImmutableList.of(
            "https://www.googleapis.com/auth/cloud-platform",
            "https://www.googleapis.com/auth/userinfo.email"));
  }
  serviceAccountCredentials.refresh();
  final GoogleCredentials accessTokenCredentials = GoogleCredentials.newBuilder()
      .setAccessToken(serviceAccountCredentials.getAccessToken())
      .build();
  assertThat(canAcquireIdToken(accessTokenCredentials), is(true));
}
 
Example 2
Source File: GzipExtractor.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
public void deflateGz(Path input) {
    File tempFile;
    tempFile = new File(getDeflatedFile(input).toUri());

    try (
            InputStream fin = Files.newInputStream(input);
            BufferedInputStream in = new BufferedInputStream(fin);
            GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
            FileOutputStream out = new FileOutputStream(tempFile)) {

        final byte[] buffer = new byte[4096];
        int n;
        while (-1 != (n = gzIn.read(buffer))) {
            out.write(buffer, 0, n);
        }

    } catch (IOException e) {
        LOG.warn("[{} - {}]: Error extracting gzip  {}.", request.getLogName(), request.getId(), e.getMessage());

        throw new IllegalStateException(e);
    }
}
 
Example 3
Source File: GroovySourceCodeWriterTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
private List<String> writeSingleType(GroovySourceCode sourceCode, String location) throws IOException {
	Path source = writeSourceCode(sourceCode).resolve(location);
	try (InputStream stream = Files.newInputStream(source)) {
		String[] lines = StreamUtils.copyToString(stream, StandardCharsets.UTF_8).split("\\r?\\n");
		return Arrays.asList(lines);
	}
}
 
Example 4
Source File: SES_SignatureTest.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
@Test
void build() throws Exception {
    Path p = Paths.get("src/test/resources", "UserV1.esl");
    final Path out = Paths.get("target/SignedValue.dat");

    Path userP12 = Paths.get("src/test/resources", "USER.p12");
    Certificate userCert = PKCS12Tools.ReadUserCert(userP12, "private", "777777");

    byte[] mockDigest = new byte[32];
    SESeal seal = SESeal.getInstance(Files.readAllBytes(p));
    String propertyInfo = "/Doc_0/Signs/Signatures.xml";
    ASN1UTCTime signUTCTime = new ASN1UTCTime(new Date(), Locale.CHINA);
    TBS_Sign tbsSign = new TBS_Sign()
            .setVersion(new ASN1Integer(1))
            .setEseal(seal)
            .setTimeInfo(new DERBitString(signUTCTime))
            .setDataHash(new DERBitString(mockDigest))
            .setPropertyInfo(new DERIA5String(propertyInfo))
            .setCert(new DEROctetString(userCert.getEncoded()))
            .setSignatureAlgorithm(GMObjectIdentifiers.sm2sign_with_sm3);


    char[] pwd = "777777".toCharArray();
    KeyStore userKs = KeyStore.getInstance("PKCS12", new BouncyCastleProvider());
    try (InputStream rootKsIn = Files.newInputStream(userP12)) {
        userKs.load(rootKsIn, pwd);

        // 取得印章制作者证书的私钥
        PrivateKey privateKey = (PrivateKey) userKs.getKey("private", pwd);
        Signature signature = Signature.getInstance("SM3withSm2", "BC");
        signature.initSign(privateKey);
        signature.update(tbsSign.getEncoded("DER"));
        byte[] sign = signature.sign();
        SES_Signature sesSignature = new SES_Signature(tbsSign, new DERBitString(sign));
        Files.write(out, sesSignature.getEncoded("DER"));
    }

}
 
Example 5
Source File: Http2Server.java    From http2-examples with Apache License 2.0 5 votes vote down vote up
private static KeyStore loadKeyStore(String name) throws Exception {
    String storeLoc = System.getProperty(name);
    final InputStream stream;
    if(storeLoc == null) {
        stream = Http2Server.class.getResourceAsStream(name);
    } else {
        stream = Files.newInputStream(Paths.get(storeLoc));
    }

    try(InputStream is = stream) {
        KeyStore loadedKeystore = KeyStore.getInstance("JKS");
        loadedKeystore.load(is, STORE_PASSWORD);
        return loadedKeystore;
    }
}
 
Example 6
Source File: XPathTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * XPath.evaluate(java.lang.String expression, InputSource source, QName
 * returnType) throws XPathExpressionException if expression is blank " ".
 *
 * @throws Exception If any errors occur.
 */
@Test(expectedExceptions = XPathExpressionException.class)
public void testCheckXPath32() throws Exception {
    try (InputStream is = Files.newInputStream(XML_PATH)) {
        xpath.evaluate(" ", new InputSource(is), STRING);
    }
}
 
Example 7
Source File: LocalComputationManager.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private void preProcess(Path workingDir, Command command, int executionIndex) throws IOException {
    // pre-processing
    for (InputFile file : command.getInputFiles()) {
        String fileName = file.getName(executionIndex);

        Path path = checkInputFileExistsInWorkingAndCommons(workingDir, fileName, file);
        if (file.getPreProcessor() != null) {
            switch (file.getPreProcessor()) {
                case FILE_GUNZIP:
                    // gunzip the file
                    try (InputStream is = new GZIPInputStream(Files.newInputStream(path));
                         OutputStream os = Files.newOutputStream(workingDir.resolve(fileName.substring(0, fileName.length() - 3)))) {
                        ByteStreams.copy(is, os);
                    }
                    break;
                case ARCHIVE_UNZIP:
                    // extract the archive
                    try (ZipFile zipFile = new ZipFile(path)) {
                        for (ZipEntry ze : Collections.list(zipFile.entries())) {
                            Files.copy(zipFile.getInputStream(ze.getName()), workingDir.resolve(ze.getName()), REPLACE_EXISTING);
                        }
                    }
                    break;

                default:
                    throw new AssertionError("Unexpected FilePreProcessor value: " + file.getPreProcessor());
            }
        }
    }
}
 
Example 8
Source File: ProcessBackgroundExecutionState.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns the process console log contents.
 *
 * @return the log as a string or {@code null} if the log cannot be read from its temp file.
 */
public String getLogContent() {
	try (InputStream is = Files.newInputStream(logFilePath)) {
		return Tools.readTextFile(is);
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 9
Source File: FileSystemUtils.java    From data-prep with Apache License 2.0 5 votes vote down vote up
static boolean matches(Path pathFile, String contentId, FolderContentType contentType) {
    boolean passFilter = false;
    try (InputStream inputStream = Files.newInputStream(pathFile)) {
        FolderEntry folderEntry = readEntryFromStream(inputStream);
        if (Objects.equals(contentType, folderEntry.getContentType()) && //
                StringUtils.equalsIgnoreCase(folderEntry.getContentId(), contentId)) {
            passFilter = true;
        }
    } catch (IOException e) {
        throw new TDPException(UNABLE_TO_READ_FOLDER_ENTRY, e, build().put("path", pathFile));
    }
    return passFilter;
}
 
Example 10
Source File: BinaryDictionary.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected final InputStream getResource(String suffix) throws IOException {
  switch(resourceScheme) {
    case CLASSPATH:
      return getClassResource(resourcePath + suffix);
    case FILE:
      return Files.newInputStream(Paths.get(resourcePath + suffix));
    default:
      throw new IllegalStateException("unknown resource scheme " + resourceScheme);
  }
}
 
Example 11
Source File: TemplatesTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private void compareToFile(String expected) throws IOException {

    try (InputStream testFileStream = Files.newInputStream(Paths.get(fileLocation));
        InputStream expectedFileStream = getDataFile(expected);
        Scanner expectedScanner = new Scanner(expectedFileStream);
        Scanner actualScanner = new Scanner(testFileStream)) {
      String expectedContent = expectedScanner.useDelimiter("\\Z").next();
      String actualContent = actualScanner.useDelimiter("\\Z").next();
      Assert.assertEquals(expectedContent, actualContent);
    }
  }
 
Example 12
Source File: PartImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public InputStream getInputStream() throws IOException {
    if (formValue.isFile()) {
        return new BufferedInputStream(Files.newInputStream(formValue.getPath()));
    } else {
        String requestedCharset = servletRequest.getCharacterEncoding();
        String charset = requestedCharset != null ? requestedCharset : servletContext.getDeployment().getDefaultRequestCharset().name();
        return new ByteArrayInputStream(formValue.getValue().getBytes(charset));
    }
}
 
Example 13
Source File: FilesystemActionCache.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Override
public ActionResult get(ActionKey actionKey) {
  String hash = actionKey.getDigest().getHash();
  Path resultPath = path.resolve(hash);
  try (InputStream in = Files.newInputStream(resultPath)) {
    return ActionResult.parseFrom(ByteString.readFrom(in));
  } catch (IOException e) {
    return null;
  }
}
 
Example 14
Source File: IndexSerializer.java    From Noexes with GNU General Public License v3.0 5 votes vote down vote up
public static List<me.mdbell.noexs.dump.DumpIndex> read(Path from) throws IOException {
    List<me.mdbell.noexs.dump.DumpIndex> indices = new ArrayList<>();
    try(XMLDecoder decoder = new XMLDecoder(Files.newInputStream(from))) {
        int count = (Integer) decoder.readObject();
        for(int i = 0; i < count; i++) {
            long addr = (Long) decoder.readObject();
            long pos = (Long) decoder.readObject();
            long size = (Long) decoder.readObject();
            indices.add(new DumpIndex(addr, pos, size));
        }
    }
    return indices;
}
 
Example 15
Source File: FileUtil.java    From RepoSense with MIT License 4 votes vote down vote up
/**
 * Unzips the contents of the {@code zipSourcePath} into {@code outputPath}.
 * @throws IOException if {@code zipSourcePath} is an invalid path.
 */
public static void unzip(Path zipSourcePath, Path outputPath) throws IOException {
    try (InputStream is = Files.newInputStream(zipSourcePath)) {
        unzip(is, outputPath);
    }
}
 
Example 16
Source File: FileUtils.java    From startup-os with Apache License 2.0 4 votes vote down vote up
/** Reads a proto binary file into a proto. */
public Message readProtoBinary(String path, Message.Builder builder) throws IOException {
  InputStream input = Files.newInputStream(fileSystem.getPath(expandHomeDirectory(path)));
  return builder.build().getParserForType().parseFrom(input);
}
 
Example 17
Source File: PathFileObject.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public InputStream openInputStream() throws IOException {
    return Files.newInputStream(path);
}
 
Example 18
Source File: ZipInputFile.java    From importer-exporter with Apache License 2.0 4 votes vote down vote up
@Override
public InputStream openStream() throws IOException {
    return new BufferedInputStream(Files.newInputStream(getFileSystem().getPath(contentFile)));
}
 
Example 19
Source File: Resources.java    From doma with Apache License 2.0 4 votes vote down vote up
@Override
public InputStream openInputStream() throws IOException {
  return Files.newInputStream(path);
}
 
Example 20
Source File: AffectedFilesResolver.java    From warnings-ng-plugin with MIT License 2 votes vote down vote up
/**
 * Returns the affected file in Jenkins' build folder.
 *
 * @param build
 *         the build
 * @param fileName
 *         the file name of the file to read from the build folder ^
 *
 * @return the file
 * @throws IOException
 *         if the file could not be found
 */
static InputStream asStream(final Run<?, ?> build, final String fileName) throws IOException {
    return Files.newInputStream(getFile(build, fileName));
}