Example usage for java.nio.file Path toFile

List of usage examples for java.nio.file Path toFile

Introduction

In this page you can find the example usage for java.nio.file Path toFile.

Prototype

default File toFile() 

Source Link

Document

Returns a File object representing this path.

Usage

From source file:io.fabric8.vertx.maven.plugin.utils.PackageHelper.java

/**
 * @param dir//from  w  w  w. j a v a  2s .co m
 * @param primaryArtifactFile
 * @return
 * @throws IOException
 */
public File build(Path dir, File primaryArtifactFile) {
    File classes = new File(dir.toFile(), "classes");
    build(classes, primaryArtifactFile);
    return createFatJar(dir);
}

From source file:io.github.swagger2markup.MarkdownConverterTest.java

@Test
public void testWithSeparatedDefinitions() throws IOException, URISyntaxException {
    //Given/* www. j a  va  2 s. c  o m*/
    Path file = Paths.get(MarkdownConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withSeparatedDefinitions()
            .withMarkupLanguage(MarkupLanguage.MARKDOWN).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("definitions");
    assertThat(files).hasSize(5).containsAll(expectedFiles);

    Path definitionsDirectory = outputDirectory.resolve("definitions");
    String[] definitions = definitionsDirectory.toFile().list();
    assertThat(definitions).hasSize(5)
            .containsAll(asList("Category.md", "Order.md", "Pet.md", "Tag.md", "User.md"));
}

From source file:io.github.swagger2markup.MarkdownConverterTest.java

@Test
public void testHandlesComposition() throws IOException, URISyntaxException {
    //Given// w  w  w.  j a va  2  s .  com
    Path file = Paths.get(MarkdownConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withSeparatedDefinitions()
            .withMarkupLanguage(MarkupLanguage.MARKDOWN).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);

    // Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("definitions");
    assertThat(files).hasSize(5).containsAll(expectedFiles);
    Path definitionsDirectory = outputDirectory.resolve("definitions");
    verifyMarkdownContainsFieldsInTables(definitionsDirectory.resolve("User.md").toFile(),
            ImmutableMap.<String, Set<String>>builder().put("User", ImmutableSet.of("id", "username",
                    "firstName", "lastName", "email", "password", "phone", "userStatus")).build());

}

From source file:com.google.cloud.tools.managedcloudsdk.install.TarGzExtractorProvider.java

@Override
public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException {

    progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

    String canonicalDestination = destination.toFile().getCanonicalPath();

    GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(Files.newInputStream(archive));
    try (TarArchiveInputStream in = new TarArchiveInputStream(gzipIn)) {
        TarArchiveEntry entry;/*from   w w  w  .j a  v  a2  s . c  o m*/
        while ((entry = in.getNextTarEntry()) != null) {
            Path entryTarget = destination.resolve(entry.getName());

            String canonicalTarget = entryTarget.toFile().getCanonicalPath();
            if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
                throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
            }

            progressListener.update(1);
            logger.fine(entryTarget.toString());

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else if (entry.isFile()) {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    IOUtils.copy(in, out);
                    PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                            PosixFileAttributeView.class);
                    if (attributeView != null) {
                        attributeView.setPermissions(PosixUtil.getPosixFilePermissions(entry.getMode()));
                    }
                }
            } else {
                // we don't know what kind of entry this is (we only process directories and files).
                logger.warning("Skipping entry (unknown type): " + entry.getName());
            }
        }
        progressListener.done();
    }
}

From source file:net.librec.data.convertor.appender.SocialDataAppender.java

/**
 * Read data from the data file. Note that we didn't take care of the
 * duplicated lines.//from   w w  w  .  j  a  va  2  s.co  m
 *
 * @param inputDataPath
 *            the path of the data file
 * @throws IOException if I/O error occurs during reading
 */
private void readData(String inputDataPath) throws IOException {
    // Table {row-id, col-id, rate}
    Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
    // Map {col-id, multiple row-id}: used to fast build a rating matrix
    Multimap<Integer, Integer> colMap = HashMultimap.create();
    // BiMap {raw id, inner id} userIds, itemIds
    final List<File> files = new ArrayList<File>();
    final ArrayList<Long> fileSizeList = new ArrayList<Long>();
    SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            fileSizeList.add(file.toFile().length());
            files.add(file.toFile());
            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(Paths.get(inputDataPath), finder);
    long allFileSize = 0;
    for (Long everyFileSize : fileSizeList) {
        allFileSize = allFileSize + everyFileSize.longValue();
    }
    // loop every dataFile collecting from walkFileTree
    for (File dataFile : files) {
        FileInputStream fis = new FileInputStream(dataFile);
        FileChannel fileRead = fis.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        int len;
        String bufferLine = new String();
        byte[] bytes = new byte[BSIZE];
        while ((len = fileRead.read(buffer)) != -1) {
            buffer.flip();
            buffer.get(bytes, 0, len);
            bufferLine = bufferLine.concat(new String(bytes, 0, len)).replaceAll("\r", "\n");
            String[] bufferData = bufferLine.split("(\n)+");
            boolean isComplete = bufferLine.endsWith("\n");
            int loopLength = isComplete ? bufferData.length : bufferData.length - 1;
            for (int i = 0; i < loopLength; i++) {
                String line = new String(bufferData[i]);
                String[] data = line.trim().split("[ \t,]+");
                String userA = data[0];
                String userB = data[1];
                Double rate = (data.length >= 3) ? Double.valueOf(data[2]) : 1.0;
                if (userIds.containsKey(userA) && userIds.containsKey(userB)) {
                    int row = userIds.get(userA);
                    int col = userIds.get(userB);
                    dataTable.put(row, col, rate);
                    colMap.put(col, row);
                }
            }
            if (!isComplete) {
                bufferLine = bufferData[bufferData.length - 1];
            }
            buffer.clear();
        }
        fileRead.close();
        fis.close();
    }
    int numRows = userIds.size(), numCols = userIds.size();
    // build rating matrix
    userSocialMatrix = new SparseMatrix(numRows, numCols, dataTable, colMap);
    // release memory of data table
    dataTable = null;
}

From source file:ch.mattrero.foldersync.FoldersSynchronizer.java

boolean syncDeleted(final Path sourceItem) {
    final Path backupItem = resolveBackupItemPath(sourceItem);

    try {//from w  ww .  j  av  a2  s. co m
        if (Files.isDirectory(backupItem)) {
            FileUtils.deleteDirectory(backupItem.toFile());
            logger.debug("Deleted directory " + backupItem);
        } else {
            Files.delete(backupItem);
            logger.debug("Deleted file " + backupItem);
        }
    } catch (final IOException e) {
        logger.warn("Failed to delete " + backupItem, e);
        return false;
    }

    return true;
}

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java

@Test
public void onPluginMetadataUnLoad_shouldClearExistingCacheAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path path = Paths.get(pluginDirPath.toString(), "foo.txt");
    FileUtils.forceMkdirParent(path.toFile());
    Files.write(path, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(path.toFile().exists());// w  w w  .  j  a v  a2 s  .co  m

    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);

    assetsService.onPluginMetadataRemove(PLUGIN_ID);

    assertFalse(path.toFile().exists());
    assertFalse(pluginDirPath.toFile().exists());
}

From source file:gndata.lib.config.AbstractConfig.java

/**
 * Serializes the config to json and writes it to a file. The method  uses {@link #getFilePath()}
 * for storing the configuration./*from   www .j  a  v  a2 s.c o m*/
 *
 * @throws IOException If the storing of the configuration failed.
 */
public void store() throws IOException {
    Path tmpPath = Paths.get(filePath);
    Files.createDirectories(tmpPath.getParent());

    try {
        ObjectMapper mapper = new ObjectMapper().enable(INDENT_OUTPUT).disable(FAIL_ON_EMPTY_BEANS);

        mapper.writeValue(tmpPath.toFile(), this);
    } catch (IOException e) {
        throw new IOException("Unable to write configuration file: " + this.filePath, e);
    }
}

From source file:io.github.swagger2markup.MarkdownConverterTest.java

@Test
public void testWithResponseHeaders() throws IOException, URISyntaxException {
    //Given/*from  ww  w .  ja  va 2  s  .co  m*/
    Path file = Paths
            .get(AsciidocConverterTest.class.getResource("/yaml/swagger_response_headers.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/response_headers");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.MARKDOWN)
            .build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);

    Path expectedFilesDirectory = Paths
            .get(AsciidocConverterTest.class.getResource("/expected/markdown/response_headers").toURI());
    DiffUtils.assertThatAllFilesAreEqual(expectedFilesDirectory, outputDirectory,
            "testWithResponseHeaders.html");
}

From source file:com.qwazr.library.audio.AudioParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final Path filePath, String extension,
        final String mimeType, final ParserResultBuilder resultBuilder) throws Exception {
    final AudioFile f = AudioFileIO.read(filePath.toFile());
    final ParserFieldsBuilder metas = resultBuilder.metas();
    metas.set(MIME_TYPE, findMimeType(extension, mimeType, EXTENSIONMAP::get));
    final Tag tag = f.getTag();
    if (tag == null)
        return;/*from w w w  .  j  a  v a2s.  c  o m*/
    if (tag.getFieldCount() == 0)
        return;
    for (Map.Entry<FieldKey, ParserField> entry : FIELDMAP.entrySet()) {
        final List<TagField> tagFields = tag.getFields(entry.getKey());
        if (tagFields == null)
            continue;
        for (TagField tagField : tagFields) {
            if (!(tagField instanceof TagTextField))
                continue;
            metas.add(entry.getValue(), ((TagTextField) tagField).getContent());
        }
    }
}