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.ccserver.digital.controller.CreditCardApplicationDocumentControllerTest.java

@Test
public void downloadDocumentByIdDocMockTest() throws IOException, URISyntaxException {
    File ifile = new File("./src/main/resources/sample");
    Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf");
    byte[] idDocByteArray = Files.readAllBytes(idDocPath);

    CreditCardApplicationDocumentThumbNailDTO CCAppDocThumbNailDTO = new CreditCardApplicationDocumentThumbNailDTO();
    CCAppDocThumbNailDTO.setId(1L);//from  w w  w. jav  a2s .c  o  m
    CCAppDocThumbNailDTO.setDocument(idDocByteArray);
    CCAppDocThumbNailDTO.setThumbNail(idDocByteArray);
    CCAppDocThumbNailDTO.setFileName("name");

    Mockito.when(mockDocService.findByCreditCardApplicationDocumentId(1L)).thenReturn(CCAppDocThumbNailDTO);
    Mockito.when(mockDocService.documentIsBelongToApp(1L, 1L)).thenReturn(true);

    ResponseEntity<?> response = mockDocController.downloadDocumentByDocId(1L, 1L);
    CreditCardApplicationDocumentThumbNailDTO result = (CreditCardApplicationDocumentThumbNailDTO) response
            .getBody();

    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

    Assert.assertTrue(result.getId() > 0);
}

From source file:org.sonar.java.AbstractJavaClasspath.java

private static Set<File> getMatchingLibraries(String pattern, Path dir) throws IOException {
    Set<File> matches = new LinkedHashSet<>();
    Set<File> dirs = getMatchingDirs(pattern, dir);

    PathMatcher matcher = FileSystems.getDefault().getPathMatcher(getGlob(dir, pattern));
    for (File d : dirs) {
        matches.addAll(getLibs(d.toPath()));
    }//ww  w . j a v  a2  s . c  om

    matches.addAll(dirs);
    matches.addAll(new LibraryFinder().find(dir, matcher));
    if (pattern.startsWith("**/")) {
        // match jar in the base dir when using wildcard
        matches.addAll(new LibraryFinder().find(dir,
                FileSystems.getDefault().getPathMatcher(getGlob(dir, pattern.substring(3)))));
    }
    return matches;
}

From source file:de.flashpixx.rrd_antlr4.TestCLanguageLabels.java

/**
 * test-case all resource strings//from ww  w. j a  v  a  2 s . c o  m
 *
 * @throws IOException throws on io errors
 */
@Test
public void testResourceString() throws IOException {
    assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty());

    final Set<String> l_ignoredlabel = new HashSet<>();

    // --- parse source and get label definition
    final Set<String> l_label = Collections.unmodifiableSet(Files.walk(Paths.get(SEARCHPATH))
            .filter(Files::isRegularFile).filter(i -> i.toString().endsWith(".java")).flatMap(i -> {
                try {
                    final CJavaVistor l_parser = new CJavaVistor();
                    l_parser.visit(JavaParser.parse(new FileInputStream(i.toFile())), null);
                    return l_parser.labels().stream();
                } catch (final IOException l_excpetion) {
                    assertTrue(MessageFormat.format("io error on file [{0}]: {1}", i, l_excpetion.getMessage()),
                            false);
                    return Stream.<String>empty();
                } catch (final ParseException l_exception) {
                    // add label build by class path to the ignore list
                    l_ignoredlabel.add(i.toAbsolutePath().toString()
                            // remove path to class directory
                            .replace(FileSystems.getDefault().provider().getPath(SEARCHPATH).toAbsolutePath()
                                    .toString(), "")
                            // string starts with path separator
                            .substring(1)
                            // remove file extension
                            .replace(".java", "")
                            // replace separators with dots
                            .replace("/", CLASSSEPARATOR)
                            // convert to lower-case
                            .toLowerCase()
                            // remove package-root name
                            .replace(CCommon.PACKAGEROOT + CLASSSEPARATOR, ""));

                    System.err.println(MessageFormat.format("parsing error on file [{0}]:\n{1}", i,
                            l_exception.getMessage()));
                    return Stream.<String>empty();
                }
            }).collect(Collectors.toSet()));

    // --- check of any label is found
    assertFalse("translation labels are empty, check naming of translation method", l_label.isEmpty());

    // --- check label towards the property definition
    if (l_ignoredlabel.size() > 0)
        System.err.println(MessageFormat.format(
                "labels that starts with {0} are ignored, because parsing errors are occurred",
                l_ignoredlabel));

    LANGUAGEPROPERY.entrySet().forEach(i -> {
        try {
            final Properties l_property = new Properties();
            l_property.load(new FileInputStream(new File(i.getValue())));

            final Set<String> l_parseditems = new HashSet<>(l_label);
            final Set<String> l_propertyitems = l_property.keySet().parallelStream().map(Object::toString)
                    .collect(Collectors.toSet());

            // --- check if all property items are within the parsed labels
            l_parseditems.removeAll(l_propertyitems);
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the language file:\n{2}",
                    i.getKey(), l_parseditems.size(), StringUtils.join(l_parseditems, ", ")),
                    l_parseditems.isEmpty());

            // --- check if all parsed labels within the property item and remove ignored labels
            l_propertyitems.removeAll(l_label);
            final Set<String> l_ignoredpropertyitems = l_propertyitems.parallelStream()
                    .filter(j -> l_ignoredlabel.parallelStream().map(j::startsWith).allMatch(l -> false))
                    .collect(Collectors.toSet());
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the source code:\n{2}",
                    i.getKey(), l_ignoredpropertyitems.size(), StringUtils.join(l_ignoredpropertyitems, ", ")),
                    l_ignoredpropertyitems.isEmpty());
        } catch (final IOException l_exception) {
            assertTrue(MessageFormat.format("io exception: {0}", l_exception.getMessage()), false);
        }
    });
}

From source file:cpd3314.project.CPD3314ProjectTest.java

@Test
public void testOutput() throws Exception {
    System.out.println("main");
    String[] args = { "-o=test" };
    CPD3314Project.main(args);//from www .  j a  v a  2s .c  o m
    File expected = FileSystems.getDefault().getPath("testFiles", "noArg.xml").toFile();
    File result = new File("test.xml");
    assertTrue("Output File Doesn't Exist", result.exists());
    assertXMLFilesEqual(expected, result);
}

From source file:org.wso2.carbon.inbound.localfile.LocalFileOneTimePolling.java

@SuppressWarnings("unchecked")
private Object watchDirectory() throws IOException {
    Path newPath = Paths.get(watchedDir);
    WatchService watchService = FileSystems.getDefault().newWatchService();
    try {//from   w  w  w  .j a v  a 2  s . c  om
        newPath.register(watchService, ENTRY_MODIFY);
        while (true) {
            WatchKey key = watchService.take();
            if (key != null) {
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = watchEvent.kind();
                    WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    Path entry = watchEventPath.context();

                    Path filePath = Paths.get(watchedDir, entry.toString());
                    if (kind == ENTRY_MODIFY) {
                        processFile(filePath, contentType);
                    } else if (kind == OVERFLOW) {
                        continue;
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Processing file is : " + entry);
                    }
                }
                key.reset();
                if (!key.isValid()) {
                    break;
                }
            }
        }
    } catch (IOException e) {
        log.error("Error while watching directory: " + e.getMessage(), e);
    } catch (InterruptedException ie) {
        log.error("Error while get the WatchKey : " + ie.getMessage(), ie);
    } finally {
        watchService.close();
    }
    return null;
}

From source file:org.jacoco.examples.ReportGenerator.java

private List<File> getFileNames(List<File> fileNames, Path dir) {

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path path : stream) {
            if (path.toFile().isDirectory()) {
                getFileNames(fileNames, path);
            } else {
                boolean match = false;
                for (String pattern : regexes) {
                    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
                    if (matcher.matches(path)) {
                        match = true;//from  w  w w  . jav a 2 s  .  c  om
                        break;
                    }
                }
                if (!match) {
                    fileNames.add(path.toFile());
                }
            }
        }
    } catch (

    IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:com.acmutv.ontoqa.tool.io.IOManagerTest.java

/**
 * Tests directory listing./*from www .ja v a 2  s .  c o m*/
 */
@Test
public void test_listAllFiles() throws IOException {
    String directory = IOManagerTest.class.getResource("/tool/io/").getPath();
    List<Path> actual = IOManager.allFiles(directory);
    actual.sort(Comparator.naturalOrder());

    List<Path> expected = new ArrayList<>();
    expected.add(
            FileSystems.getDefault().getPath(IOManagerTest.class.getResource("/tool/io/sample").getPath()));
    expected.add(
            FileSystems.getDefault().getPath(IOManagerTest.class.getResource("/tool/io/sample.txt").getPath()));
    expected.sort(Comparator.naturalOrder());

    Assert.assertEquals(expected, actual);
}

From source file:uk.ac.ebi.metabolights.webservice.utils.FileUtil.java

/**
 * Create a private FTP folder for uploading big study files
 *
 * @param folder//from   w  w  w .  ja va2  s . c  om
 * @return a String containing created folder
 * @author jrmacias
 * @date 20151102
 */
@PostConstruct
public static Path createFtpFolder(String folder) throws IOException {

    String privateFTPRoot = PropertiesUtil.getProperty("privateFTPRoot"); // ~/ftp_private/

    // create the folder
    File ftpFolder = new File(privateFTPRoot + File.separator + folder);
    Path folderPath = ftpFolder.toPath();
    if (!ftpFolder.mkdir())
        throw new IOException();

    // set folder owner, group and access permissions
    // 'chmod 770'
    UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
    Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
    // owner permissions
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    // group permissions
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    // apply changes
    Files.getFileAttributeView(folderPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
            .setPermissions(perms);

    return folderPath;
}

From source file:org.apache.hadoop.hive.llap.cache.BuddyAllocator.java

@VisibleForTesting
public BuddyAllocator(boolean isDirectVal, boolean isMappedVal, int minAllocVal, int maxAllocVal,
        int arenaCount, long maxSizeVal, long defragHeadroom, String mapPath, MemoryManager memoryManager,
        LlapDaemonCacheMetrics metrics, String discardMethod) {
    isDirect = isDirectVal;//  w w w.  j  a  va 2s  .  c  o m
    isMapped = isMappedVal;
    minAllocation = minAllocVal;
    maxAllocation = maxAllocVal;
    if (isMapped) {
        try {
            cacheDir = Files.createTempDirectory(FileSystems.getDefault().getPath(mapPath), "llap-", RWX);
        } catch (IOException ioe) {
            // conf validator already checks this, so it will never trigger usually
            throw new AssertionError("Configured mmap directory should be writable", ioe);
        }
    } else {
        cacheDir = null;
    }

    arenaSize = validateAndDetermineArenaSize(arenaCount, maxSizeVal);
    maxSize = validateAndDetermineMaxSize(maxSizeVal);
    memoryManager.updateMaxSize(determineMaxMmSize(defragHeadroom, maxSize));

    minAllocLog2 = 31 - Integer.numberOfLeadingZeros(minAllocation);
    maxAllocLog2 = 31 - Integer.numberOfLeadingZeros(maxAllocation);
    arenaSizeLog2 = 63 - Long.numberOfLeadingZeros(arenaSize);
    maxArenas = (int) (maxSize / arenaSize);
    arenas = new Arena[maxArenas];
    for (int i = 0; i < maxArenas; ++i) {
        arenas[i] = new Arena();
    }
    Arena firstArena = arenas[0];
    firstArena.init(0);
    allocatedArenas.set(1);
    this.memoryManager = memoryManager;
    defragCounters = new AtomicLong[maxAllocLog2 - minAllocLog2 + 1];
    for (int i = 0; i < defragCounters.length; ++i) {
        defragCounters[i] = new AtomicLong(0);
    }
    this.metrics = metrics;
    metrics.incrAllocatedArena();
    boolean isBoth = null == discardMethod || "both".equalsIgnoreCase(discardMethod);
    doUseFreeListDiscard = isBoth || "freelist".equalsIgnoreCase(discardMethod);
    doUseBruteDiscard = isBoth || "brute".equalsIgnoreCase(discardMethod);
    ctxPool = new FixedSizedObjectPool<DiscardContext>(32,
            new FixedSizedObjectPool.PoolObjectHelper<DiscardContext>() {
                @Override
                public DiscardContext create() {
                    return new DiscardContext();
                }

                @Override
                public void resetBeforeOffer(DiscardContext t) {
                }
            });
}

From source file:acromusashi.kafka.log.producer.WinApacheLogProducer.java

/**
 * tail??/*  ww w  .j a va  2s.  c o m*/
 *
 * @param targetPath ?
 */
public void tailRun(File targetPath) {
    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
        Path targetDir = targetPath.toPath();
        targetDir.register(watcher, ENTRY_MODIFY);
        targetDir.relativize(targetPath.toPath());
        List<String> targetFileNames = getTargetLogFiles(Lists.newArrayList(targetDir.toFile().list()));
        Collections.sort(targetFileNames);
        int logFileNameSize = targetFileNames.size();
        this.targetFile = new File(targetDir + "/" + targetFileNames.get(logFileNameSize - 1));

        while (true) {
            WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    logger.warn("OVERFLOW");
                    continue;
                }
                byte[] tail = null;
                boolean noRetry = false;
                for (int retryCount = 0; retryCount < this.retryNum; retryCount++) {
                    try {
                        tail = getTail(this.targetFile);
                        break;
                    } catch (IOException ex) {
                        if (retryCount == this.retryNum - 1) {
                            noRetry = true;
                        }
                    }
                }
                // ?????????????????
                if (noRetry) {
                    break;
                }
                List<String> allFileName = getTargetLogFiles(Arrays.asList(targetDir.toFile().list()));
                Collections.sort(allFileName);
                int allFileNameSize = allFileName.size();
                if (tail.length > 0) {
                    String inputStr = new String(tail, this.encoding);
                    if (!allFileName.equals(targetFileNames)) {
                        this.newFileName.add(allFileName.get(allFileNameSize - 1));
                        targetFileNames = allFileName;
                    }

                    List<String> eachStr = Arrays.asList(inputStr.split(System.getProperty("line.separator")));
                    List<KeyedMessage<String, String>> list = getKeyedMessage(eachStr);
                    this.producer.send(list);
                } else {
                    if (!allFileName.equals(targetFileNames)) {
                        this.newFileName.add(allFileName.get(allFileNameSize - 1));
                        targetFileNames = allFileName;
                    }
                    if (this.newFileName.size() > 0) {
                        this.targetFile = new File(targetDir + "/" + this.newFileName.get(0));
                        this.newFileName.remove(0);
                        targetFileNames = allFileName;
                    }
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    } catch (Exception ex) {
        // FindBugs?Java7????????FindBugs?????????
        logger.error("Failed start producer. ", ex);
    }
}