Search in sources :

Example 41 with Files

use of java.nio.file.Files in project irida by phac-nml.

the class RESTSampleSequenceFilesController method readSequenceFileForSequencingObject.

/**
 * Read a single {@link SequenceFile} for a given {@link Sample} and
 * {@link SequencingObject}
 *
 * @param sampleId
 *            ID of the {@link Sample}
 * @param objectType
 *            type of {@link SequencingObject}
 * @param objectId
 *            id of the {@link SequencingObject}
 * @param fileId
 *            ID of the {@link SequenceFile} to read
 * @return a {@link SequenceFile}
 */
@RequestMapping(value = "/api/samples/{sampleId}/{objectType}/{objectId}/files/{fileId}", method = RequestMethod.GET)
public ModelMap readSequenceFileForSequencingObject(@PathVariable Long sampleId, @PathVariable String objectType, @PathVariable Long objectId, @PathVariable Long fileId) {
    ModelMap modelMap = new ModelMap();
    Sample sample = sampleService.read(sampleId);
    SequencingObject readSequenceFilePairForSample = sequencingObjectService.readSequencingObjectForSample(sample, objectId);
    Optional<SequenceFile> findFirst = readSequenceFilePairForSample.getFiles().stream().filter(f -> f.getId().equals(fileId)).findFirst();
    if (!findFirst.isPresent()) {
        throw new EntityNotFoundException("File with id " + fileId + " is not associated with this sequencing object");
    }
    SequenceFile file = findFirst.get();
    file.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).getSampleSequenceFiles(sampleId)).withRel(REL_SAMPLE_SEQUENCE_FILES));
    file.add(linkTo(methodOn(RESTProjectSamplesController.class).getSample(sampleId)).withRel(REL_SAMPLE));
    file.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).readSequencingObject(sampleId, objectType, objectId)).withRel(REL_SEQ_OBJECT));
    file.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).readQCForSequenceFile(sampleId, objectType, objectId, fileId)).withRel(REL_SEQ_QC));
    file.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).readSequenceFileForSequencingObject(sampleId, objectType, objectId, fileId)).withSelfRel());
    modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, file);
    return modelMap;
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RootResource(ca.corefacility.bioinformatics.irida.web.assembler.resource.RootResource) LoggerFactory(org.slf4j.LoggerFactory) AnalysisFastQC(ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisFastQC) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) ControllerLinkBuilder.methodOn(org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn) Controller(org.springframework.stereotype.Controller) RequestPart(org.springframework.web.bind.annotation.RequestPart) RESTAnalysisSubmissionController(ca.corefacility.bioinformatics.irida.web.controller.api.RESTAnalysisSubmissionController) SequencingObject(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject) ModelMap(org.springframework.ui.ModelMap) SequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile) SequencingRun(ca.corefacility.bioinformatics.irida.model.run.SequencingRun) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) ControllerLinkBuilder.linkTo(org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo) HttpHeaders(com.google.common.net.HttpHeaders) Objects(com.google.common.base.Objects) Path(java.nio.file.Path) ResourceCollection(ca.corefacility.bioinformatics.irida.web.assembler.resource.ResourceCollection) BiMap(com.google.common.collect.BiMap) Link(org.springframework.hateoas.Link) Logger(org.slf4j.Logger) AnalysisSubmission(ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission) SequencingObjectService(ca.corefacility.bioinformatics.irida.service.SequencingObjectService) Files(java.nio.file.Files) RESTProjectSamplesController(ca.corefacility.bioinformatics.irida.web.controller.api.projects.RESTProjectSamplesController) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) SequenceFilePair(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFilePair) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) IOException(java.io.IOException) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) SampleSequencingObjectJoin(ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin) SequencingRunService(ca.corefacility.bioinformatics.irida.service.SequencingRunService) RESTGenericController(ca.corefacility.bioinformatics.irida.web.controller.api.RESTGenericController) HttpStatus(org.springframework.http.HttpStatus) SequenceFileResource(ca.corefacility.bioinformatics.irida.web.assembler.resource.sequencefile.SequenceFileResource) Optional(java.util.Optional) MultipartFile(org.springframework.web.multipart.MultipartFile) SampleService(ca.corefacility.bioinformatics.irida.service.sample.SampleService) SingleEndSequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile) AnalysisService(ca.corefacility.bioinformatics.irida.service.AnalysisService) SequencingObject(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject) SequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile) SingleEndSequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) ModelMap(org.springframework.ui.ModelMap) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 42 with Files

use of java.nio.file.Files in project irida by phac-nml.

the class DefaultFileProcessingChain method getSettledSequencingObject.

/**
 * Checks the {@link SequenceFile}s for the given {@link SequencingObject}
 * to see if it's files are in the place they should be. Since there's lots
 * of saves going on during the {@link FileProcessingChain} the transaction
 * might not be complete in the time the file is first read.
 *
 * @param sequencingObjectId
 *            the id of the {@link SequencingObject} to check
 * @return the settled {@link SequencingObject}
 * @throws FileProcessorTimeoutException
 *             if the files don't settle in the configured timeout
 */
private SequencingObject getSettledSequencingObject(Long sequencingObjectId) throws FileProcessorTimeoutException {
    boolean filesNotSettled = true;
    Integer waiting = 0;
    SequencingObject sequencingObject;
    do {
        if (waiting > timeout) {
            throw new FileProcessorTimeoutException("Waiting for longer than " + sleepDuration * timeout + "ms, bailing out.  File id " + sequencingObjectId);
        }
        waiting++;
        try {
            Thread.sleep(sleepDuration);
        } catch (InterruptedException e) {
        }
        sequencingObject = sequencingObjectRepository.findOne(sequencingObjectId);
        Set<SequenceFile> files = sequencingObject.getFiles();
        filesNotSettled = files.stream().anyMatch(f -> {
            return !Files.exists(f.getFile());
        });
    } while (filesNotSettled);
    return sequencingObject;
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) Files(java.nio.file.Files) FileProcessorException(ca.corefacility.bioinformatics.irida.processing.FileProcessorException) SequencingObjectRepository(ca.corefacility.bioinformatics.irida.repositories.sequencefile.SequencingObjectRepository) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) SequencingObject(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject) SequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile) QCEntryRepository(ca.corefacility.bioinformatics.irida.repositories.sample.QCEntryRepository) ArrayList(java.util.ArrayList) FileProcessor(ca.corefacility.bioinformatics.irida.processing.FileProcessor) FileProcessorErrorQCEntry(ca.corefacility.bioinformatics.irida.model.sample.FileProcessorErrorQCEntry) List(java.util.List) FileProcessorTimeoutException(ca.corefacility.bioinformatics.irida.exceptions.FileProcessorTimeoutException) FileProcessingChain(ca.corefacility.bioinformatics.irida.processing.FileProcessingChain) FileProcessorTimeoutException(ca.corefacility.bioinformatics.irida.exceptions.FileProcessorTimeoutException) SequencingObject(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject) SequenceFile(ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile)

Example 43 with Files

use of java.nio.file.Files in project LanternServer by LanternPowered.

the class LanternClassLoader method load.

private static LanternClassLoader load() throws IOException {
    ClassLoader.registerAsParallelCapable();
    // Get the bootstrap class loader
    final ClassLoader classLoader = LanternClassLoader.class.getClassLoader();
    // Load the dependencies files
    final List<Dependencies> dependenciesEntries = new ArrayList<>();
    // Load the dependencies file within the jar, not available in the IDE
    final URL dependenciesURL = classLoader.getResource("dependencies.json");
    if (dependenciesURL != null) {
        try {
            dependenciesEntries.add(DependenciesParser.read(new BufferedReader(new InputStreamReader(dependenciesURL.openStream()))));
        } catch (ParseException e) {
            throw new IllegalStateException("Failed to parse the dependencies.json file within the jar.", e);
        }
    }
    // Try to generate or load the dependencies file
    final Path dependenciesFile = Paths.get("dependencies.json");
    if (!Files.exists(dependenciesFile)) {
        try (BufferedWriter writer = Files.newBufferedWriter(dependenciesFile)) {
            writer.write("{\n    \"repositories\": [\n    ],\n    \"dependencies\": [\n    ]\n}");
        }
    } else {
        try {
            dependenciesEntries.add(DependenciesParser.read(Files.newBufferedReader(dependenciesFile)));
        } catch (ParseException e) {
            throw new IllegalStateException("Failed to parse the dependencies.json file within the root directory.", e);
        }
    }
    // Merge the dependencies files
    final List<URL> repositoryUrls = new ArrayList<>();
    final Map<String, Dependency> dependencyMap = new HashMap<>();
    for (Dependencies dependencies : dependenciesEntries) {
        dependencies.getRepositories().stream().map(Repository::getUrl).filter(e -> !repositoryUrls.contains(e)).forEach(repositoryUrls::add);
        for (Dependency dependency : dependencies.getDependencies()) {
            dependencyMap.put(dependency.getGroup() + ':' + dependency.getName(), dependency);
        }
    }
    String localRepoPath = System.getProperty("maven.repo.local");
    if (localRepoPath == null) {
        final String mavenHome = System.getenv("M2_HOME");
        if (mavenHome != null) {
            final Path settingsPath = Paths.get(mavenHome, "conf", "setting.xml");
            if (Files.exists(settingsPath)) {
                try {
                    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    final Document document = documentBuilder.parse(settingsPath.toFile());
                    // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
                    document.getDocumentElement().normalize();
                    final Node node = document.getElementsByTagName("localRepository").item(0);
                    if (node != null) {
                        localRepoPath = node.getTextContent();
                    }
                } catch (ParserConfigurationException | SAXException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
    if (localRepoPath == null) {
        localRepoPath = "~/.m/repository";
    }
    localRepoPath = localRepoPath.trim();
    if (localRepoPath.charAt(0) == '~') {
        localRepoPath = System.getProperty("user.home") + '/' + localRepoPath.substring(2);
    }
    // Try to find the local maven repository
    repositoryUrls.add(0, new File(localRepoPath).toURL());
    final List<FileRepository> repositories = new ArrayList<>();
    for (URL repositoryUrl : repositoryUrls) {
        if (repositoryUrl.getProtocol().equals("file")) {
            final File baseFile = new File(repositoryUrl.getFile());
            repositories.add(path -> {
                final File file = new File(baseFile, path);
                try {
                    return file.exists() ? file.toURL().openStream() : null;
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
            });
        } else {
            String repositoryUrlBase = repositoryUrl.toString();
            if (repositoryUrlBase.endsWith("/")) {
                repositoryUrlBase = repositoryUrlBase.substring(0, repositoryUrlBase.length() - 1);
            }
            final String urlBase = repositoryUrlBase;
            repositories.add(path -> {
                try {
                    final URL url = new URL(urlBase + "/" + path);
                    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    final String encoding = connection.getHeaderField("Content-Encoding");
                    InputStream is = connection.getInputStream();
                    if (encoding != null) {
                        if (encoding.equals("gzip")) {
                            is = new GZIPInputStream(is);
                        } else {
                            throw new IllegalStateException("Unsupported encoding: " + encoding);
                        }
                    }
                    return is;
                } catch (IOException e) {
                    return null;
                }
            });
        }
    }
    // If we are outside development mode, the server will be packed
    // into a jar. We will also need to make sure that this one gets
    // added in this case
    final CodeSource source = LanternClassLoader.class.getProtectionDomain().getCodeSource();
    final URL location = source == null ? null : source.getLocation();
    // Setup the environment variable
    final String env = System.getProperty(ENVIRONMENT);
    final Environment environment;
    if (env != null) {
        try {
            environment = Environment.valueOf(env.toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Invalid environment type: " + env);
        }
    } else {
        environment = location == null || new File(location.getFile()).isDirectory() ? Environment.DEVELOPMENT : Environment.PRODUCTION;
        System.setProperty(ENVIRONMENT, environment.toString().toLowerCase());
    }
    Environment.set(environment);
    // Scan the jar for library jars
    if (location != null) {
        repositories.add(path -> classLoader.getResourceAsStream("dependencies/" + path));
    }
    final List<URL> libraryUrls = new ArrayList<>();
    // Download or load all the dependencies
    final Path internalLibrariesPath = Paths.get(".cached-dependencies");
    for (Dependency dependency : dependencyMap.values()) {
        final String group = dependency.getGroup();
        final String name = dependency.getName();
        final String version = dependency.getVersion();
        final Path target = internalLibrariesPath.resolve(String.format("%s/%s/%s/%s-%s.jar", group.replace('.', '/'), name, version, name, version));
        libraryUrls.add(target.toUri().toURL());
        final String id = String.format("%s:%s:%s", dependency.getGroup(), dependency.getName(), dependency.getVersion());
        if (Files.exists(target)) {
            System.out.printf("Loaded: \"%s\"\n", id);
            continue;
        }
        InputStream is = null;
        for (FileRepository repository : repositories) {
            is = repository.get(dependency);
            if (is != null) {
                break;
            }
        }
        if (is == null) {
            throw new IllegalStateException("The following dependency could not be found: " + id);
        }
        final Path parent = target.getParent();
        if (!Files.exists(parent)) {
            Files.createDirectories(parent);
        }
        System.out.printf("Downloading \"%s\"\n", id);
        try (ReadableByteChannel i = Channels.newChannel(is);
            FileOutputStream o = new FileOutputStream(target.toFile())) {
            o.getChannel().transferFrom(i, 0, Long.MAX_VALUE);
        }
    }
    // All the folders are from lantern or sponge,
    // in development mode are all the libraries on
    // the classpath, so there is no need to add them
    // to the library classloader
    final List<URL> urls = new ArrayList<>();
    final String classPath = System.getProperty("java.class.path");
    final String[] libraries = classPath.split(File.pathSeparator);
    for (String library : libraries) {
        try {
            final URL url = Paths.get(library).toUri().toURL();
            if (!library.endsWith(".jar") || url.equals(location)) {
                urls.add(url);
            }
        } catch (MalformedURLException ignored) {
            System.out.println("Invalid library found in the class path: " + library);
        }
    }
    // The server class loader will load lantern, the api and all the plugins
    final LanternClassLoader serverClassLoader = new LanternClassLoader(urls.toArray(new URL[urls.size()]), libraryUrls.toArray(new URL[libraryUrls.size()]), classLoader);
    Thread.currentThread().setContextClassLoader(serverClassLoader);
    return serverClassLoader;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Manifest(java.util.jar.Manifest) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) Enumeration(java.util.Enumeration) URL(java.net.URL) JarFile(java.util.jar.JarFile) Repository(org.lanternpowered.launch.dependencies.Repository) URLClassLoader(java.net.URLClassLoader) Document(org.w3c.dom.Document) Map(java.util.Map) Method(java.lang.reflect.Method) Path(java.nio.file.Path) Dependency(org.lanternpowered.launch.dependencies.Dependency) LanternServer(org.lanternpowered.server.LanternServer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) DependenciesParser(org.lanternpowered.launch.dependencies.DependenciesParser) SAXException(org.xml.sax.SAXException) Optional(java.util.Optional) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HashMap(java.util.HashMap) CodeSigner(java.security.CodeSigner) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClassTransformer(org.lanternpowered.launch.transformer.ClassTransformer) ParseException(org.json.simple.parser.ParseException) Objects.requireNonNull(java.util.Objects.requireNonNull) Node(org.w3c.dom.Node) Exclusion(org.lanternpowered.launch.transformer.Exclusion) NoSuchElementException(java.util.NoSuchElementException) ReadableByteChannel(java.nio.channels.ReadableByteChannel) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) Channels(java.nio.channels.Channels) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Dependencies(org.lanternpowered.launch.dependencies.Dependencies) File(java.io.File) Consumer(java.util.function.Consumer) Element(org.w3c.dom.Element) Paths(java.nio.file.Paths) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) BufferedReader(java.io.BufferedReader) CodeSource(java.security.CodeSource) Collections(java.util.Collections) InputStream(java.io.InputStream) ReadableByteChannel(java.nio.channels.ReadableByteChannel) MalformedURLException(java.net.MalformedURLException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Node(org.w3c.dom.Node) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter) SAXException(org.xml.sax.SAXException) GZIPInputStream(java.util.zip.GZIPInputStream) HttpURLConnection(java.net.HttpURLConnection) URLClassLoader(java.net.URLClassLoader) Dependencies(org.lanternpowered.launch.dependencies.Dependencies) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Path(java.nio.file.Path) InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) Dependency(org.lanternpowered.launch.dependencies.Dependency) IOException(java.io.IOException) CodeSource(java.security.CodeSource) Repository(org.lanternpowered.launch.dependencies.Repository) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) ParseException(org.json.simple.parser.ParseException) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 44 with Files

use of java.nio.file.Files in project structr by structr.

the class JavaParserModule method addJarsToIndex.

/**
 * Add compilation units of all jar files found in the given folder to the index.
 *
 * @param folderPath
 */
public void addJarsToIndex(final String folderPath) {
    logger.info("Starting adding jar files in " + folderPath);
    final CombinedTypeSolver typeSolver = new CombinedTypeSolver();
    typeSolver.add(new ReflectionTypeSolver());
    final AtomicLong count = new AtomicLong(0);
    try {
        Files.newDirectoryStream(Paths.get(folderPath), path -> path.toString().endsWith(".jar")).forEach((file) -> {
            try {
                typeSolver.add(new JarTypeSolver(new FileInputStream(file.toFile())));
                count.addAndGet(1L);
            } catch (IOException ex) {
            }
        });
    } catch (IOException ex) {
    }
    logger.info("Added " + count.toString() + " jar files to the type solver");
    typeSolver.add(structrTypeSolver);
    facade = JavaParserFacade.get(typeSolver);
    logger.info("Done with adding jar files in " + folderPath);
}
Also used : JsonObject(com.google.gson.JsonObject) Package(org.structr.javaparser.entity.Package) XPathExpressionException(javax.xml.xpath.XPathExpressionException) UnsolvedSymbolException(com.github.javaparser.symbolsolver.javaparsermodel.UnsolvedSymbolException) LoggerFactory(org.slf4j.LoggerFactory) SecurityContext(org.structr.common.SecurityContext) StringUtils(org.apache.commons.lang3.StringUtils) ConstructorDeclaration(com.github.javaparser.ast.body.ConstructorDeclaration) Actions(org.structr.schema.action.Actions) FrameworkException(org.structr.common.error.FrameworkException) App(org.structr.core.app.App) NodeWithSimpleName(com.github.javaparser.ast.nodeTypes.NodeWithSimpleName) Type(com.github.javaparser.ast.type.Type) Document(org.w3c.dom.Document) Map(java.util.Map) CompilationUnit(com.github.javaparser.ast.CompilationUnit) JavaInterface(org.structr.javaparser.entity.JavaInterface) NodeList(com.github.javaparser.ast.NodeList) Folder(org.structr.web.entity.Folder) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) Set(java.util.Set) GraphObject(org.structr.core.GraphObject) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) Functions(org.structr.core.function.Functions) JsonArray(com.google.gson.JsonArray) List(java.util.List) StructrModule(org.structr.module.StructrModule) JarTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver) SAXException(org.xml.sax.SAXException) LicenseManager(org.structr.api.service.LicenseManager) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) QName(javax.xml.namespace.QName) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeWithOptionalBlockStmt(com.github.javaparser.ast.nodeTypes.NodeWithOptionalBlockStmt) StructrApp(org.structr.core.app.StructrApp) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) Method(org.structr.javaparser.entity.Method) PackageDeclaration(com.github.javaparser.ast.PackageDeclaration) XPath(javax.xml.xpath.XPath) XPathConstants(javax.xml.xpath.XPathConstants) Parameter(com.github.javaparser.ast.body.Parameter) HashMap(java.util.HashMap) CombinedTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver) ArrayList(java.util.ArrayList) PropertyMap(org.structr.core.property.PropertyMap) File(org.structr.web.entity.File) JavaClass(org.structr.javaparser.entity.JavaClass) JsonPrimitive(com.google.gson.JsonPrimitive) ClassOrInterface(org.structr.javaparser.entity.ClassOrInterface) LinkedHashSet(java.util.LinkedHashSet) InputSource(org.xml.sax.InputSource) Logger(org.slf4j.Logger) NodeWithModifiers(com.github.javaparser.ast.nodeTypes.NodeWithModifiers) Files(java.nio.file.Files) AbstractSchemaNode(org.structr.core.entity.AbstractSchemaNode) BodyDeclaration(com.github.javaparser.ast.body.BodyDeclaration) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CallableDeclaration(com.github.javaparser.ast.body.CallableDeclaration) AddJarsToIndexFunction(org.structr.javaparser.entity.AddJarsToIndexFunction) AtomicLong(java.util.concurrent.atomic.AtomicLong) XPathFactory(javax.xml.xpath.XPathFactory) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) StringReader(java.io.StringReader) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) Paths(java.nio.file.Paths) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) Module(org.structr.javaparser.entity.Module) JavaParser(com.github.javaparser.JavaParser) InputStream(java.io.InputStream) AtomicLong(java.util.concurrent.atomic.AtomicLong) JarTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver) IOException(java.io.IOException) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) CombinedTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver) FileInputStream(java.io.FileInputStream)

Example 45 with Files

use of java.nio.file.Files in project intellij by bazelbuild.

the class JarCache method refresh.

private void refresh(@Nullable BlazeContext context, boolean removeMissingFiles) {
    if (!enabled || traits == null) {
        return;
    }
    // Ensure the cache dir exists
    if (!cacheDir.exists()) {
        if (!cacheDir.mkdirs()) {
            logger.error("Could not create jar cache directory");
            return;
        }
    }
    FileCacheSynchronizer synchronizer = new FileCacheSynchronizer(traits);
    if (!synchronizer.synchronize(context, removeMissingFiles)) {
        logger.warn("Jar Cache synchronization didn't complete");
    }
    if (context != null) {
        try {
            Collection<File> finalCacheFiles = traits.enumerateCacheFiles();
            ImmutableMap<File, Long> cacheFileSizes = FileSizeScanner.readFilesizes(finalCacheFiles);
            Long total = cacheFileSizes.values().stream().mapToLong(x -> x).sum();
            context.output(PrintOutput.log(String.format("Total Jar Cache size: %d kB (%d files)", total / 1024, finalCacheFiles.size())));
        } catch (Exception e) {
            logger.warn("Could not determine cache size", e);
        }
    }
}
Also used : SyncMode(com.google.idea.blaze.base.sync.BlazeSyncParams.SyncMode) BlazeContext(com.google.idea.blaze.base.scope.BlazeContext) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) BlazeLibrary(com.google.idea.blaze.base.model.BlazeLibrary) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) FileCache(com.google.idea.blaze.base.filecache.FileCache) BlazeSyncParams(com.google.idea.blaze.base.sync.BlazeSyncParams) BlazeJarLibrary(com.google.idea.blaze.java.sync.model.BlazeJarLibrary) BlazeProjectData(com.google.idea.blaze.base.model.BlazeProjectData) Future(java.util.concurrent.Future) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) BlazeDataStorage(com.google.idea.blaze.base.sync.data.BlazeDataStorage) Map(java.util.Map) Project(com.intellij.openapi.project.Project) BlazeJavaUserSettings(com.google.idea.blaze.java.settings.BlazeJavaUserSettings) FileUtil(com.intellij.openapi.util.io.FileUtil) FileSizeScanner(com.google.idea.blaze.base.io.FileSizeScanner) Logger(com.intellij.openapi.diagnostic.Logger) Nullable(javax.annotation.Nullable) BiMap(com.google.common.collect.BiMap) ArtifactLocation(com.google.idea.blaze.base.ideinfo.ArtifactLocation) ImmutableMap(com.google.common.collect.ImmutableMap) Files(java.nio.file.Files) BlazeLibraryCollector(com.google.idea.blaze.base.sync.libraries.BlazeLibraryCollector) Collection(java.util.Collection) BlazeImportSettingsManager(com.google.idea.blaze.base.settings.BlazeImportSettingsManager) IOException(java.io.IOException) PrintOutput(com.google.idea.blaze.base.scope.output.PrintOutput) Collectors(java.util.stream.Collectors) File(java.io.File) BlazeImportSettings(com.google.idea.blaze.base.settings.BlazeImportSettings) HashBiMap(com.google.common.collect.HashBiMap) List(java.util.List) ServiceManager(com.intellij.openapi.components.ServiceManager) FileCacheSynchronizerTraits(com.google.idea.blaze.base.filecache.FileCacheSynchronizerTraits) Paths(java.nio.file.Paths) ProjectViewSet(com.google.idea.blaze.base.projectview.ProjectViewSet) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Preconditions(com.google.common.base.Preconditions) ArtifactLocationDecoder(com.google.idea.blaze.base.sync.workspace.ArtifactLocationDecoder) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) FileCacheSynchronizer(com.google.idea.blaze.base.filecache.FileCacheSynchronizer) FileCacheSynchronizer(com.google.idea.blaze.base.filecache.FileCacheSynchronizer) File(java.io.File) IOException(java.io.IOException)

Aggregations

Files (java.nio.file.Files)247 IOException (java.io.IOException)213 Path (java.nio.file.Path)199 List (java.util.List)177 Collectors (java.util.stream.Collectors)157 Paths (java.nio.file.Paths)135 File (java.io.File)130 ArrayList (java.util.ArrayList)117 Map (java.util.Map)111 Set (java.util.Set)97 Collections (java.util.Collections)89 Arrays (java.util.Arrays)81 Stream (java.util.stream.Stream)78 HashMap (java.util.HashMap)75 HashSet (java.util.HashSet)58 InputStream (java.io.InputStream)56 Collection (java.util.Collection)55 Logger (org.slf4j.Logger)54 Pattern (java.util.regex.Pattern)53 Optional (java.util.Optional)51