Search in sources :

Example 46 with Files

use of java.nio.file.Files in project FXGL by AlmasB.

the class SaveLoadManager method querySaveFiles.

/**
 * Asynchronously (with a progress dialog) loads save files into observable list {@link #saveFiles()}.
 */
public void querySaveFiles() {
    log.debug("Querying save files");
    loadSaveFilesTask().onSuccess(files -> {
        saveFiles.setAll(files);
        Collections.sort(saveFiles, SaveFile.RECENT_FIRST);
    }).executeAsyncWithDialogFX(new ProgressDialog("Loading save files"));
}
Also used : FS(com.almasb.fxgl.io.FS) FileExtension(com.almasb.fxgl.io.FileExtension) Files(java.nio.file.Files) FXGL(com.almasb.fxgl.app.FXGL) FXCollections(javafx.collections.FXCollections) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) Platform(javafx.application.Platform) List(java.util.List) Paths(java.nio.file.Paths) IOTask(com.almasb.fxgl.io.IOTask) Logger(com.almasb.fxgl.core.logging.Logger) ObservableList(javafx.collections.ObservableList) ProgressDialog(com.almasb.fxgl.scene.ProgressDialog) Path(java.nio.file.Path) Collections(java.util.Collections) ProgressDialog(com.almasb.fxgl.scene.ProgressDialog)

Example 47 with Files

use of java.nio.file.Files in project meghanada-server by mopemope.

the class JavaAnalyzerTest method analyzeFail.

@Test
public void analyzeFail() throws Exception {
    System.setProperty(Source.REPORT_UNKNOWN_TREE, "false");
    final JavaAnalyzer analyzer = getAnalyzer();
    final String cp = getSystemClasspath();
    List<File> files;
    try (Stream<Path> stream = Files.walk(new File("./src/main/java").getCanonicalFile().toPath(), FileVisitOption.FOLLOW_LINKS)) {
        files = stream.filter(path -> {
            File file = path.toFile();
            return FileUtils.isJavaFile(file);
        }).map(Path::toFile).collect(Collectors.toList());
    }
    try (Stream<Path> stream = Files.walk(new File("./src/test/java").getCanonicalFile().toPath(), FileVisitOption.FOLLOW_LINKS)) {
        List<File> testFiles = stream.filter(path -> {
            File file = path.toFile();
            return FileUtils.isJavaFile(file);
        }).map(Path::toFile).collect(Collectors.toList());
        files.addAll(testFiles);
    }
    // System.setProperty(Source.REPORT_UNKNOWN_TREE, "true");
    final String tmp = System.getProperty("java.io.tmpdir");
    List<File> finalFiles = files;
    timeIt(() -> {
        final CompileResult compileResult = analyzer.analyzeAndCompile(finalFiles, cp, tmp);
        // compileResult.getSources().values().forEach(Source::dump);
        return compileResult;
    });
}
Also used : Path(java.nio.file.Path) BeforeClass(org.junit.BeforeClass) Config.timeIt(meghanada.config.Config.timeIt) ArrayList(java.util.ArrayList) Path(java.nio.file.Path) AfterClass(org.junit.AfterClass) Files(java.nio.file.Files) Assert.assertNotNull(org.junit.Assert.assertNotNull) Config.timeItF(meghanada.config.Config.timeItF) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) FileUtils(meghanada.utils.FileUtils) Collectors(java.util.stream.Collectors) File(java.io.File) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) Declaration(meghanada.docs.declaration.Declaration) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) FileVisitOption(java.nio.file.FileVisitOption) Optional(java.util.Optional) DeclarationSearcher(meghanada.docs.declaration.DeclarationSearcher) GradleTestBase(meghanada.GradleTestBase) Config(meghanada.config.Config) LogManager(org.apache.logging.log4j.LogManager) Assert.assertEquals(org.junit.Assert.assertEquals) File(java.io.File) Test(org.junit.Test)

Example 48 with Files

use of java.nio.file.Files in project meghanada-server by mopemope.

the class JavaAnalyzerTest method analyzeAll.

@Test
public void analyzeAll() throws Exception {
    System.setProperty(Source.REPORT_UNKNOWN_TREE, "true");
    // project.clearCache();
    final JavaAnalyzer analyzer = getAnalyzer();
    final String cp = getClasspath();
    List<File> files;
    try (Stream<Path> stream = Files.walk(new File("./src/main/java").getCanonicalFile().toPath(), FileVisitOption.FOLLOW_LINKS)) {
        files = stream.filter(path -> {
            File file = path.toFile();
            return FileUtils.isJavaFile(file);
        }).map(Path::toFile).collect(Collectors.toList());
    }
    try (Stream<Path> stream = Files.walk(new File("./src/test/java").getCanonicalFile().toPath(), FileVisitOption.FOLLOW_LINKS)) {
        List<File> testFiles = stream.filter(path -> {
            File file = path.toFile();
            return FileUtils.isJavaFile(file);
        }).map(Path::toFile).collect(Collectors.toList());
        files.addAll(testFiles);
    }
    final String tmp = System.getProperty("java.io.tmpdir");
    List<File> finalFiles = files;
    timeIt(() -> {
        final CompileResult compileResult = analyzer.analyzeAndCompile(finalFiles, cp, tmp);
        compileResult.getSources().values().forEach(Source::dump);
        return compileResult;
    });
}
Also used : Path(java.nio.file.Path) BeforeClass(org.junit.BeforeClass) Config.timeIt(meghanada.config.Config.timeIt) ArrayList(java.util.ArrayList) Path(java.nio.file.Path) AfterClass(org.junit.AfterClass) Files(java.nio.file.Files) Assert.assertNotNull(org.junit.Assert.assertNotNull) Config.timeItF(meghanada.config.Config.timeItF) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) FileUtils(meghanada.utils.FileUtils) Collectors(java.util.stream.Collectors) File(java.io.File) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) Declaration(meghanada.docs.declaration.Declaration) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) FileVisitOption(java.nio.file.FileVisitOption) Optional(java.util.Optional) DeclarationSearcher(meghanada.docs.declaration.DeclarationSearcher) GradleTestBase(meghanada.GradleTestBase) Config(meghanada.config.Config) LogManager(org.apache.logging.log4j.LogManager) Assert.assertEquals(org.junit.Assert.assertEquals) File(java.io.File) Test(org.junit.Test)

Example 49 with Files

use of java.nio.file.Files in project fess-crawler by codelibs.

the class FileSystemClient method getResponseData.

protected ResponseData getResponseData(final String uri, final boolean includeContent) {
    final ResponseData responseData = new ResponseData();
    try {
        responseData.setMethod(Constants.GET_METHOD);
        final String filePath = preprocessUri(uri);
        responseData.setUrl(filePath);
        File file = null;
        try {
            file = new File(new URI(filePath));
        } catch (final URISyntaxException e) {
            logger.warn("Could not parse url: " + filePath, e);
        }
        if (file == null) {
            responseData.setHttpStatusCode(Constants.NOT_FOUND_STATUS_CODE);
            responseData.setCharSet(charset);
            responseData.setContentLength(0);
        } else if (file.isFile()) {
            // check file size
            responseData.setContentLength(file.length());
            checkMaxContentLength(responseData);
            try {
                final FileOwnerAttributeView ownerAttrView = Files.getFileAttributeView(file.toPath(), FileOwnerAttributeView.class);
                if (ownerAttrView != null) {
                    UserPrincipal owner = ownerAttrView.getOwner();
                    if (owner != null) {
                        responseData.addMetaData(FS_FILE_USER, owner.getName());
                    }
                }
            } catch (Exception e) {
                logger.warn("Failed to parse FileOwnerAttributeView.", e);
            }
            try {
                final AclFileAttributeView aclView = Files.getFileAttributeView(file.toPath(), AclFileAttributeView.class);
                if (aclView != null) {
                    responseData.addMetaData(FILE_ATTRIBUTE_VIEW, aclView);
                    responseData.addMetaData(FS_FILE_GROUPS, aclView.getAcl().stream().map(acl -> acl.principal().getName()).toArray(n -> new String[n]));
                }
            } catch (Exception e) {
                logger.warn("Failed to parse AclFileAttributeView.", e);
            }
            try {
                final PosixFileAttributeView posixView = Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class);
                if (posixView != null) {
                    responseData.addMetaData(FILE_ATTRIBUTE_VIEW, posixView);
                    responseData.addMetaData(FS_FILE_GROUPS, new String[] { posixView.readAttributes().group().getName() });
                }
            } catch (Exception e) {
                logger.warn("Failed to parse PosixFileAttributeView.", e);
            }
            responseData.setHttpStatusCode(Constants.OK_STATUS_CODE);
            responseData.setCharSet(geCharSet(file));
            responseData.setLastModified(new Date(file.lastModified()));
            if (file.canRead()) {
                final MimeTypeHelper mimeTypeHelper = crawlerContainer.getComponent("mimeTypeHelper");
                try (final InputStream is = new BufferedInputStream(new FileInputStream(file))) {
                    responseData.setMimeType(mimeTypeHelper.getContentType(is, file.getName()));
                } catch (final Exception e) {
                    responseData.setMimeType(mimeTypeHelper.getContentType(null, file.getName()));
                }
                if (contentLengthHelper != null) {
                    final long maxLength = contentLengthHelper.getMaxLength(responseData.getMimeType());
                    if (responseData.getContentLength() > maxLength) {
                        throw new MaxLengthExceededException("The content length (" + responseData.getContentLength() + " byte) is over " + maxLength + " byte. The url is " + filePath);
                    }
                }
                if (includeContent) {
                    if (file.length() < maxCachedContentSize) {
                        try (InputStream contentStream = new BufferedInputStream(new FileInputStream(file))) {
                            responseData.setResponseBody(InputStreamUtil.getBytes(contentStream));
                        } catch (final Exception e) {
                            logger.warn("I/O Exception.", e);
                            responseData.setHttpStatusCode(Constants.SERVER_ERROR_STATUS_CODE);
                        }
                    } else {
                        responseData.setResponseBody(file, false);
                    }
                }
            } else {
                // Forbidden
                responseData.setHttpStatusCode(Constants.FORBIDDEN_STATUS_CODE);
                responseData.setMimeType(APPLICATION_OCTET_STREAM);
            }
        } else if (file.isDirectory()) {
            final Set<RequestData> requestDataSet = new HashSet<>();
            if (includeContent) {
                final File[] files = file.listFiles();
                if (files != null) {
                    for (final File f : files) {
                        final String chileUri = f.toURI().toASCIIString();
                        requestDataSet.add(RequestDataBuilder.newRequestData().get().url(chileUri).build());
                    }
                }
            }
            throw new ChildUrlsException(requestDataSet, this.getClass().getName() + "#getResponseData");
        } else {
            responseData.setHttpStatusCode(Constants.NOT_FOUND_STATUS_CODE);
            responseData.setCharSet(charset);
            responseData.setContentLength(0);
        }
    } catch (final CrawlerSystemException e) {
        CloseableUtil.closeQuietly(responseData);
        throw e;
    } catch (final Exception e) {
        CloseableUtil.closeQuietly(responseData);
        throw new CrawlingAccessException("Could not access " + uri, e);
    }
    return responseData;
}
Also used : FileOwnerAttributeView(java.nio.file.attribute.FileOwnerAttributeView) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) BufferedInputStream(java.io.BufferedInputStream) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MaxLengthExceededException(org.codelibs.fess.crawler.exception.MaxLengthExceededException) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) AbstractCrawlerClient(org.codelibs.fess.crawler.client.AbstractCrawlerClient) HashSet(java.util.HashSet) UserPrincipal(java.nio.file.attribute.UserPrincipal) URI(java.net.URI) ContentLengthHelper(org.codelibs.fess.crawler.helper.ContentLengthHelper) MimeTypeHelper(org.codelibs.fess.crawler.helper.MimeTypeHelper) InputStreamUtil(org.codelibs.core.io.InputStreamUtil) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) Logger(org.slf4j.Logger) Files(java.nio.file.Files) Resource(javax.annotation.Resource) StringUtil(org.codelibs.core.lang.StringUtil) Set(java.util.Set) FileInputStream(java.io.FileInputStream) FileOwnerAttributeView(java.nio.file.attribute.FileOwnerAttributeView) CrawlerContainer(org.codelibs.fess.crawler.container.CrawlerContainer) File(java.io.File) CloseableUtil(org.codelibs.core.io.CloseableUtil) Constants(org.codelibs.fess.crawler.Constants) URLEncoder(java.net.URLEncoder) RequestData(org.codelibs.fess.crawler.entity.RequestData) AccessTimeoutTarget(org.codelibs.fess.crawler.client.AccessTimeoutTarget) TimeoutManager(org.codelibs.core.timer.TimeoutManager) TimeoutTask(org.codelibs.core.timer.TimeoutTask) ChildUrlsException(org.codelibs.fess.crawler.exception.ChildUrlsException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequestDataBuilder(org.codelibs.fess.crawler.builder.RequestDataBuilder) InputStream(java.io.InputStream) ResponseData(org.codelibs.fess.crawler.entity.ResponseData) ChildUrlsException(org.codelibs.fess.crawler.exception.ChildUrlsException) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) MaxLengthExceededException(org.codelibs.fess.crawler.exception.MaxLengthExceededException) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) MimeTypeHelper(org.codelibs.fess.crawler.helper.MimeTypeHelper) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ResponseData(org.codelibs.fess.crawler.entity.ResponseData) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) UserPrincipal(java.nio.file.attribute.UserPrincipal) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) URISyntaxException(java.net.URISyntaxException) MaxLengthExceededException(org.codelibs.fess.crawler.exception.MaxLengthExceededException) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) ChildUrlsException(org.codelibs.fess.crawler.exception.ChildUrlsException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Date(java.util.Date) FileInputStream(java.io.FileInputStream) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView) BufferedInputStream(java.io.BufferedInputStream) RequestData(org.codelibs.fess.crawler.entity.RequestData) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) File(java.io.File) HashSet(java.util.HashSet)

Example 50 with Files

use of java.nio.file.Files in project component-runtime by Talend.

the class BaseSpark method start.

protected Instances start() {
    // prepare needed files on the file system (this sucks but is needed....)
    final Version version = Version.find(sparkVersion);
    final File sparkHome = buildSparkHome(version);
    LOGGER.info("Copied spark libraries in " + sparkHome);
    String masterHost;
    try {
        masterHost = InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        masterHost = "localhost";
    }
    final int masterPort = newPort();
    final int webMasterPort = newPort();
    final Collection<Runnable> closingTasks = new ArrayList<>();
    final ClusterConfig localConfig = new ClusterConfig(masterHost, masterPort, webMasterPort, sparkHome, closingTasks, version);
    config.set(localConfig);
    closingTasks.add(config::remove);
    final String host = masterHost;
    Throwable exception = null;
    try {
        final SparkProcessMonitor master = new SparkProcessMonitor(localConfig, "spark-master-monitor", () -> isOpen(host, masterPort), "org.apache.spark.deploy.master.Master", "--host", masterHost, "--port", Integer.toString(masterPort), "--webui-port", Integer.toString(webMasterPort));
        final Thread masterHook = new Thread(master::close);
        Runtime.getRuntime().addShutdownHook(masterHook);
        closingTasks.add(() -> Runtime.getRuntime().removeShutdownHook(masterHook));
        closingTasks.add(master::close);
        master.start();
        assertTrue("master didn't start", master.isStarted());
        LOGGER.info("Started Master on " + getSparkMaster());
        // todo: enhance it if using slaves > 1, we need to lock all ports together
        final int firstSlavePort = newPort();
        final List<SparkProcessMonitor> slaves = IntStream.range(0, this.slaves).mapToObj(i -> {
            final int slavePort = firstSlavePort + 1 + (2 * i);
            return new SparkProcessMonitor(localConfig, "spark-slave-" + i + "-monitor", () -> isOpen(host, slavePort), "org.apache.spark.deploy.worker.Worker", "--host", host, "--port", Integer.toString(slavePort), "--webui-port", Integer.toString(slavePort + 1), getSparkMaster());
        }).collect(toList());
        slaves.stream().peek(s -> closingTasks.add(s::close)).map(m -> new Thread(m::close)).forEach(t -> {
            Runtime.getRuntime().addShutdownHook(t);
            closingTasks.add(() -> Runtime.getRuntime().removeShutdownHook(t));
        });
        slaves.forEach(SparkProcessMonitor::start);
        if (slaves.stream().anyMatch(m -> !m.isStarted())) {
            fail("Some slave(s) didn't start");
        }
    } catch (final Throwable error) {
        exception = error;
    }
    return new Instances(() -> closingTasks.forEach(r -> {
        try {
            r.run();
        } catch (final RuntimeException re) {
            LOGGER.warn(re.getMessage(), re);
        }
    }), false, exception);
}
Also used : AcceptScopesStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.AcceptScopesStrategy) URL(java.net.URL) MavenResolutionStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.MavenResolutionStrategy) Optional.of(java.util.Optional.of) LoggerFactory(org.slf4j.LoggerFactory) SparkClusterRule(org.talend.sdk.component.runtime.testing.spark.SparkClusterRule) BooleanSupplier(java.util.function.BooleanSupplier) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) Maven(org.jboss.shrinkwrap.resolver.api.maven.Maven) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Thread.sleep(java.lang.Thread.sleep) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) Collectors.toSet(java.util.stream.Collectors.toSet) ScopeType(org.jboss.shrinkwrap.resolver.api.maven.ScopeType) Predicate(java.util.function.Predicate) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ClassLoaders(org.apache.ziplock.ClassLoaders) Stream(java.util.stream.Stream) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) Optional(java.util.Optional) IntStream(java.util.stream.IntStream) Socket(java.net.Socket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Getter(lombok.Getter) HashMap(java.util.HashMap) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) UrlSet(org.apache.xbean.finder.UrlSet) JarEntry(java.util.jar.JarEntry) JarOutputStream(java.util.jar.JarOutputStream) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) JarLocation.jarLocation(org.apache.ziplock.JarLocation.jarLocation) AllArgsConstructor(lombok.AllArgsConstructor) InputStream(java.io.InputStream) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) Stream(java.util.stream.Stream) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) IntStream(java.util.stream.IntStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JarOutputStream(java.util.jar.JarOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) InputStream(java.io.InputStream) File(java.io.File)

Aggregations

Files (java.nio.file.Files)243 IOException (java.io.IOException)210 Path (java.nio.file.Path)196 List (java.util.List)176 Collectors (java.util.stream.Collectors)154 Paths (java.nio.file.Paths)133 File (java.io.File)127 ArrayList (java.util.ArrayList)117 Map (java.util.Map)109 Set (java.util.Set)96 Collections (java.util.Collections)89 Arrays (java.util.Arrays)81 Stream (java.util.stream.Stream)77 HashMap (java.util.HashMap)74 HashSet (java.util.HashSet)58 InputStream (java.io.InputStream)55 Collection (java.util.Collection)55 Logger (org.slf4j.Logger)54 Pattern (java.util.regex.Pattern)53 Optional (java.util.Optional)51