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:org.sakuli.starter.helper.SahiProxy.java

protected void injectCustomJavaScriptFiles() throws IOException {
    File injectFile = props.getSahiJSInjectConfigFile().toFile();
    String injectFileString = FileUtils.readFileToString(injectFile, Charsets.UTF_8);
    if (!injectFileString.contains(SAKULI_INJECT_SCRIPT_TAG)) {
        injectFileString = StringUtils.replace(injectFileString, SAHI_INJECT_END,
                SAKULI_INJECT_SCRIPT_TAG + "\r\n" + SAHI_INJECT_END);
        FileUtils.writeStringToFile(injectFile, injectFileString, Charsets.UTF_8);
        logger.info("added '{}' to Sahi inject config file '{}'", SAKULI_INJECT_SCRIPT_TAG,
                props.getSahiJSInjectConfigFile().toString());
    }//from   w w  w.  j av a2 s. c  o  m

    Path source = props.getSahiJSInjectSourceFile();
    Path target = props.getSahiJSInjectTargetFile();
    if (isNewer(source, target)) {
        FileUtils.copyFile(source.toFile(), target.toFile(), false);
        logger.info("copied file '{}' to target '{}'", source.toString(), target.toString());
    }
}

From source file:com.boundlessgeo.geoserver.bundle.BundleExporterTest.java

@Test
public void testZipBundle() throws Exception {
    new CatalogCreator(cat).workspace("foo");
    exporter = new BundleExporter(cat, new ExportOpts(cat.getWorkspaceByName("foo")).name("blah"));

    exporter.run();//from   ww  w . j  a va 2  s . c o m
    Path zip = exporter.zip();
    ZipInputStream zin = new ZipInputStream(
            new ByteArrayInputStream(FileUtils.readFileToByteArray(zip.toFile())));
    ZipEntry entry = null;

    boolean foundBundle = false;
    boolean foundWorkspace = false;

    while (((entry = zin.getNextEntry()) != null)) {
        if (entry.getName().equals("bundle.json")) {
            foundBundle = true;
        }
        if (entry.getName().endsWith("workspace.xml")) {
            foundWorkspace = true;
        }
    }

    assertTrue(foundBundle);
    assertTrue(foundWorkspace);
}

From source file:com.att.aro.core.settings.impl.JvmSettings.java

@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
@Override//from w  w w . j  ava  2 s .  com
public String setAttribute(String name, String value) {
    if (!StringUtils.equals("Xmx", name)) {
        throw new IllegalArgumentException("Not a valid property:" + name);
    }
    if (!NumberUtils.isNumber(value)) {
        throw new IllegalArgumentException(
                value + " is not a valid value for memory; Please enter an integer value.");
    }
    validateSize(Long.valueOf(value));
    Path path = Paths.get(CONFIG_FILE_PATH);
    List<String> values = Collections.emptyList();
    if (!path.toFile().exists()) {
        createConfig(CONFIG_FILE_PATH, Collections.singletonList("-Xmx" + value + "m"));
        return value;
    } else {
        try (Stream<String> lines = Files.lines(path)) {
            values = lines.filter((line) -> !StringUtils.contains(line, name)).collect(Collectors.toList());
            values.add(0, "-Xmx" + value + "m");
            FileUtils.deleteQuietly(path.toFile());
        } catch (IOException e) {
            String message = "Counldn't read vm options file";
            LOGGER.error(message, e);
            throw new ARORuntimeException(message, e);
        }
        createConfig(CONFIG_FILE_PATH, values);
    }
    return value;
}

From source file:com.tascape.qa.th.AbstractTestRunner.java

protected void generateHtml(Path logFile) {
    Pattern http = Pattern.compile("((http|https)://\\S+)");

    Path html = logFile.getParent().resolve("log.html");
    LOG.trace("creating file {}", html);
    try (PrintWriter pw = new PrintWriter(html.toFile())) {
        pw.println("<html><body><pre>");
        pw.println("<a href='../'>Suite Log Directory</a><br /><a href='./'>Test Log Directory</a>");
        pw.println();/*  w  ww.  j a va2s  . c om*/
        pw.println(logFile);
        pw.println();
        List<String> lines = FileUtils.readLines(logFile.toFile());
        List<File> files = new ArrayList<>(Arrays.asList(logFile.getParent().toFile().listFiles()));

        for (String line : lines) {
            String newline = line.replaceAll(">", "&gt;");
            newline = newline.replaceAll("<", "&lt;");
            if (newline.contains(" WARN  ")) {
                newline = "<b>" + newline + "</b> ";
            } else if (newline.contains(" ERROR ") || newline.contains("Failure in test")
                    || newline.contains("AssertionError")) {
                newline = "<font color='red'><b>" + newline + "</b></font> ";
            } else {
                Matcher m = http.matcher(line);
                if (m.find()) {
                    String url = m.group(1);
                    String a = String.format("<a href='%s'>%s</a>", url, url);
                    newline = newline.replace(url, a);
                }
            }
            pw.println(newline);
            for (File file : files) {
                String path = file.getAbsolutePath();
                String name = file.getName();
                if (newline.contains(path)) {
                    if (name.endsWith(".png")) {
                        pw.printf("<a href=\"%s\" target=\"_blank\"><img src=\"%s\" width=\"360px\"/></a>",
                                name, name);
                    }
                    String a = String.format("<a href=\"%s\" target=\"_blank\">%s</a>", name, name);
                    int len = newline.indexOf("    ");
                    pw.printf((len > 0 ? newline.substring(0, len + 5) : "") + a);
                    pw.println();
                    files.remove(file);
                    break;
                }
            }
        }

        pw.println("</pre></body></html>");
        logFile.toFile().delete();
    } catch (IOException ex) {
        LOG.warn(ex.getMessage());
    }
}

From source file:com.samsung.sjs.ABackendTest.java

public void compilerTest(BiFunction<CompilerOptions, String[], Process> compiler,
        Function<String, Process> evaluator, boolean execute_code, boolean verbose, String... extra) {
    try {//ww  w. j a v a2  s .  co m
        String script = getInputScriptPath();
        System.out.println("Looking for test script: " + script);
        System.err.println("COMPILING: " + script);
        File scriptfile = new File(script);
        Path tmpdir = Files.createTempDirectory("__fawefwea8ew");
        tmpdir.toFile().deleteOnExit();
        String ccode = scriptfile.getName().replaceFirst(".js$", ".c");
        File cfile = File.createTempFile("___", ccode, tmpdir.toFile());
        String exec = ccode.replaceFirst(".c$", "");
        File execfile = File.createTempFile("___", exec, tmpdir.toFile());
        CompilerOptions opts = new CompilerOptions(CompilerOptions.Platform.Native,
                scriptfile.getAbsolutePath(), verbose, // -debugcompiler
                cfile.getAbsolutePath(), true /* use GC */, "clang", "emcc", execfile.getAbsolutePath(),
                baseDirectory(), false /* don't dump C compiler spew into JUnit console */,
                true /* apply field optimizations */, verbose /* emit type inference constraints to console */,
                verbose /* dump constraint solution to console */,
                null /* find runtime src for linking locally (not running from jar) */, shouldEncodeValues(),
                false /* TODO: x86Test passes explicit -m32 flag, rather than setting this */,
                false /* we don't care about error explanations */,
                null /* we don't care about error explanations */, false /* generate efl environment code */,
                3 /* pass C compiler -O3 */);
        if (doInterop()) {
            opts.enableInteropMode();
        }
        if (bootInterop()) {
            opts.startInInteropMode();
        }
        Compiler.compile(opts);
        Process clang = compiler.apply(opts, extra);
        clang.waitFor();
        if (clang.exitValue() != 0) {
            StringWriter w_stdout = new StringWriter(), w_stderr = new StringWriter();
            IOUtils.copy(clang.getInputStream(), w_stdout, Charset.defaultCharset());
            IOUtils.copy(clang.getErrorStream(), w_stderr, Charset.defaultCharset());
            String compstdout = w_stdout.toString();
            String compstderr = w_stderr.toString();
            System.err.println("!!!!!!!!!!!!! Compiler exited with value " + clang.exitValue());
            System.err.println("Compiler stdout: " + compstdout);
            System.err.println("Compiler stderr: " + compstderr);
        }
        assertTrue(clang.exitValue() == 0);
        if (execute_code) {
            File prefixedscript = prefixJS(tmpdir, scriptfile);
            assertSameProcessOutput(runNode(prefixedscript), evaluator.apply(execfile.getAbsolutePath()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        assertTrue(false);
    }
}

From source file:de.learnlib.alex.data.dao.FileDAOImpl.java

private File getUploadDirectory(User user, Long projectId) throws NotFoundException {
    Path uploadedDirectoryLocation = Paths.get(getUploadsDir(user, projectId));
    File uploadDirectory = uploadedDirectoryLocation.toFile();

    if (!uploadDirectory.exists() || !uploadDirectory.isDirectory()) {
        try {//from   w  ww  .  j a v a 2s  .co m
            uploadDirectory.mkdirs();
        } catch (SecurityException e) {
            throw new NotFoundException("Could not find the project directory you are looking for.");
        }
    }

    return uploadDirectory;
}

From source file:io.divolte.server.filesinks.hdfs.FileFlusherLocalHdfsTest.java

private void verifyAvroFile(final List<Record> expected, final Schema schema, final Path avroFile) {
    final List<Record> result = StreamSupport
            .stream(readAvroFile(schema, avroFile.toFile()).spliterator(), false).collect(Collectors.toList());
    assertEquals(expected, result);/*from w  w w  .j  av a 2 s . c  o  m*/
}

From source file:com.bekwam.resignator.commands.UnsignCommand.java

private File verifySource(Path sourceJARFilePath) throws CommandExecutionException {
    File sourceJarFile = sourceJARFilePath.toFile();
    if (!sourceJarFile.exists()) {
        String msg = String.format("source jar file %s does not exist", sourceJARFilePath);
        logger.error(msg);//from  w  w  w  .  j  av a  2  s  . c om
        throw new CommandExecutionException(msg);
    }
    return sourceJarFile;
}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.Plug.java

/**
 * Builds new Plug instance from contents of file at passed
 * {@link java.nio.file.Path Path}./*ww  w.  j  a va  2s.  c om*/
 * 
 * @param pathToFile path to file whose contents are to be used as the string
 * to plug. Must be valid readable text file.
 * @throws Exception if pathToFile does not exists, is not a valid file, is
 * not readable, or an I/O error occurs on reading it.
 */
public Plug(Path pathToFile) throws Exception {
    Utility.isValidPfn("Plug input file", pathToFile, PfnType.FILE, "r");
    File file = pathToFile.toFile();
    this.strng = FileUtils.readFileToString(file, "UTF-8");
}

From source file:controller.GaleriaController.java

@br.com.caelum.vraptor.Path("galeria/zipGaleria/{galeriaId}")
public Download zipGaleria(long galeriaId) {
    validator.ensure(sessao.getIdsPermitidosDeGalerias().contains(galeriaId),
            new SimpleMessage("galeria", "Acesso negado"));
    Galeria galeria = new Galeria();
    galeria.setId(galeriaId);//w w w.  ja  v  a  2  s  .c om
    List<Imagem> imagens = imagemDao.listByGaleria(galeria);

    validator.addIf(imagens == null || imagens.isEmpty(), new SimpleMessage("galeria", "Galeria vazia"));
    validator.onErrorRedirectTo(UsuarioController.class).viewGaleria(galeriaId);

    List<Path> paths = new ArrayList<>();
    for (Imagem imagem : imagens) {
        String realPath = servletContext.getRealPath("/");
        java.nio.file.Path imagemPath = new File(realPath + "/" + UPLOAD_DIR + "/" + imagem.getFileName())
                .toPath();
        paths.add(imagemPath);
    }

    byte buffer[] = new byte[2048];
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos)) {
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(5);
        for (Path path : paths) {

            try (FileInputStream fis = new FileInputStream(path.toFile());
                    BufferedInputStream bis = new BufferedInputStream(fis)) {
                String pathFileName = path.getFileName().toString();
                zos.putNextEntry(new ZipEntry(pathFileName));

                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    zos.write(buffer, 0, bytesRead);
                }

                zos.closeEntry();
                zos.flush();
            } catch (IOException e) {
                result.include("mensagem", "Erro no download do zip");
                result.forwardTo(UsuarioController.class).viewGaleria(galeriaId);
                return null;
            }
        }
        zos.finish();
        byte[] zip = baos.toByteArray();

        Download download = new ByteArrayDownload(zip, "application/zip",
                sessao.getUsuario().getNome() + ".zip");
        return download;

        //zipDownload = new ZipDownload(sessao.getUsuario().getNome() + ".zip", paths);
        //return zipDownloadBuilder.build();
    } catch (IOException e) {
        result.include("mensagem", "Erro no download do zip");
        result.forwardTo(UsuarioController.class).viewGaleria(galeriaId);
        return null;
    }
}