Example usage for java.nio.file Path getFileName

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

Introduction

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

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by this path as a Path object.

Usage

From source file:io.undertow.server.handlers.file.FileHandlerTestCase.java

@Test
public void testFileTransferLargeFile() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path tmp = Paths.get(System.getProperty("java.io.tmpdir"));
    StringBuilder message = new StringBuilder();
    for (int i = 0; i < 100000; ++i) {
        message.append("Hello World");
    }//  w  w w  .ja  va 2s  .c  o  m
    Path large = Files.createTempFile(null, ".txt");
    try {
        Files.copy(new ByteArrayInputStream(message.toString().getBytes(StandardCharsets.UTF_8)), large,
                StandardCopyOption.REPLACE_EXISTING);
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(tmp, 1))
                        // 1 byte = force transfer
                        .setDirectoryListingEnabled(true))));

        HttpGet get = new HttpGet(
                DefaultServer.getDefaultServerURL() + "/path/" + large.getFileName().toString());
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/plain", headers[0].getValue());
        Assert.assertTrue(response, response.equals(message.toString()));

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:illarion.compile.Compiler.java

private static void processPath(@Nonnull final Path path) throws IOException {
    if (Files.isDirectory(path)) {
        return;//from   w  w  w  . j  a  v  a 2s.c  o  m
    }

    int compileResult = 1;
    for (CompilerType type : CompilerType.values()) {
        if (type.isValidFile(path)) {
            Compile compile = type.getImplementation();
            if (path.isAbsolute()) {
                if (storagePaths.containsKey(type)) {
                    compile.setTargetDir(storagePaths.get(type));
                } else {
                    compile.setTargetDir(path.getParent());
                }
            } else {
                if (storagePaths.containsKey(type)) {
                    Path parent = path.getParent();
                    if (parent == null) {
                        compile.setTargetDir(storagePaths.get(type));
                    } else {
                        compile.setTargetDir(storagePaths.get(type).resolve(parent));
                    }
                } else {
                    Path parent = path.getParent();
                    if (parent == null) {
                        compile.setTargetDir(path.toAbsolutePath().getParent());
                    } else {
                        compile.setTargetDir(parent);
                    }
                }
            }
            compileResult = compile.compileFile(path.toAbsolutePath());
            if (compileResult == 0) {
                break;
            }
        }
    }

    switch (compileResult) {
    case 1:
        LOGGER.info("Skipped file: {}", path.getFileName());
        break;
    case 0:
        return;
    default:
        System.exit(compileResult);
    }
}

From source file:edu.usc.goffish.gofs.util.partitioning.metis.MetisPartitioner.java

private Path partition(Path workingDir, Path metisInputPath, int numPartitions) throws IOException {

    // prepare metis command
    ProcessHelper.CommandBuilder command = new ProcessHelper.CommandBuilder(_metisBinaryPath.toString());
    if (_extraMetisOptions != null) {
        command.append(_extraMetisOptions);
    }/*from  w w w.j  a v a2s .c  om*/
    command.append(metisInputPath).append(Integer.toString(numPartitions));

    // run metis
    try {
        System.out.println("executing: \"" + command + "\"");
        ProcessHelper.runProcess(workingDir.toFile(), true, command.toArray());
    } catch (InterruptedException e) {
        throw new IOException(e);
    }

    return workingDir.resolve(metisInputPath.getFileName() + ".part." + numPartitions);
}

From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java

@Test
public void testNextTimeout() throws Exception {
    Path file = createFile(Arrays.asList("Hello1"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 0, 10);

    Assert.assertTrue(lfr.hasNext());/* ww  w.j  a v  a  2 s.  c om*/
    long start = System.currentTimeMillis();
    LiveFileChunk chunk = lfr.next(10);
    Assert.assertNull(chunk);
    Assert.assertTrue(System.currentTimeMillis() - start >= 10);
    lfr.close();
}

From source file:com.nwn.NwnUpdater.java

/**
 * Reads through every file in directory and determines correct action for each file based off the file extension
 * Files will either be moved to the correct directory or extracted and processed.
 * @param uncompressedFolder Path of directory to process
 *///  ww w  .  java  2  s  .  co m
private void processFilesInDirectory(Path uncompressedFolder) {
    ArrayList<String> fileNames;
    try {
        fileNames = NwnFileHandler.getFileNamesInDirectory(uncompressedFolder);
    } catch (NoSuchFileException nsfe) {
        currentGui.appendOutputText(
                "\nERROR: Folder " + uncompressedFolder.getFileName().toString() + " does not exist!");
        error[0] = true;
        return;
    } catch (IOException ex) {
        currentGui.appendOutputText("\nERROR: Cannot parse local directory!");
        error[0] = true;
        return;
    }
    for (String fileName : fileNames) {
        Path srcFile = Paths.get(uncompressedFolder.toString() + File.separator + fileName);
        if (srcFile.toFile().isDirectory()) {
            processFilesInDirectory(srcFile);
        } else {
            String folderName = ServerFile.getFolderByExtension(fileName);
            Path desiredFolder = Paths.get(nwnRootPath.toString() + File.separator + folderName);
            Path desiredPath = Paths
                    .get(nwnRootPath.toString() + File.separator + folderName + File.separator + fileName);

            //make sure no file with the same name exists before we move it there
            if (!desiredPath.toFile().exists() && desiredFolder.toFile().exists()) {
                NwnFileHandler.moveFile(srcFile, desiredPath);
                currentGui.appendOutputText(
                        "\nMoving " + srcFile.getFileName().toString() + " to " + desiredFolder.toString());
                if (folderName.equals(FolderByExt.COMPRESSED.toString())) {
                    uncompressFile(fileName, folderName);
                }

                //we don't want to create folders for the user, so just alert them and move on
            } else if (!desiredFolder.toFile().exists()) {
                currentGui.appendOutputText("\nERROR: Folder " + folderName + " does not exist!");
                error[0] = true;
            }
        }
    }
}

From source file:dotaSoundEditor.Controls.EditorPanel.java

protected File promptUserForNewFile(String wavePath) {
    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3s and WAVs", "mp3", "wav");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);/*from w w w .ja  v  a 2 s  .c o  m*/
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        DefaultMutableTreeNode selectedFile = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());
        //Strip caps and spaces out of filenames. The item sound parser seems to have trouble with them.
        String destFileName = chosenFile.getFileName().toString().toLowerCase().replace(" ", "_");
        Path destPath = Paths.get(installDir, "/dota/sound/" + getCustomSoundPathString() + destFileName);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            String waveString = selectedFile.getUserObject().toString();
            int startIndex = -1;
            int endIndex = -1;
            if (waveString.contains("\"wave\"")) {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 2);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 3);
            } else //Some wavestrings don't have the "wave" at the beginning for some reason
            {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 0);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 1);
            }

            String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
            waveString = waveString.replace(waveStringFilePath,
                    "\"" + getCustomSoundPathString() + destFileName + "\"");
            selectedFile.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:com.streamsets.pipeline.lib.io.TestSingleLineLiveFileReader.java

@Test
public void testReadWithinTimeout() throws Exception {
    Path file = createFile(Arrays.asList("Hello1\n"));
    LiveFile lf = new LiveFile(file);
    LiveFileReader lfr = new SingleLineLiveFileReader(
            LogRollModeFactory.REVERSE_COUNTER.get(file.getFileName().toString(), ""), null, lf,
            Charset.defaultCharset(), 0, 10);

    Assert.assertTrue(lfr.hasNext());//  w  w w. j a  v  a2 s .c om
    long start = System.currentTimeMillis();
    LiveFileChunk chunk = lfr.next(1000);
    Assert.assertNotNull(chunk);
    Assert.assertEquals("Hello1\n", readChunk(chunk));
    Assert.assertTrue(System.currentTimeMillis() - start < 1000);
    lfr.close();
}

From source file:licorice.gui.MainPanel.java

private void processBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processBtnActionPerformed
    SwingUtilities.invokeLater(() -> {
        try {//ww w . j a v  a2  s  . c om
            minQual = Integer.parseInt(minQualField.getText());

            processBtn.setEnabled(false);
            //progressBar = new JProgressBar();
            progressBar.setMinimum(0);
            progressBar.setMaximum(100);

            Path genomePath = Paths.get(prop.getProperty("genome.path"));
            prop.setProperty("input.default_dir", fc.getCurrentDirectory().getAbsolutePath());
            prop.setProperty("minimum.quality", minQual.toString());
            prop.setProperty("maximum.nocall.rate", maxNC.toString());
            prop.store(new FileOutputStream("licorice.properties"), null);

            Path inputPath = Paths.get(fileNameField.getText());

            if (!inputPath.toFile().exists()) {
                JOptionPane.showMessageDialog(null, "Input file does not exist");
                appendLog("Input file '" + inputPath + "' does not exist");
                return;
            }

            Path outputPath = inputPath
                    .resolveSibling(FilenameUtils.getBaseName(inputPath.getFileName().toString()) + ".txt");
            appendLog("Output in: '" + outputPath.getParent() + "'\n");

            appendLog("Analysis Started...\n");
            processBtn.setText("Processing...");
            SimpleGenomeRef genome = new SimpleGenomeRef(genomePath);

            GenomeRef.ValidationResult validation = genome.validate();

            if (!validation.isValid()) {
                appendLog("Reference Error: '" + validation.getErrors() + "'\n");
                return;
            }

            Path effectivePath = ZipUtil.directoryfy(inputPath);

            Map<String, String> samples = VCFUtils.makeSamplesDictionary(VCFUtils.listVCFFiles(effectivePath));

            appendLog("==================================\n");
            appendLog("Samples List\n");
            appendLog("==================================\n");
            appendLog("Sample\tFile");

            samples.forEach((k, v) -> appendLog(String.format("%s\t%s\n", k, v)));

            appendLog("==================================\n");

            Path samplesPath = inputPath.resolveSibling(
                    FilenameUtils.getBaseName(inputPath.getFileName().toString()) + ".samples.txt");
            appendLog("Samples List in: '" + samplesPath.getParent() + "'\n");

            try (PrintStream out = new PrintStream(new FileOutputStream(samplesPath.toFile()))) {
                out.println("Sample\tFile");
                samples.forEach((k, v) -> out.println(String.format("%s\t%s", k, v)));
            }

            analysis = new Analysis(genome, minQual, maxNC, false, outputPath,
                    VCFUtils.listVCFFiles(effectivePath));

            analysis.progressListener(progress -> progressBar.setValue(progress));

            analysis.onFinish(() -> {
                log.info("Callback called");
                appendLog("Analysis Finished.\n");
                fileNameField.setText("");
                processBtn.setText("Process");
                processBtn.setEnabled(true);
                processBtn.repaint();
                this.repaint();
                return null;
            });
            analysis.onException((Thread t, Throwable ex) -> {
                appendLog(ex.getMessage());
                appendLog("Analysis Failed!!!");
                JOptionPane.showMessageDialog(null, "Analysis Failed!!!");
                processBtn.setText("Process");
                processBtn.setEnabled(true);
                processBtn.repaint();
            });
        } catch (IOException ex) {
            appendLog(ex.getMessage() + "\n");
            log.error(ex.getMessage());
            JOptionPane.showMessageDialog(null, "Analysis Failed!!!");
            ex.printStackTrace();
        }
        analysis.start();
        //progressBar.

    });
}

From source file:it.polimi.modaclouds.qos.linebenchmark.solver.LineConnectionHandler.java

private synchronized void updateModelEvaluation(String message) {
    message = message.trim().replaceAll(" +", " ");
    String[] tokens = message.split(" ");
    String modelName = tokens[1];
    modelName = modelName.replace("_res.xml", ".xml");
    modelName = Paths.get(modelName).toString();
    String status = null;//from   w w  w .  j  av a 2s .  c o  m
    if (tokens.length == 4)
        status = tokens[3];
    else
        status = tokens[2];
    Path modelPath = Paths.get(modelName);
    evaluations.put(modelPath, status);

    StopWatch timer;
    if (status.equals("SUBMITTED")) {
        timer = new StopWatch();
        timers.put(modelPath, timer);
        timer.start();
        logger.debug("Model: " + modelName + " SUBMITTED");
    } else {
        timer = timers.get(modelPath);
        timer.stop();

        EvaluationCompletedEvent evaluationCompleted = new EvaluationCompletedEvent(this, 0, null);
        evaluationCompleted.setEvaluationTime(timer.getTime());
        evaluationCompleted.setSolverName(Main.LINE_SOLVER);
        evaluationCompleted.setModelPath(modelPath.getFileName());
        logger.debug("Model: " + modelName + " " + status);
        for (ActionListener l : listeners)
            l.actionPerformed(evaluationCompleted);
    }
}

From source file:at.tfr.securefs.client.SecurefsFileServiceClient.java

public void run() {
    DateTime start = new DateTime();
    try {//from w w w.  j a va  2s  .  c o m
        FileService svc = new FileService(new URL(fileServiceUrl));
        BindingProvider binding = (BindingProvider) svc.getFileServicePort();
        binding.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
        binding.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);

        for (Path path : files) {

            if (write) {
                if (!path.toFile().exists()) {
                    System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir="
                            + Paths.get("./").toAbsolutePath());
                    continue;
                }

                System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + path);
                svc.getFileServicePort().write(path.toString(),
                        IOUtils.toByteArray(Files.newInputStream(path)));
            }

            Path out = path.resolveSibling(
                    path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out");

            if (read) {
                System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out);
                if (out.getParent() != null) {
                    Files.createDirectories(out.getParent());
                }

                byte[] arr = svc.getFileServicePort().read(path.toString());
                IOUtils.write(arr, Files.newOutputStream(out));
            }

            if (write && read) {
                long inputChk = FileUtils.checksumCRC32(path.toFile());
                long outputChk = FileUtils.checksumCRC32(out.toFile());
                if (inputChk != outputChk) {
                    throw new IOException(Thread.currentThread()
                            + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out);
                }
                System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : "
                        + inputChk + " / " + outputChk);
            }

            if (delete) {
                boolean deleted = svc.getFileServicePort().delete(path.toString());
                if (!deleted) {
                    throw new IOException(
                            Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path);
                } else {
                    System.out.println(Thread.currentThread() + ": Deleted File: in=" + path);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}