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.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetFactory.java

public DatasetFactory(File aCacheRoot) {
    this(aCacheRoot.toPath());
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java

@Override
public Document convert(File tex, String title) {
    logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title);

    CommandLine cmdLine;/*w  w w  .ja v a2  s. c o  m*/
    if (execPath != null) {
        // Run the configured pandoc executable
        logger.info("Pandoc will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Pandoc will be run within the PATH variable.");
        cmdLine = new CommandLine("pandoc");
    }

    cmdLine.addArgument("--from=latex");
    cmdLine.addArgument("--to=html5");
    cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas

    cmdLine.addArgument("${file}");

    HashMap<String, Path> map = new HashMap<String, Path>();
    map.put("file", Paths.get(tex.toURI()));

    cmdLine.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(pandocStreamHandler);

    logger.debug("Launching pandoc:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Pandoc's execution failed, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Pandoc execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();

            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"pandoc\"")) {
                logger.error("Pandoc could not be found! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("pandoc conversion thread got interrupted, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // add html document structure to output
    // pandoc returns no document markup (html, head, body)
    // therefore we have to use a template
    String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" +
    // set title
            "<title>" + title + "</title>\n" +
            // include css
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>";
    try {
        htmlOutput += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading html result from StringBuffer...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // Close tags in template
    htmlOutput += "</body>\n" + "</html>";

    // output loading as JDOM Document
    SAXBuilder sax = new SAXBuilder();
    Document document = null;
    try {
        document = sax.build(new StringReader(htmlOutput));
    } catch (JDOMException e) {
        logger.error("JDOM Parsing error");
        logger.error(e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Error reading from String...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }
    return document;
}

From source file:ru.codemine.ccms.service.SettingsService.java

/**
 *   ? ??   email/* w ww .  j av  a 2  s  .com*/
 * @return
 */
public String getStorageEmailPath() {
    File test = new File(storageEmailPath);
    if (!test.isDirectory()) {
        try {
            Files.createDirectory(test.toPath());
        } catch (IOException ex) {
            log.error(
                    "? ?  ? ? ! : "
                            + storageEmailPath + ",  : " + ex.getMessage());
        }
    }

    return storageEmailPath;
}

From source file:nl.jk_5.nailed.plugin.nmm.NmmMappack.java

@Override
public void prepareWorld(File destination, SettableFuture<Void> future) {
    HttpClient httpClient = HttpClientBuilder.create().build();
    try {/*from   w w w  .j a v  a 2s. c  o  m*/
        String mappack = this.path.split("/", 2)[1];
        HttpGet request = new HttpGet("http://nmm.jk-5.nl/" + this.path + "/versions.json");
        HttpResponse response = httpClient.execute(request);
        MappackInfo list = NmmPlugin.gson.fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"),
                MappackInfo.class);

        HttpGet request2 = new HttpGet(
                "http://nmm.jk-5.nl/" + this.path + "/" + mappack + "-" + list.latest + ".zip");
        HttpEntity response2 = httpClient.execute(request2).getEntity();
        if (response2 != null) {
            File mappackZip = new File(destination, "mappack.zip");
            try (ReadableByteChannel source = Channels.newChannel(response2.getContent());
                    FileChannel out = FileChannel.open(mappackZip.toPath(), StandardOpenOption.CREATE_NEW,
                            StandardOpenOption.WRITE)) {
                out.transferFrom(source, 0, Long.MAX_VALUE);
            }
            ZipUtils.extract(mappackZip, destination);
            mappackZip.delete();
            this.dir = destination;
            File dataDir = new File(destination, ".data");
            dataDir.mkdir();
            File metadataLocation = new File(dataDir, "game.xml");
            new File(destination, "game.xml").renameTo(metadataLocation);
            new File(destination, "scripts").renameTo(new File(dataDir, "scripts"));
            File worldsDir = new File(destination, "worlds");
            for (File f : worldsDir.listFiles()) {
                f.renameTo(new File(destination, f.getName()));
            }
            worldsDir.delete();
            //metadata = XmlMappackMetadata.fromFile(metadataLocation);
            future.set(null);
        } else {
            future.setException(new RuntimeException(
                    "Got an empty response while downloading mappack " + this.path + " from nmm.jk-5.nl"));
        }
    } catch (Exception e) {
        future.setException(
                new RuntimeException("Was not able to download mappack " + this.path + " from nmm.jk-5.nl", e));
    }
}

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

@PreDestroy
/**/*from   w w w  .  j a va 2  s . c  o  m*/
 *  Cleanup by deleting temp directory and uploaded files  
 */
public void cleanupTempDirectory() {
    try {

        if (tempDir != null) {
            for (File f : tempDir.listFiles()) {
                Files.deleteIfExists(f.toPath());
            }
            Files.deleteIfExists(tempDir.toPath());
        }
    } catch (IOException e) {
        throw new RuntimeException("Error deleting temp directory", e); // improve error handling
    }
    uploadedFile = null;
    tempDir = null;
}

From source file:jhi.buntata.server.DatasourceIcon.java

@Put
public void putImage(Representation entity) {
    if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
        try {/*from w  ww .  ja v a2  s.  c  o  m*/
            DiskFileItemFactory factory = new DiskFileItemFactory();
            RestletFileUpload upload = new RestletFileUpload(factory);
            FileItemIterator fileIterator = upload.getItemIterator(entity);

            if (fileIterator.hasNext()) {
                FileItemStream fi = fileIterator.next();

                String name = fi.getName();

                File file = new File(dataDir, name);

                int i = 1;
                while (file.exists())
                    file = new File(dataDir, (i++) + name);

                Files.copy(fi.openStream(), file.toPath());

                BuntataDatasource ds = dao.get(id);
                ds.setIcon(file.getName());
                dao.updateIcon(ds);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
    }
}

From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java

public Future<File> createCodeArchive(File toolkitRoot, JsonObject submission)
        throws IOException, URISyntaxException {

    String tkName = toolkitRoot.getName();

    Path zipOutPath = pack(toolkitRoot.toPath(), graph(submission), tkName);

    if (keepBuildArchive || keepArtifacts(submission)) {
        final JsonObject submissionResult = GsonUtilities.objectCreate(submission,
                RemoteContext.SUBMISSION_RESULTS);
        submissionResult.addProperty(SubmissionResultsKeys.ARCHIVE_PATH, zipOutPath.toString());
    }//from  w  w  w .jav  a2s  .c  om

    JsonObject deployInfo = object(submission, SUBMISSION_DEPLOY);
    deleteToolkit(toolkitRoot, deployInfo);

    return new CompletedFuture<File>(zipOutPath.toFile());
}

From source file:io.werval.gradle.ApplicationPluginIntegTest.java

@Before
public void setupProjectLayout() throws IOException {
    Files.write(new File(tmp.getRoot(), "build.gradle").toPath(), BUILD.getBytes(UTF_8));
    File dev = new File(tmp.getRoot(), "src/dev/resources");
    Files.createDirectories(dev.toPath());
    Files.write(new File(dev, "development.conf").toPath(), CONFIG_DEV.getBytes(UTF_8));
    File custom = new File(tmp.getRoot(), "src/custom/resources");
    Files.createDirectories(custom.toPath());
    Files.write(new File(custom, "application-custom.conf").toPath(), CONFIG.getBytes(UTF_8));
    File resources = new File(tmp.getRoot(), "src/main/resources");
    Files.createDirectories(resources.toPath());
    Files.write(new File(resources, "routes.conf").toPath(), ROUTES.getBytes(UTF_8));
    File controllers = new File(tmp.getRoot(), "src/main/java/controllers");
    Files.createDirectories(controllers.toPath());
    Files.write(new File(controllers, "Application.java").toPath(), CONTROLLER.getBytes(UTF_8));
}

From source file:com.castlemock.web.basis.manager.FileManager.java

public List<File> uploadFiles(final String downloadURL) throws IOException {
    final File fileDirectory = new File(tempFilesFolder);

    if (!fileDirectory.exists()) {
        fileDirectory.mkdirs();/*from w  ww  .  j a v  a  2  s.  c om*/
    }

    final URL url = new URL(downloadURL);
    final String fileName = generateNewFileName();
    final File file = new File(fileDirectory.getAbsolutePath() + File.separator + fileName);

    if (!file.exists()) {
        file.createNewFile();
    }

    final Path targetPath = file.toPath();
    Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
    final List<File> files = new ArrayList<>();
    files.add(file);
    return files;
}