Search in sources :

Example 6 with StopWatch

use of org.apache.commons.lang.time.StopWatch in project archiva by apache.

the class JcrRepositorySessionFactory method initialize.

public void initialize() {
    // skip initialisation if not jcr
    if (repositorySessionFactoryBean != null && !StringUtils.equals(repositorySessionFactoryBean.getId(), "jcr")) {
        return;
    }
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    metadataFacetFactories = applicationContext.getBeansOfType(MetadataFacetFactory.class);
    // olamy with spring the "id" is now "metadataFacetFactory#hint"
    // whereas was only hint with plexus so let remove  metadataFacetFactory#
    Map<String, MetadataFacetFactory> cleanedMetadataFacetFactories = new HashMap<>(metadataFacetFactories.size());
    for (Map.Entry<String, MetadataFacetFactory> entry : metadataFacetFactories.entrySet()) {
        cleanedMetadataFacetFactories.put(StringUtils.substringAfterLast(entry.getKey(), "#"), entry.getValue());
    }
    metadataFacetFactories = cleanedMetadataFacetFactories;
    JcrMetadataRepository metadataRepository = null;
    try {
        repositoryFactory = new RepositoryFactory();
        // FIXME this need to be configurable
        Path directoryPath = Paths.get(System.getProperty("appserver.base"), "data/jcr");
        repositoryFactory.setRepositoryPath(directoryPath);
        try {
            repository = repositoryFactory.createRepository();
        } catch (InvalidFileStoreVersionException | IOException e) {
            logger.error("Repository creation failed {}", e.getMessage());
            throw new RuntimeException("Fatal error. Could not create metadata repository.");
        }
        metadataRepository = new JcrMetadataRepository(metadataFacetFactories, repository);
        JcrMetadataRepository.initialize(metadataRepository.getJcrSession());
    } catch (RepositoryException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (metadataRepository != null) {
            try {
                metadataRepository.close();
            } catch (MetadataRepositoryException e) {
                logger.error("Close of metadata repository failed {}", e.getMessage());
            }
        }
    }
    stopWatch.stop();
    logger.info("time to initialize JcrRepositorySessionFactory: {}", stopWatch.getTime());
}
Also used : Path(java.nio.file.Path) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) HashMap(java.util.HashMap) RepositoryException(javax.jcr.RepositoryException) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) IOException(java.io.IOException) StopWatch(org.apache.commons.lang.time.StopWatch) MetadataFacetFactory(org.apache.archiva.metadata.model.MetadataFacetFactory) InvalidFileStoreVersionException(org.apache.jackrabbit.oak.segment.file.InvalidFileStoreVersionException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with StopWatch

use of org.apache.commons.lang.time.StopWatch in project archiva by apache.

the class RepositoryFactory method createRepository.

public Repository createRepository() throws IOException, InvalidFileStoreVersionException {
    createExecutor();
    if (SEGMENT_FILE_TYPE == storeType) {
        fileStore = FileStoreBuilder.fileStoreBuilder(repositoryPath.toFile()).build();
        nodeStore = // 
        SegmentNodeStoreBuilders.builder(fileStore).withStatisticsProvider(// 
        StatisticsProvider.NOOP).build();
    } else if (IN_MEMORY_TYPE == storeType) {
        nodeStore = null;
    } else {
        throw new IllegalArgumentException("Store type " + storeType + " not recognized");
    }
    Oak oak = nodeStore == null ? new Oak() : new Oak(nodeStore);
    oak.with(new RepositoryInitializer() {

        @Override
        public void initialize(@Nonnull NodeBuilder root) {
            log.info("Creating index ");
            NodeBuilder lucene = IndexUtils.getOrCreateOakIndex(root).child("lucene");
            lucene.setProperty(JcrConstants.JCR_PRIMARYTYPE, "oak:QueryIndexDefinition", Type.NAME);
            lucene.setProperty("compatVersion", 2);
            lucene.setProperty("type", "lucene");
            // lucene.setProperty("async", "async");
            lucene.setProperty(INCLUDE_PROPERTY_TYPES, ImmutableSet.of("String"), Type.STRINGS);
            // lucene.setProperty("refresh",true);
            lucene.setProperty("async", ImmutableSet.of("async", "sync"), Type.STRINGS);
            NodeBuilder rules = lucene.child("indexRules").setProperty(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED, Type.NAME);
            rules.setProperty(":childOrder", // 
            ImmutableSet.of(// 
            "archiva:projectVersion", // 
            "archiva:artifact", // 
            "archiva:facet", // 
            "archiva:namespace", // 
            "archiva:project"), Type.STRINGS);
            NodeBuilder allProps = // 
            rules.child("archiva:projectVersion").child(// 
            "properties").setProperty(JcrConstants.JCR_PRIMARYTYPE, "nt:unstructured", // 
            Type.NAME).setProperty(":childOrder", ImmutableSet.of("allProps"), // 
            Type.STRINGS).setProperty("indexNodeName", // 
            true).child(// 
            "allProps").setProperty(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED, Type.NAME);
            allProps.setProperty("name", ".*");
            allProps.setProperty("isRegexp", true);
            allProps.setProperty("nodeScopeIndex", true);
            allProps.setProperty("index", true);
            allProps.setProperty("analyzed", true);
            // allProps.setProperty("propertyIndex",true);
            allProps = // 
            rules.child("archiva:artifact").child(// 
            "properties").setProperty(JcrConstants.JCR_PRIMARYTYPE, "nt:unstructured", // 
            Type.NAME).setProperty(":childOrder", ImmutableSet.of("allProps"), // 
            Type.STRINGS).setProperty("indexNodeName", true).child(// 
            "allProps").setProperty(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED, Type.NAME);
            allProps.setProperty("name", ".*");
            allProps.setProperty("isRegexp", true);
            allProps.setProperty("nodeScopeIndex", true);
            allProps.setProperty("index", true);
            allProps.setProperty("analyzed", true);
            allProps = // 
            rules.child("archiva:facet").child(// 
            "properties").setProperty(JcrConstants.JCR_PRIMARYTYPE, "nt:unstructured", // 
            Type.NAME).setProperty(":childOrder", ImmutableSet.of("allProps"), // 
            Type.STRINGS).setProperty("indexNodeName", // 
            true).child(// 
            "allProps").setProperty(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED, Type.NAME);
            allProps.setProperty("name", ".*");
            allProps.setProperty("isRegexp", true);
            allProps.setProperty("nodeScopeIndex", true);
            allProps.setProperty("index", true);
            allProps.setProperty("analyzed", true);
            allProps = // 
            rules.child("archiva:namespace").child(// 
            "properties").setProperty(JcrConstants.JCR_PRIMARYTYPE, "nt:unstructured", // 
            Type.NAME).setProperty(":childOrder", ImmutableSet.of("allProps"), // 
            Type.STRINGS).setProperty("indexNodeName", // 
            true).child(// 
            "allProps").setProperty(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED, Type.NAME);
            allProps.setProperty("name", ".*");
            allProps.setProperty("isRegexp", true);
            allProps.setProperty("nodeScopeIndex", true);
            allProps.setProperty("index", true);
            allProps.setProperty("analyzed", true);
            allProps = // 
            rules.child("archiva:project").child(// 
            "properties").setProperty(JcrConstants.JCR_PRIMARYTYPE, "nt:unstructured", // 
            Type.NAME).setProperty(":childOrder", ImmutableSet.of("allProps"), // 
            Type.STRINGS).setProperty("indexNodeName", // 
            true).child(// 
            "allProps").setProperty(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED, Type.NAME);
            allProps.setProperty("name", ".*");
            allProps.setProperty("isRegexp", true);
            allProps.setProperty("nodeScopeIndex", true);
            allProps.setProperty("index", true);
            allProps.setProperty("analyzed", true);
            log.info("Index: {} myIndex {}", lucene, lucene.getChildNode("myIndex"));
            log.info("myIndex {}", lucene.getChildNode("myIndex").getProperties());
        // IndexUtils.createIndexDefinition(  )
        }
    });
    StatisticsProvider statsProvider = StatisticsProvider.NOOP;
    int queueSize = Integer.getInteger("queueSize", 10000);
    Path indexDir = Files.createTempDirectory("archiva_index");
    log.info("Queue Index {}", indexDir.toString());
    IndexCopier indexCopier = new IndexCopier(executorService, indexDir.toFile(), true);
    NRTIndexFactory nrtIndexFactory = new NRTIndexFactory(indexCopier, statsProvider);
    MountInfoProvider mountInfoProvider = Mounts.defaultMountInfoProvider();
    IndexTracker tracker = new IndexTracker(new DefaultIndexReaderFactory(mountInfoProvider, indexCopier), nrtIndexFactory);
    DocumentQueue queue = new DocumentQueue(queueSize, tracker, executorService, statsProvider);
    LocalIndexObserver localIndexObserver = new LocalIndexObserver(queue, statsProvider);
    LuceneIndexProvider provider = new LuceneIndexProvider(tracker);
    // ExternalObserverBuilder builder = new ExternalObserverBuilder(queue, tracker, statsProvider,
    // executorService, queueSize);
    // Observer observer = builder.build();
    // builder.getBackgroundObserver();
    // 
    LuceneIndexEditorProvider editorProvider = new // 
    LuceneIndexEditorProvider(// 
    null, // 
    tracker, // 
    new ExtractedTextCache(0, 0), null, mountInfoProvider);
    editorProvider.setIndexingQueue(queue);
    log.info("Oak: {} with nodeStore {}", oak, nodeStore);
    Jcr jcr = // 
    new Jcr(oak).with(editorProvider).with(// 
    (Observer) provider).with(localIndexObserver).with(// 
    (QueryIndexProvider) provider);
    // .withAsyncIndexing( "async", 5 );
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Repository r = jcr.createRepository();
    stopWatch.stop();
    log.info("time to create jcr repository: {} ms", stopWatch.getTime());
    // }
    return r;
}
Also used : Path(java.nio.file.Path) IndexTracker(org.apache.jackrabbit.oak.plugins.index.lucene.IndexTracker) DocumentQueue(org.apache.jackrabbit.oak.plugins.index.lucene.hybrid.DocumentQueue) NodeBuilder(org.apache.jackrabbit.oak.spi.state.NodeBuilder) IndexCopier(org.apache.jackrabbit.oak.plugins.index.lucene.IndexCopier) StatisticsProvider(org.apache.jackrabbit.oak.stats.StatisticsProvider) StopWatch(org.apache.commons.lang.time.StopWatch) ExtractedTextCache(org.apache.jackrabbit.oak.plugins.index.lucene.ExtractedTextCache) Repository(javax.jcr.Repository) LuceneIndexEditorProvider(org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexEditorProvider) LocalIndexObserver(org.apache.jackrabbit.oak.plugins.index.lucene.hybrid.LocalIndexObserver) Oak(org.apache.jackrabbit.oak.Oak) NRTIndexFactory(org.apache.jackrabbit.oak.plugins.index.lucene.hybrid.NRTIndexFactory) Jcr(org.apache.jackrabbit.oak.jcr.Jcr) DefaultIndexReaderFactory(org.apache.jackrabbit.oak.plugins.index.lucene.reader.DefaultIndexReaderFactory) LuceneIndexProvider(org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexProvider) RepositoryInitializer(org.apache.jackrabbit.oak.spi.lifecycle.RepositoryInitializer) MountInfoProvider(org.apache.jackrabbit.oak.spi.mount.MountInfoProvider)

Example 8 with StopWatch

use of org.apache.commons.lang.time.StopWatch in project archiva by apache.

the class DefaultFileLockManager method writeFileLock.

@Override
public Lock writeFileLock(Path file) throws FileLockException, FileLockTimeoutException {
    if (skipLocking) {
        return new Lock(file);
    }
    try {
        mkdirs(file.getParent());
    } catch (IOException e) {
        throw new FileLockException("Could not create directory " + file.getParent(), e);
    }
    StopWatch stopWatch = new StopWatch();
    boolean acquired = false;
    Lock lock = null;
    stopWatch.start();
    while (!acquired) {
        // Make sure that not a bad lock is returned, if a exception was thrown.
        lock = null;
        if (timeout > 0) {
            long delta = stopWatch.getTime();
            log.debug("delta {}, timeout {}", delta, timeout);
            if (delta > timeout) {
                log.warn("Cannot acquire read lock within {} millis. Will skip the file: {}", timeout, file);
                // we could not get the lock within the timeout period, so throw FileLockTimeoutException
                throw new FileLockTimeoutException();
            }
        }
        Lock current = lockFiles.get(file);
        try {
            if (current != null) {
                log.trace("write lock file exist continue wait");
                continue;
            }
            lock = new Lock(file, true);
            createNewFileQuietly(file);
            lock.openLock(true, timeout > 0);
            // We are not returning an existing lock. If the lock is not
            // exclusive, another thread may release the lock and the client
            // knows nothing about it.
            // The only atomic operation is the putIfAbsent operation, so if
            // this returns null everything is OK, otherwise we should start at
            // the beginning.
            current = lockFiles.putIfAbsent(file, lock);
            if (current == null) {
                // Success
                acquired = true;
            } else {
                // We try again
                lock.close();
                lock = null;
            }
        } catch (FileNotFoundException | NoSuchFileException e) {
            log.debug("write Lock skip: {} try to create file", e.getMessage());
            createNewFileQuietly(file);
        } catch (IOException e) {
            throw new FileLockException(e.getMessage(), e);
        } catch (IllegalStateException e) {
            log.trace("openLock {}:{}", e.getClass(), e.getMessage());
        }
    }
    return lock;
}
Also used : FileNotFoundException(java.io.FileNotFoundException) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) StopWatch(org.apache.commons.lang.time.StopWatch)

Example 9 with StopWatch

use of org.apache.commons.lang.time.StopWatch in project archiva by apache.

the class DefaultFileLockManager method readFileLock.

@Override
public Lock readFileLock(Path file) throws FileLockException, FileLockTimeoutException {
    if (skipLocking) {
        return new Lock(file);
    }
    StopWatch stopWatch = new StopWatch();
    boolean acquired = false;
    try {
        mkdirs(file.getParent());
    } catch (IOException e) {
        throw new FileLockException("Could not create directories " + file.getParent(), e);
    }
    Lock lock = null;
    stopWatch.start();
    while (!acquired) {
        // Make sure that not a bad lock is returned, if a exception was thrown.
        lock = null;
        if (timeout > 0) {
            long delta = stopWatch.getTime();
            log.debug("delta {}, timeout {}", delta, timeout);
            if (delta > timeout) {
                log.warn("Cannot acquire read lock within {} millis. Will skip the file: {}", timeout, file);
                // we could not get the lock within the timeout period, so  throw  FileLockTimeoutException
                throw new FileLockTimeoutException();
            }
        }
        Lock current = lockFiles.get(file);
        if (current != null) {
            log.trace("read lock file exist continue wait");
            continue;
        }
        try {
            lock = new Lock(file, false);
            createNewFileQuietly(file);
            lock.openLock(false, timeout > 0);
            // We are not returning an existing lock. If the lock is not
            // exclusive, another thread may release the lock and the client
            // knows nothing about it.
            // The only atomic operation is the putIfAbsent operation, so if
            // this returns null everything is OK, otherwise we should start at
            // the beginning.
            current = lockFiles.putIfAbsent(file, lock);
            if (current == null) {
                // Success
                acquired = true;
            } else {
                // We try again
                lock.close();
                lock = null;
            }
        } catch (FileNotFoundException | NoSuchFileException e) {
            log.debug("read Lock skip: {} try to create file", e.getMessage());
            createNewFileQuietly(file);
        } catch (IOException e) {
            throw new FileLockException(e.getMessage(), e);
        } catch (IllegalStateException e) {
            log.trace("openLock {}:{}", e.getClass(), e.getMessage());
        }
    }
    return lock;
}
Also used : FileNotFoundException(java.io.FileNotFoundException) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) StopWatch(org.apache.commons.lang.time.StopWatch)

Example 10 with StopWatch

use of org.apache.commons.lang.time.StopWatch in project archiva by apache.

the class DefaultIndexMerger method buildMergedIndex.

@Override
public IndexingContext buildMergedIndex(IndexMergerRequest indexMergerRequest) throws IndexMergerException {
    String groupId = indexMergerRequest.getGroupId();
    if (runningGroups.contains(groupId)) {
        log.info("skip build merge remote indexes for id: '{}' as already running", groupId);
        return null;
    }
    runningGroups.add(groupId);
    StopWatch stopWatch = new StopWatch();
    stopWatch.reset();
    stopWatch.start();
    Path mergedIndexDirectory = indexMergerRequest.getMergedIndexDirectory();
    String tempRepoId = mergedIndexDirectory.getFileName().toString();
    try {
        Path indexLocation = mergedIndexDirectory.resolve(indexMergerRequest.getMergedIndexPath());
        List<IndexingContext> members = indexMergerRequest.getRepositoriesIds().stream().map(id -> repositoryRegistry.getRepository(id)).filter(repo -> repo.getType().equals(RepositoryType.MAVEN)).map(repo -> {
            try {
                return repo.getIndexingContext().getBaseContext(IndexingContext.class);
            } catch (UnsupportedBaseContextException e) {
                return null;
            // Ignore
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
        ContextMemberProvider memberProvider = new StaticContextMemberProvider(members);
        IndexingContext mergedCtx = indexer.createMergedIndexingContext(tempRepoId, tempRepoId, mergedIndexDirectory.toFile(), indexLocation.toFile(), true, memberProvider);
        mergedCtx.optimize();
        if (indexMergerRequest.isPackIndex()) {
            IndexPackingRequest request = new // 
            IndexPackingRequest(// 
            mergedCtx, // 
            mergedCtx.acquireIndexSearcher().getIndexReader(), indexLocation.toFile());
            indexPacker.packIndex(request);
        }
        if (indexMergerRequest.isTemporary()) {
            temporaryGroupIndexes.add(new TemporaryGroupIndex(mergedIndexDirectory, tempRepoId, groupId, indexMergerRequest.getMergedIndexTtl()));
            temporaryContextes.add(mergedCtx);
        }
        stopWatch.stop();
        log.info("merged index for repos {} in {} s", indexMergerRequest.getRepositoriesIds(), stopWatch.getTime());
        return mergedCtx;
    } catch (IOException e) {
        throw new IndexMergerException(e.getMessage(), e);
    } finally {
        runningGroups.remove(groupId);
    }
}
Also used : Path(java.nio.file.Path) Async(org.springframework.scheduling.annotation.Async) UnsupportedBaseContextException(org.apache.archiva.indexer.UnsupportedBaseContextException) StaticContextMemberProvider(org.apache.maven.index.context.StaticContextMemberProvider) LoggerFactory(org.slf4j.LoggerFactory) IndexCreator(org.apache.maven.index.context.IndexCreator) Inject(javax.inject.Inject) Service(org.springframework.stereotype.Service) FileUtils(org.apache.archiva.common.utils.FileUtils) IndexPackingRequest(org.apache.maven.index.packer.IndexPackingRequest) Path(java.nio.file.Path) Logger(org.slf4j.Logger) IndexPacker(org.apache.maven.index.packer.IndexPacker) Files(java.nio.file.Files) ContextMemberProvider(org.apache.maven.index.context.ContextMemberProvider) Collection(java.util.Collection) RepositoryRegistry(org.apache.archiva.repository.RepositoryRegistry) IOException(java.io.IOException) TemporaryGroupIndex(org.apache.archiva.indexer.merger.TemporaryGroupIndex) RepositoryType(org.apache.archiva.repository.RepositoryType) Collectors(java.util.stream.Collectors) IndexMerger(org.apache.archiva.indexer.merger.IndexMerger) IndexMergerException(org.apache.archiva.indexer.merger.IndexMergerException) Indexer(org.apache.maven.index.Indexer) Objects(java.util.Objects) List(java.util.List) IndexingContext(org.apache.maven.index.context.IndexingContext) IndexMergerRequest(org.apache.archiva.indexer.merger.IndexMergerRequest) StopWatch(org.apache.commons.lang.time.StopWatch) Optional(java.util.Optional) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TemporaryGroupIndex(org.apache.archiva.indexer.merger.TemporaryGroupIndex) StaticContextMemberProvider(org.apache.maven.index.context.StaticContextMemberProvider) ContextMemberProvider(org.apache.maven.index.context.ContextMemberProvider) IOException(java.io.IOException) StopWatch(org.apache.commons.lang.time.StopWatch) UnsupportedBaseContextException(org.apache.archiva.indexer.UnsupportedBaseContextException) IndexPackingRequest(org.apache.maven.index.packer.IndexPackingRequest) IndexingContext(org.apache.maven.index.context.IndexingContext) StaticContextMemberProvider(org.apache.maven.index.context.StaticContextMemberProvider) IndexMergerException(org.apache.archiva.indexer.merger.IndexMergerException)

Aggregations

StopWatch (org.apache.commons.lang.time.StopWatch)48 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 File (java.io.File)4 Path (java.nio.file.Path)4 HashMap (java.util.HashMap)4 FileNotFoundException (java.io.FileNotFoundException)3 ObjectOutputStream (java.io.ObjectOutputStream)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 Map (java.util.Map)3 SchemaHolder (org.motechproject.mds.dto.SchemaHolder)3 YarnApplicationReport (com.continuuity.weave.internal.yarn.YarnApplicationReport)2 BufferedInputStream (java.io.BufferedInputStream)2 BufferedOutputStream (java.io.BufferedOutputStream)2 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 ObjectInputStream (java.io.ObjectInputStream)2 NoSuchFileException (java.nio.file.NoSuchFileException)2 HashSet (java.util.HashSet)2