Search in sources :

Example 21 with RuntimeEnvironment

use of org.opengrok.indexer.configuration.RuntimeEnvironment in project OpenGrok by OpenGrok.

the class SearchHelper method getPrimeRelativePath.

/**
 * Determines if there is a prime equivalent to {@code relativePath}
 * according to indexed symlinks and translate (or not) accordingly.
 * @param project the project name or empty string if projects are not used
 * @param relativePath an OpenGrok-style (i.e. starting with a file
 *                     separator) relative path
 * @return a prime relative path or just {@code relativePath} if no prime
 * is matched
 */
public String getPrimeRelativePath(String project, String relativePath) throws IOException, ForbiddenSymlinkException {
    RuntimeEnvironment env = RuntimeEnvironment.getInstance();
    String sourceRoot = env.getSourceRootPath();
    if (sourceRoot == null) {
        throw new IllegalStateException("sourceRoot is not defined");
    }
    File absolute = new File(sourceRoot + relativePath);
    ensureSettingsHelper();
    settingsHelper.getSettings(project);
    Map<String, IndexedSymlink> indexedSymlinks = settingsHelper.getSymlinks(project);
    if (indexedSymlinks != null) {
        String canonical = absolute.getCanonicalFile().getPath();
        for (IndexedSymlink entry : indexedSymlinks.values()) {
            if (canonical.equals(entry.getCanonical())) {
                if (absolute.getPath().equals(entry.getAbsolute())) {
                    return relativePath;
                }
                Path newAbsolute = Paths.get(entry.getAbsolute());
                return env.getPathRelativeToSourceRoot(newAbsolute.toFile());
            } else if (canonical.startsWith(entry.getCanonicalSeparated())) {
                Path newAbsolute = Paths.get(entry.getAbsolute(), canonical.substring(entry.getCanonicalSeparated().length()));
                return env.getPathRelativeToSourceRoot(newAbsolute.toFile());
            }
        }
    }
    return relativePath;
}
Also used : Path(java.nio.file.Path) RuntimeEnvironment(org.opengrok.indexer.configuration.RuntimeEnvironment) File(java.io.File) IndexedSymlink(org.opengrok.indexer.index.IndexedSymlink)

Example 22 with RuntimeEnvironment

use of org.opengrok.indexer.configuration.RuntimeEnvironment in project OpenGrok by OpenGrok.

the class SearchHelper method searchSingle.

/**
 * Searches for a document for a single file from the index.
 * @param file the file whose definitions to find
 * @return {@link ScoreDoc#doc} or -1 if it could not be found
 * @throws IOException if an error happens when accessing the index
 * @throws ParseException if an error happens when building the Lucene query
 */
public int searchSingle(File file) throws IOException, ParseException {
    RuntimeEnvironment env = RuntimeEnvironment.getInstance();
    String path;
    try {
        path = env.getPathRelativeToSourceRoot(file);
    } catch (ForbiddenSymlinkException e) {
        LOGGER.log(Level.FINER, e.getMessage());
        return -1;
    }
    // sanitize windows path delimiters
    // in order not to conflict with Lucene escape character
    path = path.replace("\\", "/");
    QueryBuilder singleBuilder = new QueryBuilder();
    if (builder != null) {
        singleBuilder.reset(builder);
    }
    query = singleBuilder.setPath(path).build();
    TopDocs top = searcher.search(query, 1);
    if (top.totalHits.value == 0) {
        return -1;
    }
    int docID = top.scoreDocs[0].doc;
    Document doc = searcher.doc(docID);
    String foundPath = doc.get(QueryBuilder.PATH);
    // Only use the result if PATH matches exactly.
    if (!path.equals(foundPath)) {
        return -1;
    }
    return docID;
}
Also used : TopDocs(org.apache.lucene.search.TopDocs) RuntimeEnvironment(org.opengrok.indexer.configuration.RuntimeEnvironment) ForbiddenSymlinkException(org.opengrok.indexer.util.ForbiddenSymlinkException) QueryBuilder(org.opengrok.indexer.search.QueryBuilder) Document(org.apache.lucene.document.Document)

Example 23 with RuntimeEnvironment

use of org.opengrok.indexer.configuration.RuntimeEnvironment in project OpenGrok by OpenGrok.

the class PascalAnalyzerFactoryTest method setUpClass.

@BeforeAll
public static void setUpClass() throws Exception {
    ctags = new Ctags();
    repository = new TestRepository();
    repository.create(PascalAnalyzerFactoryTest.class.getClassLoader().getResource("sources"));
    PascalAnalyzerFactory analyzerFactory = new PascalAnalyzerFactory();
    analyzer = analyzerFactory.getAnalyzer();
    RuntimeEnvironment env = RuntimeEnvironment.getInstance();
    if (env.validateUniversalCtags()) {
        analyzer.setCtags(new Ctags());
    }
}
Also used : TestRepository(org.opengrok.indexer.util.TestRepository) RuntimeEnvironment(org.opengrok.indexer.configuration.RuntimeEnvironment) Ctags(org.opengrok.indexer.analysis.Ctags) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 24 with RuntimeEnvironment

use of org.opengrok.indexer.configuration.RuntimeEnvironment in project OpenGrok by OpenGrok.

the class PlainAnalyzerTest method testXrefTimeout.

@Test
void testXrefTimeout() {
    RuntimeEnvironment env = RuntimeEnvironment.getInstance();
    long timeoutOriginal = env.getXrefTimeout();
    int timeout = 1;
    env.setXrefTimeout(timeout);
    assertEquals(timeout, env.getXrefTimeout());
    TestablePlainAnalyzer analyzer = new TestablePlainAnalyzer();
    Exception exception = assertThrows(InterruptedException.class, () -> analyzer.analyze(new Document(), getStreamSource("hi".getBytes()), new OutputStreamWriter(new ByteArrayOutputStream())));
    assertTrue(analyzer.writeXrefCalled);
    assertTrue(exception.getMessage().contains("failed to generate xref"));
    env.setXrefTimeout(timeoutOriginal);
}
Also used : RuntimeEnvironment(org.opengrok.indexer.configuration.RuntimeEnvironment) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.apache.lucene.document.Document) IOException(java.io.IOException) Test(org.junit.jupiter.api.Test)

Example 25 with RuntimeEnvironment

use of org.opengrok.indexer.configuration.RuntimeEnvironment in project OpenGrok by OpenGrok.

the class IncomingFilterTest method nonLocalhostTestWithTokenChange.

@Test
public void nonLocalhostTestWithTokenChange() throws Exception {
    RuntimeEnvironment env = RuntimeEnvironment.getInstance();
    String token = "foobar";
    Map<String, String> headers = new TreeMap<>();
    final String authHeaderValue = IncomingFilter.BEARER + token;
    headers.put(HttpHeaders.AUTHORIZATION, authHeaderValue);
    assertTrue(env.getAuthenticationTokens().isEmpty());
    IncomingFilter filter = mockWithRemoteAddress("192.168.1.1", headers, true);
    ContainerRequestContext context = mockContainerRequestContext("test");
    ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
    // No tokens configured.
    filter.filter(context);
    verify(context).abortWith(captor.capture());
    // Setting tokens without refreshing configuration should have no effect.
    Set<String> tokens = new HashSet<>();
    tokens.add(token);
    env.setAuthenticationTokens(tokens);
    filter.filter(context);
    verify(context, times(2)).abortWith(captor.capture());
    // The request should pass only after applyConfig().
    env.applyConfig(false, CommandTimeoutType.RESTFUL);
    context = mockContainerRequestContext("test");
    filter.filter(context);
    verify(context, never()).abortWith(captor.capture());
}
Also used : Response(jakarta.ws.rs.core.Response) RuntimeEnvironment(org.opengrok.indexer.configuration.RuntimeEnvironment) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Aggregations

RuntimeEnvironment (org.opengrok.indexer.configuration.RuntimeEnvironment)81 File (java.io.File)26 Project (org.opengrok.indexer.configuration.Project)24 Test (org.junit.jupiter.api.Test)22 IOException (java.io.IOException)18 BeforeAll (org.junit.jupiter.api.BeforeAll)13 ArrayList (java.util.ArrayList)12 TestRepository (org.opengrok.indexer.util.TestRepository)12 Path (java.nio.file.Path)8 ForbiddenSymlinkException (org.opengrok.indexer.util.ForbiddenSymlinkException)8 Document (org.apache.lucene.document.Document)6 Ctags (org.opengrok.indexer.analysis.Ctags)6 Executor (org.opengrok.indexer.util.Executor)6 BufferedReader (java.io.BufferedReader)5 FileNotFoundException (java.io.FileNotFoundException)5 InputStreamReader (java.io.InputStreamReader)5 EnabledForRepository (org.opengrok.indexer.condition.EnabledForRepository)5 HistoryGuru (org.opengrok.indexer.history.HistoryGuru)5 BeforeEach (org.junit.jupiter.api.BeforeEach)4 RepositoryInfo (org.opengrok.indexer.history.RepositoryInfo)4