Example usage for java.io File toPath

List of usage examples for java.io File toPath

Introduction

In this page you can find the example usage for java.io File toPath.

Prototype

public Path toPath() 

Source Link

Document

Returns a Path java.nio.file.Path object constructed from this abstract path.

Usage

From source file:de.alexkamp.sandbox.model.SandboxData.java

public SandboxData copyTo(File source, String target) throws IOException {
    File targetFile = new File(basePath, target);
    if (source.isDirectory()) {
        SandboxUtils.copyDirectory(source, targetFile);
    } else {/*from  w w w.  j a  va 2  s  .c  o m*/
        ensureExistance(targetFile);
        Files.copy(source.toPath(), targetFile.toPath());
    }
    return this;
}

From source file:ws.doerr.cssinliner.server.InlinerApp.java

private InlinerApp(Path sourceFolder, Path dataFolder) throws Exception {
    TempFolder workingFolder = new TempFolder("cssinline");

    // Start the Http Server
    Server.start(getClass().getPackage().getName());
    Server.registerWebsocket("/connect");

    // Setup Handlebars
    FileTemplateLoader loader = new FileTemplateLoader(workingFolder.getFile());
    loader.setSuffix("");
    handlebars = new Handlebars(loader);

    EmailService.get().getHelpers().forEach((tag, helper) -> {
        handlebars.registerHelper(tag, helper);
    });//w ww  . j  a va 2 s . c o  m

    // List all the source files from the folder
    File[] files = sourceFolder.toFile().listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".html");
        }
    });

    for (File file : files) {
        try {
            SourceInstance instance = new SourceInstance(file.toPath(), dataFolder, workingFolder.getPath());
            InlinerContext context = inliner.process(instance.getSource(), instance.getInlined());
            instance.update(context);

            processHandlebars(instance);

            getDocumentTitle(instance);

            sources.put(instance.getId(), instance);

            pathToInstance.put(file.toPath().normalize().toString(), instance.getId());

            instance.getDependencies().forEach((dependency) -> {
                pathToInstance.put(dependency.getPath().normalize().toString(), instance.getId());
                folders.add(dependency.getPath().normalize().getParent().toString());
            });

            pathToInstance.put(instance.getData().toString(), instance.getId());
        } catch (Exception ex) {

        }
    }

    // Register the folder for change events
    Monitor.getInstance().register(sourceHandler, sourceFolder);
    Monitor.getInstance().register(dataHandler, dataFolder);

    folders.forEach(folder -> {
        Path f = Paths.get(folder);
        Monitor.getInstance().register(dependencyHandler, f);
    });
}

From source file:backtype.storm.localizer.LocalizedResourceRetentionSet.java

protected boolean deleteResource(LocalizedResource resource) {
    try {//  ww  w.ja  v  a2 s.com
        String fileWithVersion = resource.getFilePathWithVersion();
        String currentSymlinkName = resource.getCurrentSymlinkPath();
        String versionFile = resource.getVersionFilePath();
        File deletePath = new File(fileWithVersion);
        if (resource.isUncompressed()) {
            // this doesn't follow symlinks, which is what we want
            FileUtils.deleteDirectory(deletePath);
        } else {
            Files.delete(deletePath.toPath());
        }
        Files.delete(new File(currentSymlinkName).toPath());
        Files.delete(new File(versionFile).toPath());
        return true;
    } catch (IOException e) {
        LOG.warn("Could not delete: {}", resource.getFilePath());
    }
    return false;
}

From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testClassifyFileContentsDescClient() throws Exception {
    ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier");
    S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass);

    File f = new File("test-file");
    try {/*from w ww .  j av  a  2 s  .  c om*/
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);
        ClassifiedDocument result = client.classifyFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertNotNull(result.getCategory());
        assertEquals(3, result.getAllScores().size());
    } finally {
        f.delete();
    }
}

From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testClassifyFileContentsUrlClient() throws Exception {
    ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier");
    S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass);

    File f = new File("test-file");
    try {// w ww  . ja  v  a2s  . c om
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);
        ClassifiedDocument result = client.classifyFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertNotNull(result.getCategory());
        assertEquals(3, result.getAllScores().size());
    } finally {
        f.delete();
    }
}

From source file:it.unisannio.srss.dame.Dame.java

public void inject(List<Payload> payloads) throws IOException {
    FileUtils.checkDir(COMMON_SMALI_PATH);

    FTPServerConfig ftpServerConfig;/*from   w  w  w  .j  a v  a 2s  . c  om*/
    log.info("Loading FTP server configuration.");
    try {
        ftpServerConfig = getServerConfig();
    } catch (IOException e) {
        log.error("Unable to locate the FTP server configuration.", e);
        throw e;
    }
    log.info("FTP server configuration sucessfully loaded");
    log.debug(ftpServerConfig.toString());

    File decompiledDir = ApkUtils.decompile(apkIn, apktoolPath);

    CommonInjector.injectSmali(new File(COMMON_SMALI_PATH).toPath(), decompiledDir.toPath());
    CommonInjector.injectServices(decompiledDir.toPath());
    CommonInjector.injectFtpConfig(decompiledDir.toPath(), ftpServerConfig);

    Map<String, Set<String>> payloadsMap = new HashMap<String, Set<String>>();
    for (Payload payload : payloads) {
        for (String permission : payload.getConfig().getPermissions()) {
            Set<String> set = payloadsMap.get(permission);
            if (set == null)
                set = new HashSet<String>();
            set.add(payload.getClass().getCanonicalName());
            payloadsMap.put(permission, set);
        }
    }
    CallInjector injector = new CallInjector(getAPKPermissions(), payloadsMap, decompiledDir.getAbsolutePath());
    injector.inject();

    ApkUtils.compile(decompiledDir.getAbsolutePath(), androidBuildToolsPath, apktoolPath, getApkOutPath());
}

From source file:edu.harvard.iq.dataverse.ThemeWidgetFragment.java

private void createTempDir() {
    try {/*from   w ww .  j a  va 2s . co m*/
        File tempRoot = Files.createDirectories(Paths.get("../docroot/logos/temp")).toFile();
        tempDir = Files.createTempDirectory(tempRoot.toPath(), editDv.getId().toString()).toFile();
    } catch (IOException e) {
        throw new RuntimeException("Error creating temp directory", e); // improve error handling
    }
}

From source file:it.polimi.diceH2020.launcher.controller.FilesController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String multipleSave(@RequestParam("file[]") MultipartFile[] files,
        @RequestParam("scenario") String useCase, Model model, RedirectAttributes redirectAttrs) {
    boolean singleInputData = false;
    Scenarios scenario = Scenarios.valueOf(useCase);
    ArrayList<String> tmpValues = new ArrayList<>();

    redirectAttrs.addAttribute("scenario", scenario);
    model.addAttribute("scenario", scenario);

    if (files == null || files.length == 0) {
        model.addAttribute("message", "Wrong files!");
        return "launchSimulation_FileUpload";
    }//from ww  w. j  a  va 2s  . c  o  m

    if (hasDuplicate(
            Arrays.stream(files).map(MultipartFile::getOriginalFilename).collect(Collectors.toList()))) {
        model.addAttribute("message", "Duplicated files!");
        return "launchSimulation_FileUpload";
    }

    for (int i = 0; i < files.length; i++) {
        String fileName = files[i].getOriginalFilename()
                .substring(files[i].getOriginalFilename().lastIndexOf("/") + 1);
        File f = saveFile(files[i], fileName);
        if (f == null)
            return "error";
        if (fileName.contains(".json")) {
            Optional<InstanceDataMultiProvider> idmp = validator.readInstanceDataMultiProvider(f.toPath());
            if (idmp.isPresent()) {
                if (idmp.get().validate()) {
                    redirectAttrs.addAttribute("instanceDataMultiProvider", f.toPath().toString());
                    continue;
                } else {
                    model.addAttribute("message", idmp.get().getValidationError());
                    return "launchSimulation_FileUpload";
                }
            }
            model.addAttribute("message", "You have submitted an invalid json!");
            return "launchSimulation_FileUpload";
        } else {
            if (fileName.contains(".txt")) {
                tmpValues.add(f.toPath().toString());
            }
        }
    }

    redirectAttrs.addAttribute("pathList", tmpValues);
    if (singleInputData)
        return "redirect:/launch/simulationSetupSingleInputData";
    return "redirect:/launch/simulationSetup";
}

From source file:de.ks.file.FileViewController.java

protected void addPossibleImage(File file) {
    if (file == null) {
        return;/*from  ww w. j a  v  a2 s . c  o  m*/
    }
    try {
        String contentType = Files.probeContentType(file.toPath());
        if (contentType != null && contentType.contains("image")) {
            imageProvider.addImage(new ImageData(file.getName(), file.getPath()));
        }
    } catch (IOException e) {
        //
    }
}

From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testClassifyFileContentsAsStreamDescClient() throws Exception {
    ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier");
    S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass);
    serializationFormat = ResponseFormat.JSON;
    File f = new File("test-file");
    try {//from  w w  w.jav a2  s. co m
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);

        InputStream result = client.annotateFileContentsAsStream(f, Charset.forName("UTF-8"),
                SupportedMimeType.PLAINTEXT, serializationFormat);
        StringWriter writer = new StringWriter();
        IOUtils.copy(result, writer, Charset.forName("UTF-8"));

        assertTrue(writer.toString().contains("category"));
        assertTrue(writer.toString().contains("allScores"));
    } finally {
        f.delete();
    }
}