Example usage for java.nio.file FileSystems getDefault

List of usage examples for java.nio.file FileSystems getDefault

Introduction

In this page you can find the example usage for java.nio.file FileSystems getDefault.

Prototype

public static FileSystem getDefault() 

Source Link

Document

Returns the default FileSystem .

Usage

From source file:com.team3637.service.MatchServiceMySQLImpl.java

@Override
public void importCSV(String inputFile) {
    try {/*from w  w w .ja va2s.c  om*/
        String csvData = new String(Files.readAllBytes(FileSystems.getDefault().getPath(inputFile)));
        csvData = csvData.replaceAll("\\r", "");
        CSVParser parser = CSVParser.parse(csvData, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (CSVRecord record : parser) {
            Match match = new Match();
            match.setId(Integer.parseInt(record.get(0)));
            match.setMatchNum(Integer.parseInt(record.get(1)));
            match.setTeam(Integer.parseInt(record.get(2)));
            match.setScore(Integer.parseInt(record.get(3)));
            String[] tags = record.get(4).substring(1, record.get(4).length() - 1).split(",");
            for (int i = 0; i < tags.length; i++)
                tags[i] = tags[i].trim();
            if (tags.length > 0 && !tags[0].equals(""))
                match.setTags(Arrays.asList(tags));
            else
                match.setTags(new ArrayList<String>());
            if (checkForMatch(match.getMatchNum(), match.getTeam()))
                update(match);
            else
                create(match);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.coheigea.bigdata.knox.ranger.KnoxRangerTest.java

private void makeWebHDFSInvocation(int statusCode, String user, String password) throws IOException {

    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }//from ww w.j  av  a  2 s  .c o  m
    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/webhdfs-liststatus-test.json");

    hdfsServer.expect().method("GET").pathInfo("/v1/hdfstest").queryParam("op", "LISTSTATUS").respond()
            .status(HttpStatus.SC_OK).content(IOUtils.toByteArray(path.toUri()))
            .contentType("application/json");

    ValidatableResponse response = given().log().all().auth().preemptive().basic(user, password)
            .header("X-XSRF-Header", "jksdhfkhdsf").queryParam("op", "LISTSTATUS").when()
            .get("http://localhost:" + gateway.getAddresses()[0].getPort() + "/gateway/cluster/webhdfs"
                    + "/v1/hdfstest")
            .then().statusCode(statusCode).log().body();

    if (statusCode == HttpStatus.SC_OK) {
        response.body("FileStatuses.FileStatus[0].pathSuffix", is("dir"));
    }
}

From source file:com.romeikat.datamessie.core.base.util.FileUtil.java

public synchronized void appendToFile(final File file, final String content) {
    final Path path = FileSystems.getDefault().getPath(file.getAbsolutePath());
    final Charset charset = Charset.defaultCharset();
    try (BufferedWriter writer = Files.newBufferedWriter(path, charset, StandardOpenOption.APPEND)) {
        writer.write(String.format("%s%n", content));
    } catch (final Exception e) {
        LOG.error("Could not apennd to file " + file.getAbsolutePath(), e);
    }//from ww w .j  a va 2s.c  o m
}

From source file:org.apache.storm.utils.ServerUtils.java

public static String getFileOwner(String path) throws IOException {
    return Files.getOwner(FileSystems.getDefault().getPath(path)).getName();
}

From source file:cpd3314.project.CPD3314ProjectTest.java

@Test
public void testGetDateAndOutput() throws Exception {
    System.out.println("main");
    String[] args = { "-getDate=2014-02-09", "-o=byDate" };
    CPD3314Project.main(args);//  www . j  a v  a2s  .c  o m
    File expected = FileSystems.getDefault().getPath("testFiles", "getDate.xml").toFile();
    File result = new File("byDate.xml");
    assertTrue("Output File Doesn't Exist", result.exists());
    assertXMLFilesEqual(expected, result);
}

From source file:jonelo.jacksum.concurrent.Jacksum2Cli.java

private void loadFilesToHash(List<Path> allFiles, Map<Path, Long> fileSizes, Map<Path, Long> fileLastModified)
        throws IOException {

    final int maxDepth = this.recursive ? Integer.MAX_VALUE : 1;
    final FileSystem fs = FileSystems.getDefault();
    final FileVisitOption[] options = this.ignoreSymbolicLinksToDirectories ? new FileVisitOption[0]
            : new FileVisitOption[] { FileVisitOption.FOLLOW_LINKS };

    for (String filename : this.filenames) {
        Files.walk(fs.getPath(filename), maxDepth, options).filter(path -> Files.isRegularFile(path))
                .forEach(path -> {//from w  w  w .  j  a v a2  s .c  om
                    allFiles.add(path);
                    try {
                        fileSizes.put(path, Files.size(path));
                        fileLastModified.put(path, Files.getLastModifiedTime(path).toMillis());
                    } catch (IOException ioEx) {
                        fileSizes.put(path, -1l);
                        fileLastModified.put(path, 0l);
                    }
                });
    }

}

From source file:us.colloquy.sandbox.FileProcessor.java

@Test
public void getURIForAllDiaries() {

    Set<DocumentPointer> uriList = new HashSet<>();
    //String letterDirectory = System.getProperty("user.home") + "/Documents/Tolstoy/openDiaries";

    ////ww  w.  j ava  2  s  .c om

    String letterDirectory = System.getProperty("user.home")
            + "/Documents/Tolstoy/90-volume-set/diaries/uzip/dnevnik_1881-1887_vol_49";

    Path pathToLetters = FileSystems.getDefault().getPath(letterDirectory);

    List<Path> results = new ArrayList<>();

    int maxDepth = 6;

    try (Stream<Path> stream = Files.find(pathToLetters, maxDepth, (path, attr) -> {
        return String.valueOf(path).endsWith(".ncx");
    })) {

        stream.forEach(results::add);

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("files: " + results.size());

    try {

        for (Path res : results) {
            Path parent = res.getParent();

            //                System.out.println("---------------------------------------------");
            //                System.out.println(parent.toString());
            //use jsoup to list all files that contain something useful
            Document doc = Jsoup.parse(res.toFile(), "UTF-8");

            String title = "";

            for (Element element : doc.getElementsByTag("docTitle")) {
                //Letter letter = new Letter();

                // StringBuilder content = new StringBuilder();

                for (Element child : element.children()) {
                    title = child.text();
                    // System.out.println("Title: " + title);
                }
            }

            //  System.out.println("==========================   " + res.toString() + " ==========================");

            boolean startPrinting = false;

            boolean newFile = true;

            for (Element element : doc.getElementsByTag("navPoint")) {

                //get nav label and content

                Element navLabelElement = element.select("navLabel").first();
                Element srsElement = element.select("content").first();

                String navLabel = "";
                String srs = "";

                if (navLabelElement != null) {
                    navLabel = navLabelElement.text().replaceAll("\\*", "").trim();
                }

                if (srsElement != null) {
                    srs = srsElement.attr("src");
                }

                if ("??".matches(navLabel))

                {
                    startPrinting = false;

                    // System.out.println("----------------- end of file pointer ---------------");
                }

                if (StringUtils.isNotEmpty(navLabel)
                        && navLabel.matches("??.*|?? ?.*") && newFile) {
                    newFile = false;
                    startPrinting = true;
                    title = navLabel;
                }

                if (startPrinting) {
                    // System.out.println("----------------- file pointer ---------------");
                    //   System.out.println(navLabel + "\t" + srs);

                    DocumentPointer documentPointer = new DocumentPointer(
                            parent.toString() + File.separator + srs.replaceAll("#.*", ""), title);

                    uriList.add(documentPointer);
                }

                //                    for (Element child : element.children())
                //                    {
                //                        String label = child.text();
                //
                //                        if (StringUtils.isNotEmpty(label))
                //                        {
                //                            if (label.matches("??\\s\\d{4}.*"))
                //                            {
                //                                System.out.println("------------------");
                //                            }

                //
                //                            String url = child.getElementsByTag("content").attr("src");
                //
                //                            if (label.matches(".*\\d{1,3}.*[?--?]+.*") &&
                //                                    StringUtils.isNotEmpty(url))
                //                            {
                //                                DocumentPointer letterPointer = new DocumentPointer(parent.toString()
                //                                        + File.separator + url.replaceAll("#.*", ""), title);
                //
                //                                uriList.add(letterPointer);
                ////                                System.out.println("nav point: " + label + " src " + parent.toString()
                ////                                        + System.lineSeparator() + url.replaceAll("#.*",""));
                //
                //
                //                            } else if (label.matches(".*\\d{1,3}.*") &&
                //                                    StringUtils.isNotEmpty(url) && useOnlyNumber)
                //                            {
                //                                DocumentPointer letterPointer = new DocumentPointer(parent.toString()
                //                                        + File.separator + url.replaceAll("#.*", ""), title);
                //
                //                                uriList.add(letterPointer);
                ////                                System.out.println("nav point: " + label + " src " + parent.toString()
                ////                                        + System.lineSeparator() + url.replaceAll("#.*",""));
                //
                //
                //                            } else
                //                            {
                //                                // System.out.println("nav point: " + label + " src " + child.getElementsByTag("content").attr("src"));
                //                            }
                //
                //
                //                        }
                //                        }
            }

            //   System.out.println("==========================   END OF FILE ==========================");

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Size: " + uriList.size());

    for (DocumentPointer pointer : uriList) {
        //parse and
        System.out.println(pointer.getSourse() + "\t" + pointer.getUri());
    }
}

From source file:com.ipn.escom.ageinnn.aspirante.controller.CargaDocumentoAction.java

public String upload() throws Exception {
    String response = SUCCESS;//w w  w  .  jav a 2 s  . c o  m
    if (this.aspirante != null) {
        System.out.println("Updloading files... ");
        if (aspirante.getDocumentos().isEmpty()) {
            aspirante.setFechaEnvioSolicitud(new Date());
            aspirante.setFechaModificacionDocumento(new Date());
            aspiranteService.update(aspirante);
        }
        if (this.id == null || this.id.size() != this.uploads.size()) {
            response = INPUT;
            return response;
        }
        try {
            for (int i = 0; i < this.id.size(); i++) {

                DocumentoRequerido documentoRequerido = catalogoService.find(DocumentoRequerido.class,
                        this.id.get(i));
                if (null == documentoRequerido) {
                    response = INPUT;
                    break;
                }

                DocumentoEntregado documentoEntregado = new DocumentoEntregado();
                DocumentoEntregadoId documentoEntregadoId = new DocumentoEntregadoId(
                        this.aspirante.getMedicoId(), aspirante.getPeriodoAdmisionId(),
                        documentoRequerido.getId());
                documentoEntregado.setPk(documentoEntregadoId);
                EstadoRevision estadoRevision = catalogoService.findByNombre(EstadoRevision.class,
                        "Sin revisar");
                documentoEntregado.setEstadoRevisionId(estadoRevision.getId());

                String separetor = FileSystems.getDefault().getSeparator();
                System.out.println("separetor: " + separetor);
                String realPath = ServletActionContext.getServletContext().getRealPath("/");
                String documentsPath = "WEB-INF" + separetor + "documents" + separetor + "aspirantes"
                        + separetor + this.aspirante.getMedico().getId().toString() + separetor
                        + aspirante.getPeriodoAdmisionId();
                String absolutePath = realPath + documentsPath;

                String fileName = this.aspirante.getMedico().getId().toString() + "_"
                        + aspirante.getPeriodoAdmisionId() + "_" + documentoRequerido.getId().toString();
                String extension = FilenameUtils.getExtension(uploadFileNames.get(i));

                documentoEntregado.setRuta(documentsPath);
                documentoEntregado.setNombreArchivo(fileName);
                documentoEntregado.setExtension(extension);

                File filePath = new File(absolutePath);
                filePath.mkdirs();
                File file = new File(filePath, fileName + "." + extension);
                FileInputStream fis = new FileInputStream(uploads.get(i));
                FileOutputStream fos = new FileOutputStream(file);
                byte[] datos = new byte[(int) uploads.get(i).length()];
                fis.read(datos);
                fos.write(datos);
                fis.close();
                fos.close();

                this.aspiranteService.guardarDocumento(documentoEntregado);

            }
        } catch (Exception e) {

            response = INPUT;
            throw e;
        }

    } else {
        response = INPUT;
    }
    addActionMessage("Documentos Enviados");
    return response;

}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./*from   w  w w.j a v  a  2  s.c  om*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:org.zanata.ZanataInit.java

/**
 * Returns true if any of the files appear to be stored in NFS (or we can't
 * tell).//  w  w  w .  j  a  v a  2 s  . c  o  m
 */
private boolean mightUseNFS(File... files) {
    try {
        FileSystem fileSystem = FileSystems.getDefault();
        for (File file : files) {
            Path path = fileSystem.getPath(file.getAbsolutePath());
            String fileStoreType = Files.getFileStore(path).type();
            if (fileStoreType.toLowerCase().contains("nfs")) {
                return true;
            }
        }
        return false;
    } catch (IOException e) {
        log.warn(e.toString(), e);
        // assume the worst case
        return true;
    }
}