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:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java

@Override
public synchronized void start() {
    if (!this.running) {
        this.directory = getFileRepo();
        if (this.directory != null && !this.directory.isEmpty()) {
            log.info("Monitoring for local config changes: " + this.directory);
            try {
                this.watcher = FileSystems.getDefault().newWatchService();
                for (Path path : this.directory) {
                    walkDirectory(path);
                }//w w  w  .  j a v a  2  s .co  m
            } catch (IOException e) {
            }
        } else {
            log.info("Not monitoring for local config changes");
        }
        this.running = true;
    }
}

From source file:edu.usc.pgroup.floe.utils.Utils.java

/**
 * Checks if the filename (to be uploaded or downloaded) is valid.
 * It should not contain ".." and should not be an absolute path.
 *
 * @param fileName filename to be uploaded or downloaded relative to the
 *                 coordinator's scratch folder.
 * @return returns true if the filename is valid and can be used in the
 * download or upload functions./* www.j a  v a2  s.  co  m*/
 */
public static boolean checkValidFileName(final String fileName) {
    if (fileName.contains("..")) {
        return false;
    }

    Path filePath = FileSystems.getDefault().getPath(fileName);
    if (filePath.isAbsolute()) {
        return true;
    }
    return true;
}

From source file:com.talkdesk.geo.GeoCodeRepositoryBuilder.java

/**
 * Format of the file loading data from// w  ww  .ja v  a  2 s  . c o  m
 * geonameid         : integer id of record in geonames database
 * name              : name of geographical point (utf8) varchar(200)
 * asciiname         : name of geographical point in plain ascii characters, varchar(200)
 * alternatenames    : alternatenames, comma separated, ascii names automatically transliterated, convenience attribute from alternatename table, varchar(10000)
 * latitude          : latitude in decimal degrees (wgs84)
 * longitude         : longitude in decimal degrees (wgs84)
 * feature class     : see http://www.geonames.org/export/codes.html, char(1)
 * feature code      : see http://www.geonames.org/export/codes.html, varchar(10)
 * country code      : ISO-3166 2-letter country code, 2 characters
 * cc2               : alternate country codes, comma separated, ISO-3166 2-letter country code, 60 characters
 * admin1 code       : fipscode (subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20)
 * admin2 code       : code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80)
 * admin3 code       : code for third level administrative division, varchar(20)
 * admin4 code       : code for fourth level administrative division, varchar(20)
 * population        : bigint (8 byte int)
 * elevation         : in meters, integer
 * dem               : digital elevation model, srtm3 or gtopo30, average elevation of 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer. srtm processed by cgiar/ciat.
 * timezone          : the timezone id (see file timeZone.txt) varchar(40)
 * modification date : date of last modification in yyyy-MM-dd format
 *
 * @throws IOException
 */
public void populateGeoData() throws GeoResolverException {

    try {
        if (connection == null)
            connection = connectToDatabase();
        if (!new File(geocodeDataLocation).exists()) {
            log.error("No Data file found for geoData. please add to data/geodata.tsv ");
            return;
        }

        Path file = FileSystems.getDefault().getPath(geocodeDataLocation);
        Charset charset = Charset.forName("UTF-8");
        BufferedReader inputStream = Files.newBufferedReader(file, charset);
        String buffer;
        PreparedStatement preparedStatement;
        preparedStatement = connection
                .prepareStatement("INSERT INTO geocodes (ID , CITY_NAME, LATITUDE, LONGITUDE, COUNTRY_CODE)"
                        + " VALUES (?,?,?,?,?)");
        while ((buffer = inputStream.readLine()) != null) {
            String[] values = buffer.split("\t");

            preparedStatement.setInt(1, Integer.parseInt(values[0].trim()));
            preparedStatement.setString(2, values[1].trim());
            preparedStatement.setFloat(3, Float.parseFloat(values[4].trim()));
            preparedStatement.setFloat(4, Float.parseFloat(values[5].trim()));
            preparedStatement.setString(5, values[8].trim());

            preparedStatement.execute();

        }
    } catch (SQLException e) {
        throw new GeoResolverException("Error while executing SQL query", e);
    } catch (IOException e) {
        throw new GeoResolverException("Error while accessing input file", e);
    }
    log.info("Finished populating Database.");
    //should close all the connections for memory leaks.
}

From source file:nl.uva.DataHandler.Indexing.java

@Override
public void Indexer(String indexPathString) throws Exception, Throwable {
    try {//from   ww  w.  j  ava  2  s.  c  o  m
        log.info(
                "----------------------- INDEXING - Override Version: for BM25 :)  --------------------------");

        Path ipath = FileSystems.getDefault().getPath(indexPathString);
        super.IndexesCleaner(indexPathString);
        MyAnalyzer myAnalyzer;
        if (!super.stopWordsRemoving)
            myAnalyzer = new MyAnalyzer(super.stemming);
        else
            myAnalyzer = new MyAnalyzer(super.stemming, super.LoadStopwords());

        Analyzer analyzer = myAnalyzer.getAnalyzer(configFile.getProperty("CORPUS_LANGUAGE"));
        PerFieldAnalyzerWrapper prfWrapper = new PerFieldAnalyzerWrapper(analyzer, super.analyzerMap);
        IndexWriterConfig irc = new IndexWriterConfig(prfWrapper);
        irc.setSimilarity(new BM25Similarity(1.2F, 0.75F));
        this.writer = new IndexWriter(new SimpleFSDirectory(ipath), irc);
        this.docIndexer();
        this.writer.commit();
        this.writer.close();
        analyzer.close();
        prfWrapper.close();
        log.info("-------------------------------------------------");
        log.info("Index is created successfully...");
        log.info("-------------------------------------------------");

    } catch (Exception ex) {
        log.error(ex);
        throw ex;
    }
}

From source file:uk.org.openeyes.diagnostics.FhirUtils.java

/**
 *
 * @param reference// www . j  a  va2s.  c  om
 * @param attachments
 * @return
 * @throws IOException
 */
public DiagnosticReport createDiagnosticReport(int patientRef, String reference, File[] attachments)
        throws IOException {
    DiagnosticReport report = DiagnosticReport.Factory.newInstance();

    ResourceReference subject = report.addNewSubject();
    subject.addNewReference().setValue("patient/pat-" + patientRef);
    DiagnosticReportImage image = report.addNewImage();
    ResourceReference imageRef = image.addNewLink();
    org.hl7.fhir.String ref = imageRef.addNewReference();
    ref.setValue(reference);
    for (int i = 0; i < attachments.length; i++) {
        ResourceReference resref = report.addNewResult();
        resref.addNewReference().setValue("#r" + (i + 1)); // TODO
        ResourceInline inline = report.addNewContained();
        Observation o = inline.addNewObservation();
        o.setId("r" + (i + 1));

        Attachment att = o.addNewValueAttachment();
        Base64Binary binary = att.addNewData();
        Path path = FileSystems.getDefault().getPath(attachments[i].getParentFile().getAbsolutePath(),
                attachments[i].getName());
        att.addNewContentType().setValue(Files.probeContentType(path));
        att.addNewTitle().setValue(attachments[i].getName());
        binary.setValue(this.base64encode(attachments[i]));
        att.setData(binary);

    }
    DiagnosticReportDocument doc = DiagnosticReportDocument.Factory.newInstance();
    doc.setDiagnosticReport(report);
    return report;
}

From source file:com.expedia.tesla.compiler.Util.java

/**
 * Expand glob file patterns to path strings. Any path element that is not a glob pattern will be keep as it is.
 * //from  w  ww. j  a  va  2  s .c om
 * @param pathOrPatterns
 *       glob patterns.
 * 
 * @return
 *       The expanded paths.
 * 
 * @throws IOException
 *       On IO errors.
 */
public static Collection<String> expandWildcard(Collection<String> pathOrPatterns) throws IOException {
    final List<String> files = new ArrayList<String>();
    final List<PathMatcher> matchers = new ArrayList<PathMatcher>();
    for (String pattern : pathOrPatterns) {
        if (pattern.contains("*") || pattern.contains("?")) {
            PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
            matchers.add(matcher);
        } else {
            files.add(pattern);
        }
    }

    if (!matchers.isEmpty()) {
        Files.walkFileTree(new File(System.getProperty("user.dir")).toPath(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
                for (PathMatcher matcher : matchers) {
                    if (matcher.matches(file)) {
                        files.add(file.toString());
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }

    return files;
}

From source file:org.teknux.dropbitz.controller.UploadController.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML })
@Authenticated/*from w w  w  . ja  v  a  2  s  .  c o  m*/
public Response uploadFile(@FormDataParam("file") final InputStream inputStream,
        @FormDataParam("file") final FormDataContentDisposition formDataContentDisposition,
        @FormDataParam("name") final String name, @FormDataParam("email") final String email,
        @FormDataParam("fallback") final Boolean fallback) {

    String fileName = null;
    try {
        fileName = new String(formDataContentDisposition.getFileName().getBytes(CHARSET_ISO_8859_1),
                CHARSET_UTF8);
    } catch (UnsupportedEncodingException e) {
        logger.warn("Can not translate file name charset", e);
        fileName = formDataContentDisposition.getFileName();
    }
    ;

    logger.trace("Checking email");
    if (!email.isEmpty()) {
        //validate email
        if (!EmailValidator.getInstance().isValid(email)) {
            return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName,
                    i18n(I18nKey.DROP_FILE_EMAIL_ERROR));
        }
    }

    String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT));
    String destFileName = date + (name.isEmpty() ? "" : "-" + name) + "-" + fileName;

    try {
        if (formDataContentDisposition.getFileName().isEmpty()) {
            return getResponse(fallback, Status.BAD_REQUEST, fileName, i18n(I18nKey.DROP_FILE_MISSING));
        }
        Configuration config = getServiceManager().getService(IConfigurationService.class).getConfiguration();
        java.nio.file.Path outputPath = FileSystems.getDefault()
                .getPath(config.getDirectory().getAbsolutePath(), destFileName);

        //Checks destination directory
        if (!FileUtil.isChildOfDirectory(outputPath.toFile(), config.getDirectory())) {
            return getResponse(fallback, Status.FORBIDDEN, fileName, i18n(I18nKey.DROP_FILE_MISSING));
        }

        Files.copy(inputStream, outputPath);

        long fileSize = outputPath.toFile().length();
        sendEmail(true, name, fileName, destFileName, fileSize, email);
    } catch (IOException e) {
        logger.error("Can not copy file", e);

        sendEmail(false, name, fileName, null, 0L, email);
        return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName, i18n(I18nKey.DROP_FILE_ERROR));
    }

    return getResponse(fallback, Status.OK, fileName, null);
}

From source file:org.apache.zeppelin.storage.LocalConfigStorage.java

private void atomicWriteToFile(String content, File file) throws IOException {
    File directory = file.getParentFile();
    File tempFile = File.createTempFile(file.getName(), null, directory);
    FileOutputStream out = new FileOutputStream(tempFile);
    try {// ww  w.  j  a v a 2s.c o m
        IOUtils.write(content, out);
    } catch (IOException iox) {
        if (!tempFile.delete()) {
            tempFile.deleteOnExit();
        }
        throw iox;
    }
    out.close();
    FileSystem defaultFileSystem = FileSystems.getDefault();
    Path tempFilePath = defaultFileSystem.getPath(tempFile.getCanonicalPath());
    Path destinationFilePath = defaultFileSystem.getPath(file.getCanonicalPath());
    try {
        Files.move(tempFilePath, destinationFilePath, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException iox) {
        if (!tempFile.delete()) {
            tempFile.deleteOnExit();
        }
        throw iox;
    }
}

From source file:cpd3314.project.CPD3314ProjectTest.java

@Test
public void testNoArg() throws Exception {
    System.out.println("main");
    String[] args = {};/*from ww  w  .j  av  a 2s  . co m*/
    CPD3314Project.main(args);
    File expected = FileSystems.getDefault().getPath("testFiles", "noArg.xml").toFile();
    File result = new File("CPD3314.xml");
    assertTrue("Output File Doesn't Exist", result.exists());
    assertXMLFilesEqual(expected, result);
}

From source file:org.ng200.openolympus.services.StorageService.java

public void setSolutionFile(final Solution solution, final Path file) {
    solution.setFile(/*from w  w w. j a va 2s.c  o  m*/
            FileSystems.getDefault().getPath(this.storagePath, "solutions").relativize(file).toString());
}