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:com.reactive.hzdfs.dll.JarModuleLoader.java

private Set<File> walkDirectory(Path directory) {
    final Set<File> walkedFiles = new LinkedHashSet<File>();
    try {/*from  www  .ja  v a 2 s  .  co  m*/
        registerWatch(directory);
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.preVisitDirectory(dir, attrs);
                registerWatch(dir);
                return fileVisitResult;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.visitFile(file, attrs);
                if (isJarFile(file.toFile()))
                    walkedFiles.add(file.toFile());

                return fileVisitResult;
            }

        });
    } catch (IOException e) {
        log.error("Failed to walk directory: " + directory.toString(), e);
    }
    return walkedFiles;
}

From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java

/**
 * Creates the qualified name form a source file.
 *
 * @param path/*from  w ww.  j  av  a 2s.  c  o m*/
 *            the path to the sourcefile
 * @return the qualified name
 * @throws IOException
 *             in case of io errors
 */
private String getQuallifiedNameFromSource(Path path) throws IOException {

    final String packageRegex = "package\\s[^,;]+;";
    LineIterator it;
    String result = "";
    it = FileUtils.lineIterator(path.toFile(), "UTF-8");

    while (it.hasNext()) {
        String line = it.nextLine();
        if (line.matches(packageRegex)) {
            result = line;
            // strip not needed elements
            result = result.substring(8, result.length() - 1);
            // append classname
            return result + "." + FilenameUtils.getBaseName(path.toString());
        }
    }
    return FilenameUtils.getBaseName(path.toString());
}

From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java

/**
 * Creates a thumbnail for the image file using plain old java
 * @param file the image file//  w w  w.j ava  2  s .c o m
 * @param thumbFile the resulting thumbnail file
 * @param size the size of the thumbnail
 */
private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException {

    try {
        BufferedImage image = ImageIO.read(file.toFile());

        int w = image.getWidth();
        int h = image.getHeight();

        // Never scale up
        if (w <= size.getSize() && h <= size.getSize()) {
            FileUtils.copyFile(file.toFile(), thumbFile.toFile());

        } else {
            // Compute the scale factor
            double dx = (double) size.getSize() / (double) w;
            double dy = (double) size.getSize() / (double) h;
            double d = Math.min(dx, dy);

            // Create the thumbnail
            BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbImage.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(d, d);
            g2d.drawRenderedImage(image, at);
            g2d.dispose();

            // Save the thumbnail
            String fileName = thumbFile.getFileName().toString();
            ImageIO.write(thumbImage, FilenameUtils.getExtension(fileName), thumbFile.toFile());

            // Releas resources
            image.flush();
            thumbImage.flush();
        }

        // Update the timestamp of the thumbnail file to match the change date of the image file
        Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file));

    } catch (Exception e) {
        log.error("Error creating thumbnail for image " + file, e);
        throw new IOException(e);
    }
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.configurationextractor.LocalCopyConfigurationsExtractor.java

/**
 * This method performs the extraction. 
 * The context must contain: /*from w w w  .  ja  v  a2  s  .co m*/
 * <ul>
 * <li>One or more {@link ConfigureAppsTarget} returned by {@link ConfigurationAnalysisContext#getInputTargets()}. 
 * All the referenced {@link Application} must return "file://" URIs at {@link Application#getConfigurationURIs()}.</li>
 * <li>An {@link Environment} object returned by {@link ConfigurationAnalysisContext#getInputEnvironment()}, from which 
 * the configuration of the runtime where all the referenced applications are run.</li>
 * </ul>
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.configurationextractor.ConfigurationsExtractor#extractConfigurations(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext)
 */
@Override
public void extractConfigurations(ConfigurationAnalysisContext context)
        throws ConfigurationExtractionException {
    try {
        Path tempFolderPath = Files.createTempDirectory("ConfigurationAnalyzer");
        for (Target currentTarget : context.getInputTargets().values()) {
            if (!(currentTarget instanceof ConfigureAppsTarget)) {
                continue;
            }
            Properties configurationAnalyzerSettings = context.getConfigurationAnalyzerSettings();
            String runtimeConfigurationDirName = configurationAnalyzerSettings
                    .getProperty(PROPERTY_KEY_RUNTIME_CONFIGURATION_FILENAME);
            if (runtimeConfigurationDirName == null) {
                throw new ConfigurationExtractionException(
                        "Property '" + PROPERTY_KEY_RUNTIME_CONFIGURATION_FILENAME + "' not found");
            }
            ConfigureAppsTarget currentConfigureAppsTarget = (ConfigureAppsTarget) currentTarget;
            for (String appId : currentConfigureAppsTarget.getParameters().keySet()) {
                Path subfolderForApp = tempFolderPath.resolve(Paths.get(appId));
                List<File> copiedFiles = new ArrayList<>();
                Files.createDirectory(subfolderForApp);
                //We copy the application configuration files to the root of the directory.
                //We also copy the runtime configuration.
                Application currentApplication = (Application) currentConfigureAppsTarget.getParameters()
                        .get(appId);
                for (URI configurationURI : currentApplication.getConfigurationURIs()) {
                    //TODO: Let other configuration URIs live, specially, SVN-based ones, which should be extracted by other extractors. This would require some refactoring. 
                    if (!configurationURI.getScheme().equalsIgnoreCase("file")) {
                        throw new ConfigurationExtractionException(
                                "URI '" + configurationURI.toString() + "' does not have a 'file' scheme");
                    }
                    Path configurationPath = Paths.get(configurationURI);
                    Path configurationPathName = configurationPath.getFileName();
                    if (configurationPathName.toString().equals(runtimeConfigurationDirName)) {
                        throw new ConfigurationExtractionException(
                                "One of the application configuration files has the same name than the runtime configuration folder ('"
                                        + runtimeConfigurationDirName + "')");
                    }

                    Path destinationConfigurationPath = Files.copy(configurationPath,
                            subfolderForApp.resolve(configurationPathName), REPLACE_EXISTING);
                    File destinationConfigurationFile = destinationConfigurationPath.toFile();
                    copiedFiles.add(destinationConfigurationFile);

                }

                File runtimeConfigurationDirectory = new File(
                        context.getInputEnvironment().getApplicationConfigurations().get(appId));
                File destinationRuntimeConfigurationDirectory = subfolderForApp
                        .resolve(runtimeConfigurationDirName).toFile();
                FileUtils.copyDirectory(runtimeConfigurationDirectory,
                        destinationRuntimeConfigurationDirectory);
                copiedFiles.add(destinationRuntimeConfigurationDirectory);

                ExtractedConfiguration<File> extractedConfiguration = new FileExtractedConfiguration(appId,
                        currentTarget, copiedFiles);
                context.getExtractedConfigurations().add(extractedConfiguration);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationExtractionException(e);
    }

}

From source file:dk.dma.msiproxy.common.repo.FileTypes.java

/**
 * Returns the content type of the file, or null if unknown
 * @param path the file to check//from  www . j a v  a  2 s  . co m
 * @return the content type of the file, or null if unknown
 */
public String getContentType(Path path) {
    try {
        // For some reason unknown, this does not work
        // String type = Files.probeContentType(path);
        return new MimetypesFileTypeMap().getContentType(path.toFile());
    } catch (Exception e) {
        // Unknown type
        return null;
    }
}

From source file:io.cloudslang.content.vmware.services.DeployOvfTemplateService.java

private ITransferVmdkFrom getTransferVmdK(final String templateFilePathStr, final String vmdkName)
        throws IOException {
    final Path templateFilePath = Paths.get(templateFilePathStr);
    if (isOva(templateFilePath)) {
        final TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(templateFilePathStr));
        TarArchiveEntry entry;//w w w . j av a  2  s.  c  om
        while ((entry = tar.getNextTarEntry()) != null) {
            if (new File(entry.getName()).getName().startsWith(vmdkName)) {
                return new TransferVmdkFromInputStream(tar, entry.getSize());
            }
        }
    } else if (isOvf(templateFilePath)) {
        final Path vmdkPath = templateFilePath.getParent().resolve(vmdkName);
        return new TransferVmdkFromFile(vmdkPath.toFile());
    }
    throw new RuntimeException(NOT_OVA_OR_OVF);
}

From source file:io.cloudslang.lang.tools.build.tester.parallel.report.SlangTestCaseRunReportGeneratorService.java

public void generateReport(IRunTestResults iRunTestResults, String reportDirectory) throws IOException {
    String reportFileName = String.format(TEST_CASE_REPORT_NAME + FORMATTER_STRING + REPORT_EXTENSION,
            valueOf(currentTimeMillis()));
    Path path = Paths.get(reportDirectory, reportFileName);

    try (Writer writer = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path.toFile(), false), UTF_8)))) {
        HtmlCanvas reportPage = new HtmlCanvas(writer);

        HtmlCanvas reportPageHtml = reportPage.html();
        appendReportPageHead(reportPageHtml);

        HtmlCanvas reportPageBody = reportPageHtml.body();
        createResourcesFolder(reportDirectory);
        copyResources(reportDirectory);/*from  ww  w. j a v  a 2 s  .  c  o  m*/

        generateHeader(reportPageBody, CURRENT_DIRECTORY + RES + SLASH + CLOUD_SLANG_LOGO_PNG);
        generatePiechart(reportPageBody, iRunTestResults);
        generateTestCaseReportTable(reportPageBody, iRunTestResults);
    }
}

From source file:com.ibm.vicos.client.ClientCommand.java

@CliCommand(value = "getblob", help = "Downloads a blob to destination path")
public String getBlob(
        @CliOption(key = { "container" }, mandatory = true, help = "container name") final String container,
        @CliOption(key = { "blob" }, mandatory = true, help = "blob name") final String blob,
        @CliOption(key = { "dest_path" }, mandatory = true, help = "destination path") final String path) {
    Path fullPath = FileSystems.getDefault().getPath(path, blob);
    fullPath.getParent().toFile().mkdirs();

    try {/*from  ww  w . j a  v a 2  s.  com*/
        InputStream inputStream = storage.getObject(container, blob);
        OutputStream outputStream = new FileOutputStream(fullPath.toFile());

        long total = ByteStreams.copy(inputStream, outputStream);

        checkState(fullPath.toFile().exists(), "Could not create file");
        return "Successfully downloaded " + fullPath.toString() + " [" + total + " bytes]";
    } catch (Exception e) {
        e.printStackTrace();
        return "Error while getting the " + container + "/" + blob;
    }
}

From source file:eu.peppol.document.PayloadParserTest.java

/**
 * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while
 * calculating the message digest./*  w  w  w  .ja v  a 2s. c  o m*/
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {

    InputStream resourceAsStream = PayloadParserTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");
    assertNotNull(resourceAsStream);

    Path xmlFile = Files.createTempFile("unit-test", ".xml");

    XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(resourceAsStream,
            "UTF-8");
    FileOutputStream outputStream = new FileOutputStream(xmlFile.toFile());
    XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(outputStream, "UTF-8");

    Path asicFile = Files.createTempFile("unit-test", ".asice");
    OutputStream asicOutputStream = Files.newOutputStream(asicFile);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

    DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest);
    Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false);

    boolean insideAsicElement = false;

    while (xmlEventReader.hasNext()) {
        XMLEvent xmlEvent = xmlEventReader.nextEvent();

        switch (xmlEvent.getEventType()) {
        case XMLEvent.START_ELEMENT:
            String localPart = xmlEvent.asStartElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = true;
            }
            break;
        case XMLEvent.END_ELEMENT:
            localPart = xmlEvent.asEndElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = false;
            }
            break;

        case XMLEvent.CHARACTERS:
            // Whenever we are inside the ASiC XML element, spit
            // out the base64 encoded data into the base64 decoding output stream.
            if (insideAsicElement) {
                Characters characters = xmlEvent.asCharacters();
                base64OutputStream.write(characters.getData().getBytes("UTF-8"));
            }
            break;
        }
        xmlEventWriter.add(xmlEvent);
    }

    asicOutputStream.close();
    outputStream.close();
    log.debug("Wrote xml output to: " + xmlFile);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));
}