java.nio.file.Files Java Examples

The following examples show how to use java.nio.file.Files. 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: CompressingTempFileStore.java    From nexus-repository-apt with Eclipse Public License 1.0 7 votes vote down vote up
public Writer openOutput(String key) throws UncheckedIOException {
  try {
    if (holdersByKey.containsKey(key)) {
      throw new IllegalStateException("Output already opened");
    }
    FileHolder holder = new FileHolder();
    holdersByKey.put(key, holder);
    return new OutputStreamWriter(new TeeOutputStream(
        new TeeOutputStream(new GZIPOutputStream(Files.newOutputStream(holder.gzTempFile)),
            new BZip2CompressorOutputStream(Files.newOutputStream(holder.bzTempFile))),
        Files.newOutputStream(holder.plainTempFile)), Charsets.UTF_8);
  }
  catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example #2
Source File: SerialKillerTest.java    From SerialKiller with Apache License 2.0 6 votes vote down vote up
@Test
public void testReload() throws Exception {
    Path tempFile = Files.createTempFile("sk-", ".conf");
    Files.copy(new File("src/test/resources/blacklist-all-refresh-10-ms.conf").toPath(), tempFile, REPLACE_EXISTING);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    try (ObjectOutputStream stream = new ObjectOutputStream(bytes)) {
        stream.writeObject(42);
    }

    try (ObjectInputStream stream = new SerialKiller(new ByteArrayInputStream(bytes.toByteArray()), tempFile.toAbsolutePath().toString())) {

        Files.copy(new File("src/test/resources/whitelist-all.conf").toPath(), tempFile, REPLACE_EXISTING);
        Thread.sleep(1000L); // Wait to ensure the file is fully copied
        Files.setLastModifiedTime(tempFile, FileTime.fromMillis(System.currentTimeMillis())); // Commons configuration watches file modified time
        Thread.sleep(1000L); // Wait to ensure a reload happens

        assertEquals(42, stream.readObject());
    }
}
 
Example #3
Source File: MMapOfflineDb.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Map<Integer, SecurityIndex> getSecurityIndexes(String workflowId, SecurityIndexId securityIndexId) {
    PersistenceContext context = getContext(workflowId);
    int securityIndexNum = context.getTable().getDescription().getColumnIndex(securityIndexId);
    Map<Integer, SecurityIndex> securityIndexes = new TreeMap<>();
    try {
        try (BufferedReader securityIndexesXmlReader = Files.newBufferedReader(context.getWorkflowDir().resolve(SECURITY_INDEXES_XML_FILE_NAME), StandardCharsets.UTF_8)) {
            String line;
            while ((line = securityIndexesXmlReader.readLine()) != null) {
                String[] tokens = line.split(Character.toString(CSV_SEPARATOR));
                int sampleId = Integer.parseInt(tokens[0]);
                int securityIndexNum2 = Integer.parseInt(tokens[1]);
                if (securityIndexNum2 == securityIndexNum) {
                    String xml = tokens[2];
                    try (StringReader reader = new StringReader(xml)) {
                        SecurityIndex securityIndex = SecurityIndexParser.fromXml(securityIndexId.getContingencyId(), reader).get(0);
                        securityIndexes.put(sampleId, securityIndex);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return securityIndexes;
}
 
Example #4
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void scan(Path root, Path directory, String basePath, BuildProducer<HotDeploymentWatchedFileBuildItem> watchedPaths,
        BuildProducer<TemplatePathBuildItem> templatePaths,
        BuildProducer<NativeImageResourceBuildItem> nativeImageResources)
        throws IOException {
    try (Stream<Path> files = Files.list(directory)) {
        Iterator<Path> iter = files.iterator();
        while (iter.hasNext()) {
            Path filePath = iter.next();
            if (Files.isRegularFile(filePath)) {
                LOGGER.debugf("Found template: %s", filePath);
                String templatePath = root.relativize(filePath).toString();
                if (File.separatorChar != '/') {
                    templatePath = templatePath.replace(File.separatorChar, '/');
                }
                produceTemplateBuildItems(templatePaths, watchedPaths, nativeImageResources, basePath, templatePath,
                        filePath);
            } else if (Files.isDirectory(filePath)) {
                LOGGER.debugf("Scan directory: %s", filePath);
                scan(root, filePath, basePath, watchedPaths, templatePaths, nativeImageResources);
            }
        }
    }
}
 
Example #5
Source File: FileActionLogger.java    From LuckPerms with MIT License 6 votes vote down vote up
public Log getLog() throws IOException {
    if (!Files.exists(this.contentFile)) {
        return Log.empty();
    }

    Log.Builder log = Log.builder();

    try (BufferedReader reader = Files.newBufferedReader(this.contentFile, StandardCharsets.UTF_8)) {
        String line;
        while ((line = reader.readLine()) != null) {
            try {
                JsonElement parsed = GsonProvider.parser().parse(line);
                log.add(ActionJsonSerializer.deserialize(parsed));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return log.build();
}
 
Example #6
Source File: FieldSetAccessibleTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
Stream<String> folderToStream(String folderName) {
    final File root = new File(folderName);
    if (root.canRead() && root.isDirectory()) {
        final Path rootPath = root.toPath();
        try {
            return Files.walk(rootPath)
                .filter(p -> p.getFileName().toString().endsWith(".class"))
                .map(rootPath::relativize)
                .map(p -> p.toString().replace(File.separatorChar, '/'));
        } catch (IOException x) {
            x.printStackTrace(System.err);
            skipped.add(folderName);
        }
    } else {
        cantread.add(folderName);
    }
    return Collections.<String>emptyList().stream();
}
 
Example #7
Source File: RegexBasedPartitionedRetrieverTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@AfterClass
public void cleanup() throws IOException {
  Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
        throws IOException {
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc)
        throws IOException {
      Files.delete(dir);
      return FileVisitResult.CONTINUE;
    }
  });
}
 
Example #8
Source File: RustBinaryIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleBinaryIncremental() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "simple_binary", tmp);
  workspace.setUp();
  BuckBuildLog buildLog;

  workspace
      .runBuckCommand("build", "-c", "rust#default.incremental=opt", "//:xyzzy#check")
      .assertSuccess();
  buildLog = workspace.getBuildLog();
  buildLog.assertTargetBuiltLocally("//:xyzzy#check");

  workspace
      .runBuckCommand("build", "-c", "rust#default.incremental=dev", "//:xyzzy")
      .assertSuccess();
  buildLog = workspace.getBuildLog();
  buildLog.assertTargetBuiltLocally("//:xyzzy");

  assertTrue(
      Files.isDirectory(workspace.resolve("buck-out/tmp/rust-incremental/dev/binary/default")));
  assertTrue(
      Files.isDirectory(workspace.resolve("buck-out/tmp/rust-incremental/opt/check/default")));
}
 
Example #9
Source File: TestHostConfigAutomaticDeployment.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testSetContextClassName() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        StandardHost standardHost = (StandardHost) host;
        standardHost.setContextClass(TesterContext.class.getName());
    }

    // Copy the WAR file
    File war = new File(host.getAppBaseFile(),
            APP_NAME.getBaseName() + ".war");
    Files.copy(WAR_XML_SOURCE.toPath(), war.toPath());

    // Deploy the copied war
    tomcat.start();
    host.backgroundProcess();

    // Check the Context class
    Context ctxt = (Context) host.findChild(APP_NAME.getName());

    Assert.assertTrue(ctxt instanceof TesterContext);
}
 
Example #10
Source File: PackagedProgramTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtractContainedLibraries() throws Exception {
	String s = "testExtractContainedLibraries";
	byte[] nestedJarContent = s.getBytes(ConfigConstants.DEFAULT_CHARSET);
	File fakeJar = temporaryFolder.newFile("test.jar");
	try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fakeJar))) {
		ZipEntry entry = new ZipEntry("lib/internalTest.jar");
		zos.putNextEntry(entry);
		zos.write(nestedJarContent);
		zos.closeEntry();
	}

	final List<File> files = PackagedProgram.extractContainedLibraries(fakeJar.toURI().toURL());
	Assert.assertEquals(1, files.size());
	Assert.assertArrayEquals(nestedJarContent, Files.readAllBytes(files.iterator().next().toPath()));
}
 
Example #11
Source File: DumpPlatformClassPath.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Writes the given entry names and data to a jar archive at the given path. */
private static void writeEntries(Path output, Map<String, InputStream> entries)
    throws IOException {
  if (!entries.containsKey("java/lang/Object.class")) {
    throw new AssertionError(
        "\nCould not find java.lang.Object on bootclasspath; something has gone terribly wrong.\n"
            + "Please file a bug: https://github.com/bazelbuild/bazel/issues");
  }
  try (OutputStream os = Files.newOutputStream(output);
      BufferedOutputStream bos = new BufferedOutputStream(os, 65536);
      JarOutputStream jos = new JarOutputStream(bos)) {
    entries.entrySet().stream()
        .forEachOrdered(
            entry -> {
              try {
                addEntry(jos, entry.getKey(), entry.getValue());
              } catch (IOException e) {
                throw new UncheckedIOException(e);
              }
            });
  }
}
 
Example #12
Source File: PersistTestModuleBuilderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void generatesPersistenceXml() throws Exception {
  Path path =
      new PersistTestModuleBuilder()
          .setDriver("org.h2.Driver")
          .addEntityClass(MyEntity1.class)
          .addEntityClass(
              "org.eclipse.che.commons.test.db.PersistTestModuleBuilderTest$MyEntity2")
          .setUrl("jdbc:h2:mem:test")
          .setUser("username")
          .setPassword("secret")
          .setLogLevel("FINE")
          .setPersistenceUnit("test-unit")
          .setExceptionHandler(MyExceptionHandler.class)
          .setProperty("custom-property", "value")
          .savePersistenceXml();

  URL url =
      Thread.currentThread()
          .getContextClassLoader()
          .getResource("org/eclipse/che/commons/test/db/test-persistence-1.xml");
  assertNotNull(url);
  assertEquals(new String(Files.readAllBytes(path), UTF_8), Resources.toString(url, UTF_8));
}
 
Example #13
Source File: Font.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Used with the byte count tracker for fonts created from streams.
 * If a thread can create temp files anyway, no point in counting
 * font bytes.
 */
private static boolean hasTempPermission() {

    if (System.getSecurityManager() == null) {
        return true;
    }
    File f = null;
    boolean hasPerm = false;
    try {
        f = Files.createTempFile("+~JT", ".tmp").toFile();
        f.delete();
        f = null;
        hasPerm = true;
    } catch (Throwable t) {
        /* inc. any kind of SecurityException */
    }
    return hasPerm;
}
 
Example #14
Source File: RevertSamSpark.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("unchecked")
static List<String>  validateOutputParamsByReadGroup(final String output, final String outputMap) throws IOException {
    final List<String> errors = new ArrayList<>();
    if (output != null) {
        if (!Files.isDirectory(IOUtil.getPath(output))) {
            errors.add("When '--output-by-readgroup' is set and output is provided, it must be a directory: " + output);
        }
        return errors;
    }
    // output is null if we reached here
    if (outputMap == null) {
        errors.add("Must provide either output or outputMap when '--output-by-readgroup' is set.");
        return errors;
    }
    if (!Files.isReadable(IOUtil.getPath(outputMap))) {
        errors.add("Cannot read outputMap " + outputMap);
        return errors;
    }
    final FeatureReader<TableFeature>  parser = AbstractFeatureReader.getFeatureReader(outputMap, new TableCodec(null),false);
    if (!isOutputMapHeaderValid((List<String>)parser.getHeader())) {
        errors.add("Invalid header: " + outputMap + ". Must be a tab-separated file with +"+OUTPUT_MAP_READ_GROUP_FIELD_NAME+"+ as first column and output as second column.");
    }
    return errors;
}
 
Example #15
Source File: PathOperationsTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteDir ()
{
  final Path aDir = Paths.get ("deldir.test");
  try
  {
    _expectedError (PathOperations.deleteDir (aDir), EFileIOErrorCode.SOURCE_DOES_NOT_EXIST);
    assertFalse (Files.isDirectory (aDir));
    _expectedSuccess (PathOperations.createDir (aDir));
    assertEquals (0, PathHelper.getDirectoryObjectCount (aDir));
    _expectedSuccess (PathOperations.deleteDir (aDir));
    assertFalse (Files.isDirectory (aDir));
  }
  finally
  {
    PathOperations.deleteDirRecursive (aDir);
  }

  try
  {
    PathOperations.deleteDir (null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example #16
Source File: SesarSample.java    From ET_Redux with Apache License 2.0 6 votes vote down vote up
public static SesarSample createSesarSampleFromSesarRecord(String igsn) {
    SesarSample sesarSample = null;
    try {
        File sample = retrieveXMLFileFromSesarForIGSN(igsn);

        // replace the results tag with sample tag
        // todo make more robust
        Path file = sample.toPath();
        byte[] fileArray;
        fileArray = Files.readAllBytes(file);
        String str = new String(fileArray, "UTF-8");
        str = str.replace("results", "sample");
        fileArray = str.getBytes();
        Files.write(file, fileArray);

        sesarSample = (SesarSample) readXMLObject(file.toString());
    } catch (IOException | ETException iOException) {
    }

    return sesarSample;
}
 
Example #17
Source File: SubmitAndSyncUnicodeFileTypeOnUnicodeEnabledServerTest.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodedByeGb18030WithWinLineEndingFileWhenClientCharsetIsMatchUnderServerUnicodeEnabled_UnixClientLineEnding() throws Exception{
    String perforceCharset = "cp936";
    login(perforceCharset);

    File testResourceFile = loadFileFromClassPath("com/perforce/p4java/common/io/gb18030_win_line_endings.txt");
    long originalFileSize = Files.size(testResourceFile.toPath());
    Charset matchCharset = Charset.forName(PerforceCharsets.getJavaCharsetName(perforceCharset));
    long utf8EncodedOriginalFileSize = getUnicodeFileSizeAfterEncodedByUtf8(
            testResourceFile,
            matchCharset);

    testSubmitFile(
            "p4TestUnixLineend",
            testResourceFile,
            "unicode",
            utf8EncodedOriginalFileSize,
            originalFileSize
    );
}
 
Example #18
Source File: StandardDirectoryFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Override for more efficient moves.
 * 
 * Intended for use with replication - use
 * carefully - some Directory wrappers will
 * cache files for example.
 * 
 * You should first {@link Directory#sync(java.util.Collection)} any file that will be 
 * moved or avoid cached files through settings.
 * 
 * @throws IOException
 *           If there is a low-level I/O error.
 */
@Override
public void move(Directory fromDir, Directory toDir, String fileName, IOContext ioContext)
    throws IOException {
  
  Directory baseFromDir = getBaseDir(fromDir);
  Directory baseToDir = getBaseDir(toDir);
  
  if (baseFromDir instanceof FSDirectory && baseToDir instanceof FSDirectory) {

    Path path1 = ((FSDirectory) baseFromDir).getDirectory().toAbsolutePath();
    Path path2 = ((FSDirectory) baseToDir).getDirectory().toAbsolutePath();
    
    try {
      Files.move(path1.resolve(fileName), path2.resolve(fileName), StandardCopyOption.ATOMIC_MOVE);
    } catch (AtomicMoveNotSupportedException e) {
      Files.move(path1.resolve(fileName), path2.resolve(fileName));
    }
    return;
  }

  super.move(fromDir, toDir, fileName, ioContext);
}
 
Example #19
Source File: AppleLibraryIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppleLibraryWithDefaultsInRuleBuildsSomething() throws IOException {
  assumeTrue(Platform.detect() == Platform.MACOS);
  assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));

  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(
          this, "apple_library_with_platform_and_type", tmp);
  workspace.setUp();
  ProjectFilesystem filesystem =
      TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());

  BuildTarget target = BuildTargetFactory.newInstance("//Libraries/TestLibrary:TestLibrary");
  ProcessResult result = workspace.runBuckCommand("build", target.getFullyQualifiedName());
  result.assertSuccess();

  BuildTarget implicitTarget =
      target.withAppendedFlavors(
          InternalFlavor.of("shared"), InternalFlavor.of("iphoneos-arm64"));
  Path outputPath =
      workspace.getPath(BuildTargetPaths.getGenPath(filesystem, implicitTarget, "%s"));
  assertTrue(Files.exists(outputPath));
}
 
Example #20
Source File: ConversionTest.java    From carbon-kernel with Apache License 2.0 6 votes vote down vote up
private boolean isOSGiBundle(Path bundlePath, String bundleSymbolicName) throws IOException, CarbonToolException {
    if (Files.exists(bundlePath)) {
        boolean validSymbolicName, exportPackageAttributeCheck, importPackageAttributeCheck;
        try (FileSystem zipFileSystem = BundleGeneratorUtils.createZipFileSystem(bundlePath, false)) {
            Path manifestPath = zipFileSystem.getPath(Constants.JAR_MANIFEST_FOLDER, Constants.MANIFEST_FILE_NAME);
            Manifest manifest = new Manifest(Files.newInputStream(manifestPath));

            Attributes attributes = manifest.getMainAttributes();
            String actualBundleSymbolicName = attributes.getValue(Constants.BUNDLE_SYMBOLIC_NAME);
            validSymbolicName = ((actualBundleSymbolicName != null) && ((bundleSymbolicName != null)
                    && bundleSymbolicName.equals(actualBundleSymbolicName)));
            exportPackageAttributeCheck = attributes.getValue(Constants.EXPORT_PACKAGE) != null;
            importPackageAttributeCheck = attributes.getValue(Constants.DYNAMIC_IMPORT_PACKAGE) != null;
        }
        return (validSymbolicName && exportPackageAttributeCheck && importPackageAttributeCheck);
    } else {
        return false;
    }
}
 
Example #21
Source File: TestExecuteStreamCommand.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteIngestAndUpdatePutToAttribute() throws IOException {
    File exJar = new File("src/test/resources/ExecuteCommand/TestIngestAndUpdate.jar");
    File dummy = new File("src/test/resources/ExecuteCommand/1000bytes.txt");
    File dummy10MBytes = new File("target/10MB.txt");
    byte[] bytes = Files.readAllBytes(dummy.toPath());
    try (FileOutputStream fos = new FileOutputStream(dummy10MBytes)) {
        for (int i = 0; i < 10000; i++) {
            fos.write(bytes, 0, 1000);
        }
    }
    String jarPath = exJar.getAbsolutePath();
    exJar.setExecutable(true);
    final TestRunner controller = TestRunners.newTestRunner(ExecuteStreamCommand.class);
    controller.enqueue(dummy10MBytes.toPath());
    controller.setProperty(ExecuteStreamCommand.EXECUTION_COMMAND, "java");
    controller.setProperty(ExecuteStreamCommand.EXECUTION_ARGUMENTS, "-jar;" + jarPath);
    controller.setProperty(ExecuteStreamCommand.PUT_OUTPUT_IN_ATTRIBUTE, "outputDest");
    controller.run(1);
    controller.assertTransferCount(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP, 1);
    controller.assertTransferCount(ExecuteStreamCommand.OUTPUT_STREAM_RELATIONSHIP, 0);
    List<MockFlowFile> flowFiles = controller.getFlowFilesForRelationship(ExecuteStreamCommand.ORIGINAL_RELATIONSHIP);
    String result = flowFiles.get(0).getAttribute("outputDest");

    assertTrue(Pattern.compile("nifi-standard-processors:ModifiedResult\r?\n").matcher(result).find());
}
 
Example #22
Source File: KnowNERCorpusCheckerIntegrationTest.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnSuccessIfCorpusAndConfigurationExist() throws IOException, KnowNERLanguageConfiguratorException {
	Path corpusDir = Files.createDirectories(Paths.get(tempMainDir.toString(),language,
			CorpusConfiguration.CORPUS_DIRECTORY_NAME,
			CorpusConfiguration.DEFAULT_CORPUS_NAME));
	Files.write(Paths.get(corpusDir.toString(), CorpusConfiguration.DEFAULT_FILE_NAME),
			Collections.nCopies(6, "-DOCSTART-"));
	Files.write(Paths.get(corpusDir.toString(), CorpusConfiguration.DEFAULT_CORPUS_CONFIG_NAME),
			("{corpusFormat: DEFAULT, " +
					"rangeMap: {" +
					"TRAIN: [0,1]," +
					"TESTA: [2,3]," +
					"TESTB: [4,5]," +
					"TRAINA: [0,3]}}").getBytes());

	KnowNERCorpusChecker checker = new KnowNERCorpusChecker(tempMainDir.toString(), language, 6);
	assertTrue(checker.check().isSuccess());
}
 
Example #23
Source File: URLResource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isDirectory() {
    Path file = getFilePath();
    if (file != null) {
        return Files.isDirectory(file);
    } else if (url.getPath().endsWith("/")) {
        return true;
    }
    return false;
}
 
Example #24
Source File: XMLProperties.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new XMLPropertiesTest object.
 *
 * @param file the file that properties should be read from and written to.
 * @throws IOException if an error occurs loading the properties.
 */
public XMLProperties(Path file) throws IOException {
    this.file = file;
    if (Files.notExists(file)) {
        // Attempt to recover from this error case by seeing if the
        // tmp file exists. It's possible that the rename of the
        // tmp file failed the last time Jive was running,
        // but that it exists now.
        Path tempFile;
        tempFile = file.getParent().resolve(file.getFileName() + ".tmp");
        if (Files.exists(tempFile)) {
            Log.error("WARNING: " + file.getFileName() + " was not found, but temp file from " +
                    "previous write operation was. Attempting automatic recovery." +
                    " Please check file for data consistency.");
            Files.move(tempFile, file, StandardCopyOption.REPLACE_EXISTING);
        }
        // There isn't a possible way to recover from the file not
        // being there, so throw an error.
        else {
            throw new NoSuchFileException("XML properties file does not exist: "
                    + file.getFileName());
        }
    }
    // Check read and write privs.
    if (!Files.isReadable(file)) {
        throw new IOException("XML properties file must be readable: " + file.getFileName());
    }
    if (!Files.isWritable(file)) {
        throw new IOException("XML properties file must be writable: " + file.getFileName());
    }

    try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
         buildDoc(reader);
    }
}
 
Example #25
Source File: AbbyyInputValidatorTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void validate_destinationFileAlreadyExists_ValidationException() {
    //Arrange
    R abbyyRequestMock = mockAbbyyRequest();

    Path destinationFileMock = mock(Path.class);
    PowerMockito.when(Files.exists(destinationFileMock)).thenReturn(true);
    when(abbyyRequestMock.getDestinationFile()).thenReturn(destinationFileMock);

    //Act
    ValidationException ex = this.sut.validate(abbyyRequestMock);

    //Assert
    assertNotNull(ex);
}
 
Example #26
Source File: ReferenceFileSourceUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(expectedExceptions = UserException.MissingReferenceDictFile.class)
public void testReferenceInPathWithoutDict() throws IOException {
    try (FileSystem jimfs = Jimfs.newFileSystem(Configuration.unix())) {
        final Path refPath = jimfs.getPath("reference.fasta");
        Files.createFile(refPath);
        final Path faiFile = jimfs.getPath("reference.fasta.fai");
        Files.createFile(faiFile);

        new ReferenceFileSource(refPath);
    }
}
 
Example #27
Source File: FaultyFileSystem.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
Example #28
Source File: X509CertRequestTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateCertReqPublicKey() throws IOException {
    Path path = Paths.get("src/test/resources/valid.csr");
    String csr = new String(Files.readAllBytes(path));
    
    X509CertRequest certReq = new X509CertRequest(csr);
    assertNotNull(certReq);
    
    final String ztsPublicKey = "-----BEGIN PUBLIC KEY-----\n"
            + "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKrvfvBgXWqWAorw5hYJu3dpOJe0gp3n\n"
            + "TgiiPGT7+jzm6BRcssOBTPFIMkePT2a8Tq+FYSmFnHfbQjwmYw2uMK8CAwEAAQ==\n"
            + "-----END PUBLIC KEY-----";
    
    assertTrue(certReq.validatePublicKeys(ztsPublicKey));
}
 
Example #29
Source File: PluginsService.java    From crate with Apache License 2.0 5 votes vote down vote up
Bundle(PluginInfo plugin, Path dir) throws IOException {
    this.plugin = Objects.requireNonNull(plugin);
    Set<URL> urls = new LinkedHashSet<>();
    // gather urls for jar files
    try (DirectoryStream<Path> jarStream = Files.newDirectoryStream(dir, "*.jar")) {
        for (Path jar : jarStream) {
            // normalize with toRealPath to get symlinks out of our hair
            URL url = jar.toRealPath().toUri().toURL();
            if (urls.add(url) == false) {
                throw new IllegalStateException("duplicate codebase: " + url);
            }
        }
    }
    this.urls = Objects.requireNonNull(urls);
}
 
Example #30
Source File: FileInstaller.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file,
        BasicFileAttributes attrs) throws IOException {
    if (!file.toFile().isFile()) {
        return FileVisitResult.CONTINUE;
    }
    Path relativePath = copyFrom.relativize(file);
    Path destination = copyTo.resolve(relativePath);
    Files.copy(file, destination, StandardCopyOption.COPY_ATTRIBUTES);
    return FileVisitResult.CONTINUE;
}