proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/PhraseHighlight.java
|
PhraseHighlight
|
merge
|
class PhraseHighlight {
/**
* a value that has been translated from start offset w.r.t. document
* start to a value w.r.t. line start -- or -1 if not beginning this
* line
*/
private final int lineStart;
/**
* a value that has been translated from start offset w.r.t. document
* start to a value w.r.t. line start -- or {@link Integer#MAX_VALUE} if
* not ending this line
*/
private final int lineEnd;
public static PhraseHighlight create(int start, int end) {
return new PhraseHighlight(start, end);
}
public static PhraseHighlight createStarter(int start) {
return new PhraseHighlight(start, Integer.MAX_VALUE);
}
public static PhraseHighlight createEnder(int end) {
return new PhraseHighlight(-1, end);
}
public static PhraseHighlight createEntire() {
return new PhraseHighlight(-1, Integer.MAX_VALUE);
}
/**
* Gets a value that has been translated from start offset w.r.t. document
* start to a value w.r.t. line start -- or -1 if not beginning this
* line.
* @return offset
*/
public int getLineStart() {
return lineStart;
}
/**
* Gets a value that has been translated from start offset w.r.t. document
* start to a value w.r.t. line start -- or {@link Integer#MAX_VALUE} if
* not ending this line.
* @return offset
*/
public int getLineEnd() {
return lineEnd;
}
/**
* Determines if the specified {@code other} overlaps with this instance.
*
* @param other object to compare to
* @return {@code true} if the instances overlap
*/
public boolean overlaps(PhraseHighlight other) {
return (lineStart >= other.lineStart && lineStart <= other.lineEnd) ||
(other.lineStart >= lineStart && other.lineStart <= lineEnd) ||
(lineEnd >= other.lineStart && lineEnd <= other.lineEnd) ||
(other.lineEnd >= lineStart && other.lineEnd <= lineEnd);
}
/**
* Creates a new instance that is the merging of this instance and the
* specified {@code other}.
* @param other object to compare to
* @return a defined instance
*/
public PhraseHighlight merge(PhraseHighlight other) {<FILL_FUNCTION_BODY>}
/** Private to enforce static create() methods. */
private PhraseHighlight(int start, int end) {
this.lineStart = start;
this.lineEnd = end;
}
}
|
int mergeStart = Math.min(lineStart, other.lineStart);
int mergeEnd = Math.max(lineEnd, other.lineEnd);
return PhraseHighlight.create(mergeStart, mergeEnd);
| 714
| 55
| 769
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/PhraseHighlightComparator.java
|
PhraseHighlightComparator
|
compare
|
class PhraseHighlightComparator implements Comparator<PhraseHighlight> {
public static final PhraseHighlightComparator INSTANCE = new PhraseHighlightComparator();
/**
* Compares two {@link PhraseHighlight} instances for order by first
* comparing using {@link Integer#compare(int, int)} the
* {@link PhraseHighlight#lineStart} values of {@code o1} and {@code o2} and
* subsequently, if identical, comparing the {@link PhraseHighlight#lineEnd}
* values of {@code o2} and {@code o1} (i.e. inverted).
* <p>The ordering allows to iterate through a collection afterward and
* easily subsume where necessary a {@link PhraseHighlight} instance into
* its immediate predecessor.
* @param o1 a required instance
* @param o2 a required instance
* @return a negative integer, zero, or a positive integer as the first
* argument is less than, equal to, or greater than the second
*/
@Override
public int compare(PhraseHighlight o1, PhraseHighlight o2) {<FILL_FUNCTION_BODY>}
/** Private to enforce singleton. */
private PhraseHighlightComparator() {
}
}
|
int cmp;
if (o1.getLineStart() < 0) {
if (o2.getLineStart() >= 0) {
return -1;
}
cmp = 0;
} else if (o2.getLineStart() < 0) {
return 1;
} else {
cmp = Integer.compare(o1.getLineStart(), o2.getLineStart());
}
if (cmp != 0) {
return cmp;
}
cmp = Integer.compare(o2.getLineEnd(), o1.getLineEnd());
return cmp;
| 321
| 158
| 479
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/PhraseMatcher.java
|
PhraseMatcher
|
match
|
class PhraseMatcher extends LineMatcher {
private final String[] phraseTerms;
private int cur;
PhraseMatcher(String[] phraseTerms, boolean caseInsensitive) {
super(caseInsensitive);
this.phraseTerms = phraseTerms.clone();
cur = 0;
}
@Override
public int match(String token) {<FILL_FUNCTION_BODY>}
}
|
if (equal(token, phraseTerms[cur])) {
if (cur < phraseTerms.length - 1) {
cur++;
return WAIT; //matching.
}
cur = 0;
return MATCHED; //matched!
} else if (cur > 0) {
cur = 0;
if (equal(token, phraseTerms[cur])) {
cur++;
return WAIT; //matching.
}
}
return NOT_MATCHED;
| 107
| 131
| 238
|
<methods>public abstract int match(java.lang.String) <variables>public static final int MATCHED,public static final int NOT_MATCHED,public static final int WAIT,private final non-sealed boolean caseInsensitive
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/PrefixMatcher.java
|
PrefixMatcher
|
match
|
class PrefixMatcher extends LineMatcher {
private final String prefix;
public PrefixMatcher(String prefix, boolean caseInsensitive) {
super(caseInsensitive);
this.prefix = normalizeString(prefix);
}
@Override
public int match(String token) {<FILL_FUNCTION_BODY>}
}
|
String tokenToMatch = normalizeString(token);
return tokenToMatch.startsWith(prefix) ? MATCHED : NOT_MATCHED;
| 88
| 40
| 128
|
<methods>public abstract int match(java.lang.String) <variables>public static final int MATCHED,public static final int NOT_MATCHED,public static final int WAIT,private final non-sealed boolean caseInsensitive
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/QueryMatchers.java
|
QueryMatchers
|
getWildTerm
|
class QueryMatchers {
private Set<String> caseSensitiveTerms;
private Set<String> caseInsensitiveTerms;
private List<LineMatcher> matchers;
private Map<String, Boolean> fields;
/**
* Get the terms from a query and returns a list of DFAs which match a stream
* of tokens.
*
* @param query the query to generate matchers for
* @param fields a map whose keys tell which fields to create matchers for,
* and whose values tell if the field is case insensitive (true) or case
* sensitive (false)
* @return list of LineMatching DFAs
*/
public LineMatcher[] getMatchers(Query query, Map<String, Boolean> fields) {
caseSensitiveTerms = new HashSet<>();
caseInsensitiveTerms = new HashSet<>();
matchers = new ArrayList<>();
this.fields = fields;
getTerms(query);
if (!caseSensitiveTerms.isEmpty()) {
matchers.add(0, new TokenSetMatcher(caseSensitiveTerms, false));
}
if (!caseInsensitiveTerms.isEmpty()) {
matchers.add(0, new TokenSetMatcher(caseInsensitiveTerms, true));
}
if (matchers.isEmpty()) {
return null;
}
return matchers.toArray(new LineMatcher[0]);
}
private void getTerms(Query query) {
if (query instanceof BooleanQuery) {
getBooleans((BooleanQuery) query);
} else if (query instanceof PhraseQuery) {
getPhrases((PhraseQuery) query);
} else if (query instanceof WildcardQuery) {
getWildTerm((WildcardQuery) query);
} else if (query instanceof TermQuery) {
getTerm((TermQuery) query);
} else if (query instanceof PrefixQuery) {
getPrefix((PrefixQuery) query);
} else if (query instanceof RegexpQuery) {
getRegexp((RegexpQuery) query);
}
}
private void getRegexp(RegexpQuery query) {
if (useTerm(query.getField())) {
String term = query.toString(query.getField());
term = term.substring(1, term.length() - 1); //trim / from /regexp/
matchers.add(new RegexpMatcher(term, true));
}
}
private void getBooleans(BooleanQuery query) {
for (BooleanClause clause : query) {
if (!clause.isProhibited()) {
getTerms(clause.getQuery());
}
}
}
private void getPhrases(PhraseQuery query) {
Term[] queryTerms = query.getTerms();
if (queryTerms.length > 0 && useTerm(queryTerms[0])) {
boolean caseInsensitive = isCaseInsensitive(queryTerms[0]);
String[] termsArray = new String[queryTerms.length];
for (int i = 0; i < queryTerms.length; i++) {
termsArray[i] = queryTerms[i].text();
}
matchers.add(new PhraseMatcher(termsArray, caseInsensitive));
}
}
private void getTerm(TermQuery query) {
Term term = query.getTerm();
if (useTerm(term)) {
String text = term.text();
if (isCaseInsensitive(term)) {
caseInsensitiveTerms.add(text);
} else {
caseSensitiveTerms.add(text);
}
}
}
private void getWildTerm(WildcardQuery query) {<FILL_FUNCTION_BODY>}
private void getPrefix(PrefixQuery query) {
Term term = query.getPrefix();
if (useTerm(term)) {
matchers.add(
new PrefixMatcher(term.text(), isCaseInsensitive(term)));
}
}
/**
* Check whether a matcher should be created for a term.
*/
private boolean useTerm(Term term) {
return useTerm(term.field());
}
/**
* Check whether a matcher should be created for a term.
*/
private boolean useTerm(String termField) {
return fields.containsKey(termField);
}
/**
* Check if a term should be matched in a case-insensitive manner. Should
* only be called on terms for which {@link #useTerm(Term)} returns true.
*/
private boolean isCaseInsensitive(Term term) {
return fields.get(term.field());
}
}
|
Term term = query.getTerm();
if (useTerm(term)) {
matchers.add(
new WildCardMatcher(term.text(), isCaseInsensitive(term)));
}
| 1,186
| 52
| 1,238
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/RegexpMatcher.java
|
RegexpMatcher
|
match
|
class RegexpMatcher extends LineMatcher {
private static final Logger LOGGER = LoggerFactory.getLogger(RegexpMatcher.class);
private final Pattern termRegexp;
RegexpMatcher(String term, boolean caseInsensitive) {
super(caseInsensitive);
Pattern regexp;
try {
regexp = Pattern.compile(term, caseInsensitive ? Pattern.CASE_INSENSITIVE : 0 );
} catch ( PatternSyntaxException e) {
regexp = null;
LOGGER.log(Level.WARNING, "RegexpMatcher: {0}", e.getMessage() );
}
this.termRegexp = regexp;
}
@Override
public int match(String line) {<FILL_FUNCTION_BODY>}
}
|
return (termRegexp != null && termRegexp.matcher(line).matches()) ? MATCHED : NOT_MATCHED;
| 212
| 39
| 251
|
<methods>public abstract int match(java.lang.String) <variables>public static final int MATCHED,public static final int NOT_MATCHED,public static final int WAIT,private final non-sealed boolean caseInsensitive
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/StrictLineBreakIterator.java
|
StrictLineBreakIterator
|
next
|
class StrictLineBreakIterator extends BreakIterator {
private final List<Integer> breaks = new ArrayList<>();
private char peekChar = CharacterIterator.DONE;
private CharacterIterator charIt;
private int breakOffset = -1;
public StrictLineBreakIterator() {
charIt = new StringCharacterIterator("");
}
@Override
public int first() {
breaks.clear();
breakOffset = -1;
charIt.first();
return 0;
}
@Override
public int last() {
int c;
do {
c = current();
} while (next() != BreakIterator.DONE);
return c;
}
@Override
public int next(int n) {
if (n < 0) {
throw new IllegalArgumentException("n cannot be negative");
}
int noff = current();
for (int i = 0; i < n; ++i) {
noff = next();
if (noff == BreakIterator.DONE) {
return noff;
}
}
return noff;
}
@Override
public int next() {<FILL_FUNCTION_BODY>}
@Override
public int previous() {
if (breakOffset >= 0) {
if (--breakOffset >= 0) {
return breaks.get(breakOffset);
}
return 0;
}
return BreakIterator.DONE;
}
@Override
public int following(int offset) {
if (!breaks.isEmpty() && breaks.get(breaks.size() - 1) > offset) {
int lo = 0;
int hi = breaks.size() - 1;
int mid;
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
int boff = breaks.get(mid);
if (offset < boff) {
if (mid < 1 || offset >= breaks.get(mid - 1)) {
return boff;
} else {
hi = mid - 1;
}
} else {
lo = mid + 1;
}
}
// This should not be reached.
return BreakIterator.DONE;
}
int noff;
do {
noff = next();
if (noff > offset) {
return noff;
}
} while (noff != BreakIterator.DONE);
return noff;
}
@Override
public int current() {
if (breakOffset < 0) {
return 0;
}
return breakOffset < breaks.size() ? breaks.get(breakOffset) :
charIt.current();
}
@Override
public CharacterIterator getText() {
return (CharacterIterator) charIt.clone();
}
@Override
public void setText(CharacterIterator newText) {
if (newText == null) {
throw new IllegalArgumentException("newText is null");
}
this.charIt = newText;
this.breaks.clear();
this.peekChar = newText.current();
this.breakOffset = -1;
}
}
|
if (breakOffset + 1 < breaks.size()) {
return breaks.get(++breakOffset);
}
char lastChar = CharacterIterator.DONE;
int charOff;
while (true) {
char nextChar;
if (peekChar != CharacterIterator.DONE) {
nextChar = peekChar;
peekChar = CharacterIterator.DONE;
} else {
nextChar = charIt.next();
}
switch (nextChar) {
case CharacterIterator.DONE:
if (lastChar != CharacterIterator.DONE) {
charOff = charIt.getIndex();
breaks.add(charOff);
++breakOffset;
return charOff;
} else {
return BreakIterator.DONE;
}
case '\n':
// charOff is just past the LF
charOff = charIt.getIndex() + 1;
breaks.add(charOff);
++breakOffset;
return charOff;
case '\r':
charOff = charIt.getIndex() + 1;
peekChar = charIt.next();
switch (peekChar) {
case '\n':
peekChar = CharacterIterator.DONE;
// charOff is just past the LF
++charOff;
breaks.add(charOff);
++breakOffset;
return charOff;
case CharacterIterator.DONE:
default:
breaks.add(charOff);
++breakOffset;
return charOff;
}
default:
lastChar = nextChar;
break;
}
}
| 809
| 407
| 1,216
|
<methods>public java.lang.Object clone() ,public abstract int current() ,public abstract int first() ,public abstract int following(int) ,public static synchronized java.util.Locale[] getAvailableLocales() ,public static java.text.BreakIterator getCharacterInstance() ,public static java.text.BreakIterator getCharacterInstance(java.util.Locale) ,public static java.text.BreakIterator getLineInstance() ,public static java.text.BreakIterator getLineInstance(java.util.Locale) ,public static java.text.BreakIterator getSentenceInstance() ,public static java.text.BreakIterator getSentenceInstance(java.util.Locale) ,public abstract java.text.CharacterIterator getText() ,public static java.text.BreakIterator getWordInstance() ,public static java.text.BreakIterator getWordInstance(java.util.Locale) ,public boolean isBoundary(int) ,public abstract int last() ,public abstract int next() ,public abstract int next(int) ,public int preceding(int) ,public abstract int previous() ,public void setText(java.lang.String) ,public abstract void setText(java.text.CharacterIterator) <variables>private static final int CHARACTER_INDEX,public static final int DONE,private static final int LINE_INDEX,private static final int SENTENCE_INDEX,private static final int WORD_INDEX,private static final SoftReference<java.text.BreakIterator.BreakIteratorCache>[] iterCache
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/WildCardMatcher.java
|
WildCardMatcher
|
wildcardEquals
|
class WildCardMatcher extends LineMatcher {
final String pattern;
public WildCardMatcher(String pattern, boolean caseInsensitive) {
super(caseInsensitive);
this.pattern = normalizeString(pattern);
}
@Override
public int match(String token) {
String tokenToMatch = normalizeString(token);
return wildcardEquals(pattern, 0, tokenToMatch, 0)
? MATCHED
: NOT_MATCHED;
}
//TODO below might be buggy, we might need to rewrite this anyways
// so far keep it for the sake of 4.0 port
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
public static final char WILDCARD_STRING = '*';
public static final char WILDCARD_CHAR = '?';
/**
* Determines if a word matches a wildcard pattern. <small>Work released by
* Granta Design Ltd after originally being done on company time.</small>
* @param pattern pattern
* @param patternIdx index
* @param string word
* @param stringIdx index
* @return true if word matches the pattern
*/
public static boolean wildcardEquals(String pattern, int patternIdx,
String string, int stringIdx) {<FILL_FUNCTION_BODY>}
}
|
int p = patternIdx;
for (int s = stringIdx;; ++p, ++s) {
// End of string yet?
boolean sEnd = (s >= string.length());
// End of pattern yet?
boolean pEnd = (p >= pattern.length());
// If we're looking at the end of the string...
if (sEnd) {
// Assume the only thing left on the pattern is/are wildcards
boolean justWildcardsLeft = true;
// Current wildcard position
int wildcardSearchPos = p;
// While we haven't found the end of the pattern,
// and haven't encountered any non-wildcard characters
while (wildcardSearchPos < pattern.length() && justWildcardsLeft) {
// Check the character at the current position
char wildchar = pattern.charAt(wildcardSearchPos);
// If it's not a wildcard character, then there is more
// pattern information after this/these wildcards.
if (wildchar != WILDCARD_CHAR && wildchar != WILDCARD_STRING) {
justWildcardsLeft = false;
} else {
// to prevent "cat" matches "ca??"
if (wildchar == WILDCARD_CHAR) {
return false;
}
// Look at the next character
wildcardSearchPos++;
}
}
// This was a prefix wildcard search, and we've matched, so
// return true.
if (justWildcardsLeft) {
return true;
}
}
// If we've gone past the end of the string, or the pattern,
// return false.
if (sEnd || pEnd) {
break;
}
// Match a single character, so continue.
if (pattern.charAt(p) == WILDCARD_CHAR) {
continue;
}
//
if (pattern.charAt(p) == WILDCARD_STRING) {
// Look at the character beyond the '*' characters.
while (p < pattern.length() && pattern.charAt(p) == WILDCARD_STRING) {
++p;
}
// Examine the string, starting at the last character.
for (int i = string.length(); i >= s; --i) {
if (wildcardEquals(pattern, p, string, i)) {
return true;
}
}
break;
}
if (pattern.charAt(p) != string.charAt(s)) {
break;
}
}
return false;
| 532
| 663
| 1,195
|
<methods>public abstract int match(java.lang.String) <variables>public static final int MATCHED,public static final int NOT_MATCHED,public static final int WAIT,private final non-sealed boolean caseInsensitive
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/AbstractObjectPool.java
|
AbstractObjectPool
|
release
|
class AbstractObjectPool<T> implements ObjectPool<T> {
/**
* Returns the object to the pool.
* The method first validates the object if it is
* re-usable and then puts returns it to the pool.
*
* If the object validation fails,
* {@link #handleInvalidReturn(java.lang.Object)} is called.
* Some implementations
* will try to create a new object
* and put it into the pool; however
* this behaviour is subject to change
* from implementation to implementation.
*/
public final void release(T t) {<FILL_FUNCTION_BODY>}
protected abstract void handleInvalidReturn(T t);
protected abstract void returnToPool(T t);
protected abstract boolean isValid(T t);
}
|
if (isValid(t)) {
returnToPool(t);
} else {
handleInvalidReturn(t);
}
| 199
| 37
| 236
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/BoundedBlockingObjectPool.java
|
BoundedBlockingObjectPool
|
handleInvalidReturn
|
class BoundedBlockingObjectPool<T> extends AbstractObjectPool<T>
implements BlockingObjectPool<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(
BoundedBlockingObjectPool.class);
private final int size;
private final LinkedBlockingDeque<T> objects;
private final ObjectValidator<T> validator;
private final ObjectFactory<T> objectFactory;
private final ExecutorService executor = Executors.newCachedThreadPool(new OpenGrokThreadFactory("bounded"));
private volatile boolean puttingLast;
private volatile boolean shutdownCalled;
public BoundedBlockingObjectPool(int size, ObjectValidator<T> validator,
ObjectFactory<T> objectFactory) {
this.objectFactory = objectFactory;
this.size = size;
this.validator = validator;
objects = new LinkedBlockingDeque<>(size);
initializeObjects();
}
@Override
public T get(long timeOut, TimeUnit unit) {
if (!shutdownCalled) {
T ret = null;
try {
ret = objects.pollFirst(timeOut, unit);
/*
* When the queue first empties, switch to a strategy of putting
* returned objects last instead of first.
*/
if (!puttingLast && objects.isEmpty()) {
puttingLast = true;
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
return ret;
}
throw new IllegalStateException("Object pool is already shutdown");
}
@Override
public T get() {
if (!shutdownCalled) {
T ret = null;
try {
ret = objects.takeFirst();
/*
* When the queue first empties, switch to a strategy of putting
* returned objects last instead of first.
*/
if (!puttingLast && objects.isEmpty()) {
puttingLast = true;
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
return ret;
}
throw new IllegalStateException("Object pool is already shutdown");
}
@Override
public void shutdown() {
shutdownCalled = true;
executor.shutdownNow();
clearResources();
}
private void clearResources() {
for (T t : objects) {
validator.invalidate(t);
}
}
@Override
protected void returnToPool(T t) {
if (validator.isValid(t)) {
executor.submit(new ObjectReturner<>(objects, t, puttingLast));
}
}
/*
* Creates a new instance, and returns that instead to the pool.
*/
@Override
protected void handleInvalidReturn(T t) {<FILL_FUNCTION_BODY>}
@Override
protected boolean isValid(T t) {
return validator.isValid(t);
}
private void initializeObjects() {
for (int i = 0; i < size; i++) {
objects.add(objectFactory.createNew());
}
}
private static class ObjectReturner<E> implements Callable<Void> {
private final LinkedBlockingDeque<E> queue;
private final E e;
private final boolean puttingLast;
ObjectReturner(LinkedBlockingDeque<E> queue, E e, boolean puttingLast) {
this.queue = queue;
this.e = e;
this.puttingLast = puttingLast;
}
@Override
public Void call() {
while (true) {
try {
if (puttingLast) {
queue.putLast(e);
} else {
queue.putFirst(e);
}
break;
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
return null;
}
}
}
|
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "createNew() to handle invalid {0}",
t.getClass());
}
t = objectFactory.createNew();
executor.submit(new ObjectReturner<>(objects, t, puttingLast));
| 1,013
| 85
| 1,098
|
<methods>public non-sealed void <init>() ,public final void release(T) <variables>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/CloseableReentrantReadWriteLock.java
|
CloseableReentrantReadWriteLock
|
readLockAsResource
|
class CloseableReentrantReadWriteLock extends ReentrantReadWriteLock {
private static final long serialVersionUID = 95L;
private transient ResourceLock readUnlocker = newReadUnlocker();
private transient ResourceLock writeUnlocker = newWriteUnlocker();
/**
* @return a defined {@link ResourceLock} once the {@link #readLock()} has
* been acquired
*/
public ResourceLock readLockAsResource() {<FILL_FUNCTION_BODY>}
/**
* @return a defined {@link ResourceLock} once the {@link #writeLock()}
* has been acquired
*/
public ResourceLock writeLockAsResource() {
/*
* A subclass of ReentrantReadWriteLock is forced to be serializable, so
* we would have to handle where serialization can short-circuit field
* initialization above and leave the instance's fields null.
* Consequently, the fields cannot be final. They are encapsulating
* fixed logic, so we can optimize and choose not to even bother
* serializing by declaring transient and handling below.
*/
ResourceLock unlocker = writeUnlocker;
if (unlocker == null) {
unlocker = newWriteUnlocker();
// No synchronization necessary since overwrite is of no matter.
writeUnlocker = unlocker;
}
writeLock().lock();
return unlocker;
}
private ResourceLock newReadUnlocker() {
return () -> this.readLock().unlock();
}
private ResourceLock newWriteUnlocker() {
return () -> this.writeLock().unlock();
}
}
|
/*
* A subclass of ReentrantReadWriteLock is forced to be serializable, so
* we would have to handle where serialization can short-circuit field
* initialization above and leave the instance's fields null.
* Consequently, the fields cannot be final. They are encapsulating
* fixed logic, so we can optimize and choose not to even bother
* serializing by declaring transient and handling below.
*/
ResourceLock unlocker = readUnlocker;
if (unlocker == null) {
unlocker = newReadUnlocker();
// No synchronization necessary since overwrite is of no matter.
readUnlocker = unlocker;
}
readLock().lock();
return unlocker;
| 411
| 180
| 591
|
<methods>public void <init>() ,public void <init>(boolean) ,public final int getQueueLength() ,public int getReadHoldCount() ,public int getReadLockCount() ,public int getWaitQueueLength(java.util.concurrent.locks.Condition) ,public int getWriteHoldCount() ,public final boolean hasQueuedThread(java.lang.Thread) ,public final boolean hasQueuedThreads() ,public boolean hasWaiters(java.util.concurrent.locks.Condition) ,public final boolean isFair() ,public boolean isWriteLocked() ,public boolean isWriteLockedByCurrentThread() ,public java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock readLock() ,public java.lang.String toString() ,public java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock writeLock() <variables>private final java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock readerLock,private static final long serialVersionUID,final java.util.concurrent.locks.ReentrantReadWriteLock.Sync sync,private final java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock writerLock
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/ColorUtil.java
|
ColorUtil
|
fromHex
|
class ColorUtil {
private ColorUtil() {
}
/**
* Return Color object from string. The following formats are allowed:
* {@code A1B2C3},
* {@code abc123}
*
* @param str hex string
* @return Color object
*/
public static Color fromHex(String str) {<FILL_FUNCTION_BODY>}
private static int parseHexNumber(String str, int pos) {
return 16 * convertToDecimal(str, pos) + convertToDecimal(str, pos + 1);
}
private static int convertToDecimal(String str, int pos) {
char ch = str.charAt(pos);
if (ch >= '0' && ch <= '9') {
return ch - '0';
}
if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
}
throw new IllegalArgumentException("unsupported char at " + pos + ":" + str);
}
}
|
if (str.length() != 6) {
throw new IllegalArgumentException("unsupported length:" + str);
}
return new Color(parseHexNumber(str, 0), parseHexNumber(str, 2), parseHexNumber(str, 4));
| 297
| 70
| 367
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/CtagsUtil.java
|
CtagsUtil
|
canProcessFiles
|
class CtagsUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(CtagsUtil.class);
public static final String SYSTEM_CTAGS_PROPERTY = "org.opengrok.indexer.analysis.Ctags";
/** Private to enforce static. */
private CtagsUtil() {
}
/**
* Check that {@code ctags} program exists and is working.
* @param ctagsBinary name of the ctags program or path
* @return true if the program works, false otherwise
*/
public static boolean validate(String ctagsBinary) {
if (!isUniversalCtags(ctagsBinary)) {
return false;
}
return canProcessFiles(RuntimeEnvironment.getInstance().getSourceRootFile());
}
/**
* Run ctags program on a known temporary file to be created under given path and see if it was possible
* to get some symbols.
* @param baseDir directory to use for storing the temporary file
* @return true if at least one symbol was found, false otherwise
*/
private static boolean canProcessFiles(File baseDir) {<FILL_FUNCTION_BODY>}
@Nullable
public static String getCtagsVersion(String ctagsBinary) {
Executor executor = new Executor(new String[]{ctagsBinary, "--version"});
executor.exec(false);
String output = executor.getOutputString();
if (output != null) {
output = output.trim();
}
return output;
}
private static boolean isUniversalCtags(String ctagsBinary) {
String version = getCtagsVersion(ctagsBinary);
boolean isUniversalCtags = version != null && version.contains("Universal Ctags");
if (version == null || !isUniversalCtags) {
LOGGER.log(Level.SEVERE, "Error: No Universal Ctags found !\n"
+ "(tried running " + "{0}" + ")\n"
+ "Please use the -c option to specify path to a "
+ "Universal Ctags program.\n"
+ "Or set it in Java system property {1}",
new Object[]{ctagsBinary, SYSTEM_CTAGS_PROPERTY});
return false;
}
return true;
}
/**
* Gets the base set of languages by executing {@code --list-languages} for the specified binary.
* @return empty list on failure to run, or a defined list
*/
public static Set<String> getLanguages(String ctagsBinary) {
Executor executor = new Executor(new String[]{ctagsBinary, "--list-languages"});
int rc = executor.exec(false);
String output = executor.getOutputString();
if (output == null || rc != 0) {
LOGGER.log(Level.WARNING, "Failed to get Ctags languages");
return Collections.emptySet();
}
output = output.replaceAll("\\s+\\[disabled]", "");
String[] split = output.split("(?m)$");
Set<String> result = new HashSet<>();
for (String lang : split) {
lang = lang.trim();
if (!lang.isEmpty()) {
result.add(lang);
}
}
return result;
}
/**
* Deletes Ctags temporary files left over after terminating Ctags processes
* in case of timeout or Ctags crash, @see Ctags#doCtags.
*/
public static void deleteTempFiles() {
Set<String> dirs = new HashSet<>(Arrays.asList(System.getProperty("java.io.tmpdir"),
System.getenv("TMPDIR"), System.getenv("TMP")));
if (SystemUtils.IS_OS_UNIX) {
// hard-coded TMPDIR in Universal Ctags on Unix.
dirs.add("/tmp");
}
dirs = dirs.stream()
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for (String directoryName : dirs) {
File directory = new File(directoryName);
if (!directory.isDirectory()) {
continue;
}
LOGGER.log(Level.FINER, "deleting Ctags temporary files in directory ''{0}''", directoryName);
deleteTempFiles(directory);
}
}
private static void deleteTempFiles(File directory) {
final Pattern pattern = Pattern.compile("tags\\.\\S{6}"); // ctags uses this pattern to call mkstemp()
File[] files = directory.listFiles((dir, name) -> {
Matcher matcher = pattern.matcher(name);
return matcher.find();
});
if (Objects.isNull(files)) {
return;
}
for (File file : files) {
if (file.isFile()) {
try {
Files.delete(file.toPath());
} catch (IOException exception) {
LOGGER.log(Level.WARNING, String.format("cannot delete file '%s'", file), exception);
}
}
}
}
}
|
Path inputPath;
try {
inputPath = File.createTempFile("ctagsValidation", ".c", baseDir).toPath();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "cannot create temporary file in ''{0}''", baseDir);
return false;
}
final String resourceFileName = "sample.c";
ClassLoader classLoader = CtagsUtil.class.getClassLoader();
try (InputStream inputStream = classLoader.getResourceAsStream(resourceFileName)) {
if (inputStream == null) {
LOGGER.log(Level.SEVERE, "cannot get resource URL of ''{0}'' for ctags check",
resourceFileName);
return false;
}
Files.copy(inputStream, inputPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "cannot copy ''{0}'' to ''{1}'' for ctags check: {2}",
new Object[]{resourceFileName, inputPath, e});
return false;
}
Ctags ctags = new Ctags();
try {
Definitions definitions = ctags.doCtags(inputPath.toString());
if (definitions != null && definitions.numberOfSymbols() > 1) {
return true;
}
} catch (IOException | InterruptedException e) {
LOGGER.log(Level.SEVERE, "cannot determine whether ctags can produce definitions", e);
} finally {
ctags.close();
try {
Files.delete(inputPath);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "cannot delete ''{0}''", inputPath);
}
}
return false;
| 1,313
| 445
| 1,758
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/ErrorMessageCollector.java
|
ErrorMessageCollector
|
finisher
|
class ErrorMessageCollector implements Collector<String, StringJoiner, Optional<String>> {
private final String prefix;
private final String emptyString;
private final boolean returnNullWhenEmpty;
/**
* Creates a collector with given prefix and
* returns optional empty for empty collection.
* @param prefix prefix before the joined string
*/
public ErrorMessageCollector(@NotNull String prefix) {
Objects.requireNonNull(prefix);
this.prefix = prefix;
this.emptyString = "";
this.returnNullWhenEmpty = true;
}
/**
* Creates a string joiner with given prefix and empty string.
* @param prefix prefix before the joined string
* @param emptyString string to display if collection is empty
*/
public ErrorMessageCollector(@NotNull String prefix, @NotNull String emptyString) {
Objects.requireNonNull(prefix);
Objects.requireNonNull(emptyString);
this.prefix = prefix;
this.emptyString = emptyString;
this.returnNullWhenEmpty = false;
}
/**
* A function that creates and returns a new mutable result container.
*
* @return a function which returns a new, mutable result container
*/
@Override
public Supplier<StringJoiner> supplier() {
return () -> {
var joiner = new StringJoiner(", ", prefix, "");
joiner.setEmptyValue(emptyString);
return joiner;
};
}
/**
* A function that folds a value into a mutable result container.
*
* @return a function which folds a value into a mutable result container
*/
@Override
public BiConsumer<StringJoiner, String> accumulator() {
return StringJoiner::add;
}
/**
* A function that accepts two partial results and merges them. The
* combiner function may fold state from one argument into the other and
* return that, or may return a new result container.
*
* @return a function which combines two partial results into a combined
* result
*/
@Override
public BinaryOperator<StringJoiner> combiner() {
return StringJoiner::merge;
}
/**
* Perform the final transformation from the intermediate accumulation type
* {@code A} to the final result type {@code R}.
*
* <p>If the characteristic {@code IDENTITY_FINISH} is
* set, this function may be presumed to be an identity transform with an
* unchecked cast from {@code A} to {@code R}.
*
* @return a function which transforms the intermediate result to the final
* result
*/
@Override
public Function<StringJoiner, Optional<String>> finisher() {<FILL_FUNCTION_BODY>}
/**
* Returns a {@code Set} of {@code Collector.Characteristics} indicating
* the characteristics of this Collector. This set should be immutable.
*
* @return an immutable set of collector characteristics
*/
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
|
return stringJoiner ->
Optional.of(stringJoiner.toString())
.filter(msg -> !(msg.isEmpty() && returnNullWhenEmpty));
| 792
| 44
| 836
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/Executor.java
|
SpoolHandler
|
processStream
|
class SpoolHandler implements StreamHandler {
private final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
public byte[] getBytes() {
return bytes.toByteArray();
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
BufferedInputStream in = new BufferedInputStream(input);
byte[] buffer = new byte[8092];
int len;
while ((len = in.read(buffer)) != -1) {
if (len > 0) {
bytes.write(buffer, 0, len);
}
}
| 79
| 85
| 164
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/FileExtraZipper.java
|
FileExtraZipper
|
zip
|
class FileExtraZipper {
/**
* Merge the specified lists by looking up a possible entry in
* {@code extras} for every element in {@code entries}.
*
* @param entries list of {@link DirectoryEntry} instances
* @param extras some OpenGrok-analyzed extra metadata
*/
public void zip(List<DirectoryEntry> entries, List<NullableNumLinesLOC> extras) {<FILL_FUNCTION_BODY>}
private NullableNumLinesLOC findExtra(Map<String, NullableNumLinesLOC> byName, File fileobj) {
String key = fileobj.getName();
return byName.get(key);
}
private Map<String, NullableNumLinesLOC> indexExtraByName(List<NullableNumLinesLOC> extras) {
Map<String, NullableNumLinesLOC> byPath = new HashMap<>();
for (NullableNumLinesLOC extra : extras) {
if (extra.getPath() != null) {
File f = new File(extra.getPath());
String filename = f.getName();
byPath.put(filename, extra);
}
}
return byPath;
}
}
|
if (extras == null) {
return;
}
Map<String, NullableNumLinesLOC> byName = indexExtraByName(extras);
for (DirectoryEntry entry : entries) {
NullableNumLinesLOC extra = findExtra(byName, entry.getFile());
entry.setExtra(extra);
}
| 305
| 91
| 396
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/Getopt.java
|
Option
|
parse
|
class Option {
char optOption;
String argument;
}
private final List<Option> options;
private int current;
private int optind;
private final String[] argv;
private final String opts;
/**
* Creates a new instance of Getopt.
* @param argv argument vector
* @param opts the list of allowed options
*/
public Getopt(String[] argv, String opts) {
options = new ArrayList<>();
current = -1;
optind = -1;
this.argv = argv.clone();
this.opts = opts;
}
/**
* Parse the command line options.
* @throws ParseException if an illegal argument is passed
*/
public void parse() throws ParseException {<FILL_FUNCTION_BODY>
|
int ii = 0;
while (ii < argv.length) {
char[] chars = argv[ii].toCharArray();
if (chars.length > 0 && chars[0] == '-') {
if (argv[ii].equals("--")) {
// End of command line options ;)
optind = ii + 1;
break;
}
for (int jj = 1; jj < chars.length; ++jj) {
int idx = opts.indexOf(chars[jj]);
if (idx == -1) {
throw new ParseException("Unknown argument: " + argv[ii].substring(jj), ii);
}
Option option = new Option();
option.optOption = chars[jj];
options.add(option);
// does this option take an argument?
if ((idx + 1) < opts.length() && (opts.charAt(idx + 1) == ':')) {
// next should be an argument
if ((jj + 1) < chars.length) {
// Rest of this is the argument
option.argument = argv[ii].substring(jj + 1);
break;
}
// next argument vector contains the argument
++ii;
if (ii < argv.length) {
option.argument = argv[ii];
} else {
throw new ParseException("Option " + chars[jj] + " requires an argument", ii);
}
}
}
++ii;
} else {
// End of options
optind = ii;
break;
}
}
| 211
| 413
| 624
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/HeadHandler.java
|
HeadHandler
|
processStream
|
class HeadHandler implements Executor.StreamHandler {
private final int maxLines;
private final List<String> lines = new ArrayList<>();
private final Charset charset;
private static final int BUFFERED_READER_SIZE = 200;
/**
* Charset of the underlying reader is set to UTF-8.
* @param maxLines maximum number of lines to store
*/
public HeadHandler(int maxLines) {
this.maxLines = maxLines;
this.charset = StandardCharsets.UTF_8;
}
/**
* @param maxLines maximum number of lines to store
* @param charset character set
*/
public HeadHandler(int maxLines, Charset charset) {
this.maxLines = maxLines;
this.charset = charset;
}
/**
* @return number of lines read
*/
public int count() {
return lines.size();
}
/**
* @param index index
* @return line at given index. Will be non {@code null} for valid index.
*/
public String get(int index) {
return lines.get(index);
}
// for testing
static int getBufferedReaderSize() {
return BUFFERED_READER_SIZE;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try (BufferedInputStream bufStream = new BufferedInputStream(input);
BufferedReader reader = new BufferedReader(new InputStreamReader(bufStream, this.charset),
BUFFERED_READER_SIZE)) {
int lineNum = 0;
while (lineNum < maxLines) {
String line = reader.readLine();
if (line == null) { // EOF
return;
}
lines.add(line);
lineNum++;
}
// Read and forget the rest.
byte[] buf = new byte[1024];
while ((bufStream.read(buf)) != -1) {
;
}
}
| 366
| 173
| 539
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/HostUtil.java
|
HostUtil
|
isReachable
|
class HostUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HostUtil.class);
private HostUtil() {
// private to enforce static
}
/**
* @param urlStr URI
* @return port number
* @throws URISyntaxException on error
*/
public static int urlToPort(String urlStr) throws URISyntaxException {
URI uri = new URI(urlStr);
return uri.getPort();
}
private static boolean isWebAppReachable(String webappURI, int timeOutSeconds, @Nullable String token) {
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
clientBuilder.connectTimeout(timeOutSeconds, TimeUnit.SECONDS);
clientBuilder.readTimeout(timeOutSeconds, TimeUnit.SECONDS);
// Here, IndexerUtil#getWebAppHeaders() is not used because at the point this method is called,
// the RuntimeEnvironment configuration used by getWebAppHeaders() is not set yet.
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
if (token != null) {
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
}
LOGGER.log(Level.FINE, "checking reachability of {0} with connect/read timeout of {1} seconds",
new Object[]{webappURI, timeOutSeconds});
try (Client client = clientBuilder.build()) {
Response response = client
.target(webappURI)
.path("api")
.path("v1")
.path("system")
.path("ping")
.request()
.headers(headers)
.get();
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
LOGGER.log(Level.SEVERE, "cannot reach OpenGrok web application on {0}: {1}",
new Object[]{webappURI, response.getStatusInfo()});
return false;
}
} catch (ProcessingException e) {
LOGGER.log(Level.SEVERE, String.format("could not connect to %s", webappURI), e);
return false;
}
return true;
}
/**
*
* @param webappURI URI of the web app
* @param timeOutSeconds connect/read timeout in seconds
* @param token authentication token, can be {@code null}
* @return whether web app is reachable within given timeout on given URI
*/
public static boolean isReachable(String webappURI, int timeOutSeconds, @Nullable String token) {<FILL_FUNCTION_BODY>}
}
|
boolean connectWorks = false;
try {
int port = HostUtil.urlToPort(webappURI);
if (port <= 0) {
LOGGER.log(Level.SEVERE, () -> "invalid port number for " + webappURI);
return false;
}
return isWebAppReachable(webappURI, timeOutSeconds, token);
} catch (URISyntaxException e) {
LOGGER.log(Level.SEVERE, String.format("URI not valid: %s", webappURI), e);
}
return connectWorks;
| 679
| 150
| 829
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/LazilyInstantiate.java
|
LazilyInstantiate
|
swapper
|
class LazilyInstantiate<T> implements Supplier<T> {
private final Supplier<T> supplier;
private Supplier<T> current;
private volatile boolean active;
public static <T> LazilyInstantiate<T> using(Supplier<T> supplier) {
return new LazilyInstantiate<>(supplier);
}
/**
* Executes the {@link #using(java.util.function.Supplier)} supplier in a
* thread-safe manner if it has not yet been executed, and keeps the result
* to provide to every caller of this method.
* @return the result of {@code supplier}
*/
@Override
public T get() {
return current.get();
}
/**
* Gets a value indicating if the instance is active and no longer
* technically lazy, since {@link #get()} has been called.
*/
public boolean isActive() {
return active;
}
private LazilyInstantiate(Supplier<T> supplier) {
this.supplier = supplier;
this.current = this::swapper;
}
/**
* Swaps itself out for a supplier of an instantiated object.
*/
private synchronized T swapper() {<FILL_FUNCTION_BODY>}
private static class Factory<U> implements Supplier<U> {
private final U obj;
Factory(U obj) {
this.obj = obj;
}
@Override
public U get() {
return obj;
}
}
}
|
if (!(current instanceof Factory)) {
T obj = supplier.get();
current = new Factory<>(obj);
active = true;
}
return current.get();
| 399
| 48
| 447
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/LineBreaker.java
|
LineBreaker
|
reset
|
class LineBreaker {
private static final String RESET_FAILED_MSG = "reset() did not succeed";
private int length;
private int count;
private int[] lineOffsets;
/**
* Calls
* {@link #reset(org.opengrok.indexer.analysis.StreamSource, org.opengrok.indexer.util.ReaderWrapper)}
* with {@code src} and {@code null}.
* @param src a defined instance
* @throws java.io.IOException if an I/O error occurs
*/
public void reset(StreamSource src) throws IOException {
reset(src, null);
}
/**
* Resets the breaker using the specified inputs.
* @param src a defined instance
* @param wrapper an optional instance
* @throws java.io.IOException if an I/O error occurs
*/
public void reset(StreamSource src, ReaderWrapper wrapper)
throws IOException {
if (src == null) {
throw new IllegalArgumentException("`src' is null");
}
SplitterUtil.reset(this::reset, src, wrapper);
}
private void reset(Reader reader) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Gets the number of characters in the original source document.
* @return value
*/
public int originalLength() {
return length;
}
/**
* Gets the number of split lines.
*/
public int count() {
if (lineOffsets == null) {
throw new IllegalStateException(RESET_FAILED_MSG);
}
return count;
}
/**
* Gets the starting document character offset of the line at the
* specified index in the lines list.
* @param index greater than or equal to zero and less than or equal to
* {@link #count()}
* @return line starting offset
* @throws IllegalArgumentException if {@code index} is out of bounds
*/
public int getOffset(int index) {
if (lineOffsets == null) {
throw new IllegalStateException(RESET_FAILED_MSG);
}
if (index < 0 || index >= lineOffsets.length) {
throw new IllegalArgumentException("index is out of bounds");
}
return lineOffsets[index];
}
/**
* Find the line index for the specified document offset.
* @param offset greater than or equal to zero and less than
* {@link #originalLength()}.
* @return -1 if {@code offset} is beyond the document bounds; otherwise,
* a valid index
*/
public int findLineIndex(int offset) {
if (lineOffsets == null) {
throw new IllegalStateException(RESET_FAILED_MSG);
}
return SplitterUtil.findLineIndex(length, lineOffsets, offset);
}
}
|
length = 0;
lineOffsets = null;
List<Long> newOffsets = new ArrayList<>();
LineBreakerScanner scanner = new LineBreakerScanner(reader);
scanner.setTarget(newOffsets);
scanner.consume();
long fullLength = scanner.getLength();
/*
* Lucene cannot go past Integer.MAX_VALUE so revise the length to fit
* within the Integer constraint.
*/
length = fullLength > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) fullLength;
count = newOffsets.size() - 1;
lineOffsets = new int[newOffsets.size()];
for (int i = 0; i < lineOffsets.length; ++i) {
long fullOffset = newOffsets.get(i);
if (fullOffset <= Integer.MAX_VALUE) {
lineOffsets[i] = (int) fullOffset;
} else {
/*
* Lucene cannot go past Integer.MAX_VALUE so revise the line
* breaks to fit within the Integer constraint, and stop.
*/
lineOffsets[i] = Integer.MAX_VALUE;
lineOffsets = Arrays.copyOf(lineOffsets, i + 1);
count -= newOffsets.size() - lineOffsets.length;
break;
}
}
| 727
| 343
| 1,070
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/NumberUtil.java
|
NumberUtil
|
tryParseLong
|
class NumberUtil {
/**
* Parses the specified {@code value} without throwing a checked exception.
*/
public static Long tryParseLong(String value) {<FILL_FUNCTION_BODY>}
/* private to enforce static */
private NumberUtil() {
}
}
|
if (value == null) {
return null;
}
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
return null;
}
| 75
| 53
| 128
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/PathUtils.java
|
PathUtils
|
getRelativeToCanonical
|
class PathUtils {
private static final Logger LOGGER =
LoggerFactory.getLogger(PathUtils.class);
/**
* Calls {@link #getRelativeToCanonical(Path, Path, Set, Set)}
* with {@code path}, {@code canonical}, {@code allowedSymlinks=null}, and
* {@code canonicalRoots=null} (to disable validation of links).
* @param path a non-canonical (or canonical) path to compare
* @param canonical a canonical path to compare against
* @return a relative path determined as described -- or {@code path} if no
* canonical relativity is found.
* @throws IOException if an error occurs determining canonical paths
* for portions of {@code path}
*/
public static String getRelativeToCanonical(Path path, Path canonical)
throws IOException {
try {
return getRelativeToCanonical(path, canonical, null, null);
} catch (ForbiddenSymlinkException e) {
// should not get here with allowedSymlinks==null
return path.toString();
}
}
/**
* Determine a relative path comparing {@code path} to {@code canonical},
* with an algorithm that can handle the possibility of one or more
* symbolic links as components of {@code path}.
* <p>
* When {@code allowedSymlinks} is not null, any symbolic links as
* components of {@code path} (below {@code canonical}) are required to
* match an element of {@code allowedSymlinks} or target a canonical child
* of an element of {@code allowedSymlinks}.
* <p>
* E.g., with {@code path="/var/opengrok/src/proj_a"} and
* {@code canonical="/private/var/opengrok/src"} where /var is linked to
* /private/var and where /var/opengrok/src/proj_a is linked to /proj/a,
* the function will return {@code "proj_a"} as a relative path.
* <p>
* The algorithm will have evaluated canonical paths upward from
* (non-canonical) /var/opengrok/src/proj_a (a.k.a. /proj/a) to find a
* canonical similarity at /var/opengrok/src (a.k.a.
* /private/var/opengrok/src).
* @param path a non-canonical (or canonical) path to compare
* @param canonical a canonical path to compare against
* @param allowedSymlinks optional set of allowed symbolic links, so that
* any links encountered within {@code path} and not covered by the set (or
* whitelisted in a defined {@code canonicalRoots}) will abort the algorithm
* @param canonicalRoots optional set of allowed canonicalRoots, so that
* any checks done because of a defined {@code allowedSymlinks} will first
* check against the whitelist of canonical roots and possibly short-circuit
* the explicit validation against {@code allowedSymlinks}.
* @return a relative path determined as described above -- or {@code path}
* if no canonical relativity is found
* @throws ForbiddenSymlinkException if symbolic-link checking is active
* and it encounters an ineligible link
* @throws InvalidPathException if path cannot be decoded
*/
public static String getRelativeToCanonical(Path path, Path canonical,
Set<String> allowedSymlinks, Set<String> canonicalRoots)
throws IOException, ForbiddenSymlinkException, InvalidPathException {<FILL_FUNCTION_BODY>}
private static boolean isAllowedSymlink(Path canonicalFile,
Set<String> allowedSymlinks) {
final FileSystem fileSystem = canonicalFile.getFileSystem();
String canonicalFileStr = canonicalFile.toString();
for (String allowedSymlink : allowedSymlinks) {
String canonicalLink;
try {
canonicalLink = fileSystem.getPath(allowedSymlink).toRealPath().toString();
} catch (IOException e) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(String.format("unresolvable symlink: '%s'", allowedSymlink));
}
continue;
}
if (canonicalFileStr.equals(canonicalLink) ||
canonicalFile.startsWith(canonicalLink + fileSystem.getSeparator())) {
return true;
}
}
return false;
}
private static boolean isWhitelisted(String canonical, Set<String> canonicalRoots) {
if (canonicalRoots != null) {
for (String canonicalRoot : canonicalRoots) {
if (canonical.startsWith(canonicalRoot)) {
return true;
}
}
}
return false;
}
/** Private to enforce static. */
private PathUtils() {
}
}
|
if (path.equals(canonical)) {
return "";
}
// The following fixup of \\ is really to allow
// IndexDatabaseTest.testGetDefinitions() to succeed on Linux or macOS.
// That test has an assertion that operation is the "same for windows
// delimiters" and passes a path with backslashes. On Windows, the
// following fixup would not be needed, since File and Paths recognize
// backslash as a delimiter. On Linux and macOS, any backslash needs to
// be normalized.
final FileSystem fileSystem = path.getFileSystem();
final String separator = fileSystem.getSeparator();
String strPath = path.toString();
strPath = strPath.replace("\\", separator);
String strCanonical = canonical.toString();
strCanonical = strCanonical.replace("\\", separator);
String normCanonical = strCanonical.endsWith(separator) ?
strCanonical : strCanonical + separator;
Deque<String> tail = null;
Path iterPath = fileSystem.getPath(strPath);
while (iterPath != null) {
Path iterCanon;
try {
iterCanon = iterPath.toRealPath();
} catch (IOException e) {
iterCanon = iterPath.normalize().toAbsolutePath();
}
// optional symbolic-link check
if (Objects.nonNull(allowedSymlinks) && Files.isSymbolicLink(iterPath) &&
!isWhitelisted(iterCanon.toString(), canonicalRoots) &&
!isAllowedSymlink(iterCanon, allowedSymlinks)) {
String format = String.format("'%1$s' is prohibited symlink", iterPath);
LOGGER.finest(format);
throw new ForbiddenSymlinkException(format);
}
String rel = null;
if (iterCanon.startsWith(normCanonical)) {
rel = fileSystem.getPath(normCanonical).relativize(iterCanon).toString();
} else if (normCanonical.equals(iterCanon + separator)) {
rel = "";
}
if (rel != null) {
if (tail != null) {
while (!tail.isEmpty()) {
rel = Paths.get(rel, tail.pop()).toString();
}
}
return rel;
}
if (tail == null) {
tail = new LinkedList<>();
}
tail.push(Optional.ofNullable(iterPath.getFileName()).map(Path::toString).orElse(""));
iterPath = iterPath.getParent();
}
// `path' is not found to be relative to `canonical', so return as is.
return path.toString();
| 1,205
| 696
| 1,901
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/Progress.java
|
Progress
|
logIt
|
class Progress implements AutoCloseable {
private final Logger logger;
private final Long totalCount;
private final String suffix;
private final AtomicLong currentCount = new AtomicLong();
private final Map<Level, Integer> levelCountMap = new TreeMap<>(Comparator.comparingInt(Level::intValue).reversed());
private Thread loggerThread = null;
private volatile boolean run;
private final Level baseLogLevel;
private final Object sync = new Object();
/**
* @param logger logger instance
* @param suffix string suffix to identify the operation
*/
public Progress(Logger logger, String suffix) {
this(logger, suffix, -1, Level.INFO);
}
/**
* @param logger logger instance
* @param suffix string suffix to identify the operation
* @param logLevel base log level
*/
public Progress(Logger logger, String suffix, Level logLevel) {
this(logger, suffix, -1, logLevel);
}
/**
* @param logger logger instance
* @param suffix string suffix to identify the operation
* @param totalCount total count
*/
public Progress(Logger logger, String suffix, long totalCount) {
this(logger, suffix, totalCount, Level.INFO);
}
/**
* @param logger logger instance
* @param suffix string suffix to identify the operation
* @param totalCount total count
* @param logLevel base log level
*/
public Progress(Logger logger, String suffix, long totalCount, Level logLevel) {
this.logger = logger;
this.suffix = suffix;
this.baseLogLevel = logLevel;
if (totalCount < 0) {
this.totalCount = null;
} else {
this.totalCount = totalCount;
}
// Note: Level.CONFIG is missing as it does not make too much sense for progress reporting semantically.
final List<Level> standardLevels = Arrays.asList(Level.OFF, Level.SEVERE, Level.WARNING, Level.INFO,
Level.FINE, Level.FINER, Level.FINEST, Level.ALL);
int i = standardLevels.indexOf(baseLogLevel);
for (int num : new int[]{100, 50, 10, 1}) {
if (i >= standardLevels.size()) {
break;
}
Level level = standardLevels.get(i);
if (level == null) {
break;
}
levelCountMap.put(level, num);
if (num == 1) {
break;
}
i++;
}
// Assuming the printProgress configuration setting cannot be changed on the fly.
if (!baseLogLevel.equals(Level.OFF) && RuntimeEnvironment.getInstance().isPrintProgress()) {
spawnLogThread();
}
}
private void spawnLogThread() {
// spawn a logger thread.
run = true;
loggerThread = new Thread(this::logLoop,
"progress-thread-" + suffix.replace(" ", "_"));
loggerThread.start();
}
// for testing
Thread getLoggerThread() {
return loggerThread;
}
/**
* Increment counter. The actual logging will be done eventually.
*/
public void increment() {
this.currentCount.incrementAndGet();
if (loggerThread != null) {
// nag the thread.
synchronized (sync) {
sync.notifyAll();
}
}
}
private void logLoop() {
long cachedCount = 0;
Map<Level, Long> lastLoggedChunk = new HashMap<>();
while (true) {
long longCurrentCount = this.currentCount.get();
Level currentLevel = Level.FINEST;
// Do not log if there was no progress.
if (cachedCount < longCurrentCount) {
currentLevel = getLevel(lastLoggedChunk, longCurrentCount, currentLevel);
logIt(lastLoggedChunk, longCurrentCount, currentLevel);
}
if (!run) {
return;
}
cachedCount = longCurrentCount;
// wait for event
try {
synchronized (sync) {
if (!run) {
// Loop once more to do the final logging.
continue;
}
sync.wait();
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "logger thread interrupted");
}
}
}
@VisibleForTesting
Level getLevel(Map<Level, Long> lastLoggedChunk, long currentCount, Level currentLevel) {
// The intention is to log the initial and final count at the base log level.
if (currentCount <= 1 || (totalCount != null && currentCount == totalCount)) {
currentLevel = baseLogLevel;
} else {
// Set the log level based on the "buckets".
for (var entry : levelCountMap.entrySet()) {
if (lastLoggedChunk.getOrDefault(entry.getKey(), -1L) <
currentCount / entry.getValue()) {
currentLevel = entry.getKey();
break;
}
}
}
return currentLevel;
}
private void logIt(Map<Level, Long> lastLoggedChunk, long currentCount, Level currentLevel) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
if (loggerThread == null) {
return;
}
try {
run = false;
synchronized (sync) {
sync.notifyAll();
}
loggerThread.join();
} catch (InterruptedException e) {
logger.log(Level.WARNING, "logger thread interrupted");
}
}
}
|
if (logger.isLoggable(currentLevel)) {
lastLoggedChunk.put(currentLevel, currentCount / levelCountMap.get(currentLevel));
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Progress: ");
stringBuilder.append(currentCount);
stringBuilder.append(" ");
if (totalCount != null) {
stringBuilder.append("(");
stringBuilder.append(String.format("%.2f", currentCount * 100.0f / totalCount));
stringBuilder.append("%) ");
}
stringBuilder.append(suffix);
logger.log(currentLevel, stringBuilder.toString());
}
| 1,465
| 170
| 1,635
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/RainbowColorGenerator.java
|
RainbowColorGenerator
|
generateLinearColorSequence
|
class RainbowColorGenerator {
private static final int COLORS_BETWEEN_ANCHORS = 4;
private static final Color[] STOP_COLORS = new Color[]{
fromHex("eaffe2"),
fromHex("d9e4f9"),
fromHex("d1d1d1"),
fromHex("fffbcf"),
fromHex("ffbfc3"),
};
private RainbowColorGenerator() {
}
/**
* Get linear sequence for all stop colors.
*
* @return the list of colors
* @see #STOP_COLORS
* @see #COLORS_BETWEEN_ANCHORS
*/
public static List<Color> getOrderedColors() {
return generateLinearColorSequence(Arrays.asList(STOP_COLORS), COLORS_BETWEEN_ANCHORS);
}
/**
* Generate linear color sequence between given stop colors as {@code anchorColors}
* and with {@code colorsBetweenAnchors} number of intermediary steps between them.
*
* @param anchorColors the stop colors
* @param colorsBetweenAnchors number of steps between each pair of stop colors
* @return the list of colors
*/
public static List<Color> generateLinearColorSequence(List<? extends Color> anchorColors, int colorsBetweenAnchors) {<FILL_FUNCTION_BODY>}
/**
* Generate linear color sequence between two given colors.
*
* @param color1 the first color (to be included in the sequence)
* @param color2 the last color (to be included in the sequence)
* @param colorsBetweenAnchors number of colors between the two colors
* @return the list of colors
*/
public static List<Color> generateLinearColorSequence(Color color1, Color color2, int colorsBetweenAnchors) {
assert colorsBetweenAnchors >= 0;
List<Color> result = new ArrayList<>(colorsBetweenAnchors + 2);
result.add(color1);
for (int i = 1; i <= colorsBetweenAnchors; i++) {
float ratio = (float) i / (colorsBetweenAnchors + 1);
result.add(new Color(
ratio(color1.red, color2.red, ratio),
ratio(color1.green, color2.green, ratio),
ratio(color1.blue, color2.blue, ratio)
));
}
result.add(color2);
return result;
}
private static int ratio(int val1, int val2, float ratio) {
int value = (int) (val1 + (val2 - val1) * ratio);
return Math.max(Math.min(value, 255), 0);
}
}
|
assert colorsBetweenAnchors >= 0;
if (anchorColors.size() == 1) {
return Collections.singletonList(anchorColors.get(0));
}
int segmentCount = anchorColors.size() - 1;
List<Color> result = new ArrayList<>(anchorColors.size() + segmentCount * colorsBetweenAnchors);
result.add(anchorColors.get(0));
for (int i = 0; i < segmentCount; i++) {
Color color1 = anchorColors.get(i);
Color color2 = anchorColors.get(i + 1);
List<Color> linearColors = generateLinearColorSequence(color1, color2, colorsBetweenAnchors);
// skip first element from sequence to avoid duplication from connected segments
result.addAll(linearColors.subList(1, linearColors.size()));
}
return result;
| 719
| 235
| 954
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/SourceSplitter.java
|
SourceSplitter
|
reset
|
class SourceSplitter {
private static final String RESET_FAILED_MSG = "reset() did not succeed";
private int length;
private String[] lines;
private int[] lineOffsets;
/**
* Gets the number of characters in the original source document.
*/
public int originalLength() {
return length;
}
/**
* Gets the number of split lines.
*/
public int count() {
if (lines == null) {
throw new IllegalStateException(RESET_FAILED_MSG);
}
return lines.length;
}
/**
* Gets the line at the specified index in the lines list.
* @param index greater than or equal to zero and less than
* {@link #count()}
* @return defined instance
* @throws IllegalArgumentException if {@code index} is out of bounds
*/
public String getLine(int index) {
if (lines == null) {
throw new IllegalStateException(RESET_FAILED_MSG);
}
if (index < 0 || index >= lines.length) {
throw new IllegalArgumentException("index is out of bounds");
}
return lines[index];
}
/**
* Gets the starting document character offset of the line at the
* specified index in the lines list.
* @param index greater than or equal to zero and less than or equal to
* {@link #count()}
* @return line starting offset
* @throws IllegalArgumentException if {@code index} is out of bounds
*/
public int getOffset(int index) {
if (lineOffsets == null) {
throw new IllegalStateException(RESET_FAILED_MSG);
}
if (index < 0 || index >= lineOffsets.length) {
throw new IllegalArgumentException("index is out of bounds");
}
return lineOffsets[index];
}
/**
* Find the line index for the specified document offset.
* @param offset greater than or equal to zero and less than
* {@link #originalLength()}.
* @return -1 if {@code offset} is beyond the document bounds; otherwise,
* a valid index
*/
public int findLineIndex(int offset) {
if (lineOffsets == null) {
throw new IllegalStateException(RESET_FAILED_MSG);
}
return SplitterUtil.findLineIndex(length, lineOffsets, offset);
}
/**
* Reset the splitter to use the specified content.
* @param original a defined instance
*/
public void reset(String original) {
if (original == null) {
throw new IllegalArgumentException("`original' is null");
}
try {
reset(new StringReader(original));
} catch (IOException ex) {
/*
* Should not get here, as String and StringReader operations cannot
* throw IOException.
*/
throw new WrapperIOException(ex);
}
}
/**
* Calls
* {@link #reset(org.opengrok.indexer.analysis.StreamSource, org.opengrok.indexer.util.ReaderWrapper)}
* with {@code src} and {@code null}.
* @param src a defined instance
* @throws java.io.IOException if an I/O error occurs
*/
public void reset(StreamSource src) throws IOException {
reset(src, null);
}
/**
* Reset the splitter to use the specified inputs.
* @param src a defined instance
* @param wrapper an optional instance
* @throws java.io.IOException if an I/O error occurs
*/
public void reset(StreamSource src, ReaderWrapper wrapper)
throws IOException {<FILL_FUNCTION_BODY>}
private void reset(Reader reader) throws IOException {
length = 0;
lines = null;
lineOffsets = null;
List<String> slist = new ArrayList<>();
SourceSplitterScanner scanner = new SourceSplitterScanner(reader);
scanner.setTarget(slist);
scanner.consume();
long fullLength = scanner.getLength();
/*
* Lucene cannot go past Integer.MAX_VALUE so revise the length to fit
* within the Integer constraint.
*/
length = fullLength > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) fullLength;
lines = slist.toArray(new String[0]);
setLineOffsets();
}
private void setLineOffsets() {
/*
* Add one more entry for lineOffsets so that findLineIndex() can
* easily work on the last line.
*/
lineOffsets = new int[lines.length + 1];
int offset = 0;
for (int i = 0; i < lineOffsets.length; ++i) {
lineOffsets[i] = offset;
if (i < lines.length) {
offset += lines[i].length();
}
}
}
}
|
if (src == null) {
throw new IllegalArgumentException("`src' is null");
}
SplitterUtil.reset(this::reset, src, wrapper);
| 1,259
| 46
| 1,305
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/SplitterUtil.java
|
SplitterUtil
|
reset
|
class SplitterUtil {
@FunctionalInterface
interface Resetter {
void reset(Reader reader) throws IOException;
}
/**
* Find the line index for the specified document offset.
* @param offset greater than or equal to zero and less than
* {@code length}.
* @return -1 if {@code offset} is beyond the document bounds; otherwise,
* a valid index
*/
static int findLineIndex(int length, int[] lineOffsets, int offset) {
if (lineOffsets == null) {
throw new IllegalArgumentException("lineOffsets");
}
if (offset < 0 || offset > length) {
return -1;
}
int lo = 0;
int hi = lineOffsets.length - 1;
int mid;
while (lo <= hi) {
mid = lo + (hi - lo) / 2;
int lineLength = (mid + 1 < lineOffsets.length ? lineOffsets[mid + 1] : length) -
lineOffsets[mid];
if (offset < lineOffsets[mid]) {
hi = mid - 1;
} else if (lineLength == 0 && offset == lineOffsets[mid]) {
return mid;
} else if (offset >= lineOffsets[mid] + lineLength) {
lo = mid + 1;
} else {
return mid;
}
}
return -1;
}
/**
* Resets the breaker using the specified inputs.
* @param resetter a defined instance
* @param src a defined instance
* @param wrapper an optional instance
* @throws java.io.IOException if an I/O error occurs
*/
static void reset(Resetter resetter, StreamSource src, ReaderWrapper wrapper)
throws IOException {<FILL_FUNCTION_BODY>}
/* private to enforce static. */
private SplitterUtil() {
}
}
|
if (src == null) {
throw new IllegalArgumentException("src is null");
}
try (InputStream in = src.getStream();
Reader rdr = IOUtils.createBOMStrippedReader(in, StandardCharsets.UTF_8.name())) {
Reader intermediate = null;
if (wrapper != null) {
intermediate = wrapper.get(rdr);
}
try (BufferedReader brdr = new BufferedReader(intermediate != null ?
intermediate : rdr)) {
resetter.reset(brdr);
} finally {
if (intermediate != null) {
intermediate.close();
}
}
}
| 483
| 171
| 654
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/Statistics.java
|
Statistics
|
logIt
|
class Statistics {
private final Instant startTime;
public Statistics() {
startTime = Instant.now();
}
/**
* Log a message with duration using provided logger if the supplied log level is active.
* @param logger logger instance
* @param logLevel log level
* @param msg message string
* @param duration duration to report
* @return whether logging was performed
*/
private boolean logIt(Logger logger, Level logLevel, String msg, Duration duration) {<FILL_FUNCTION_BODY>}
/**
* Log a message along with how much time it took since the constructor was called.
* @param logger logger instance
* @param logLevel log level
* @param msg message string
* @return whether logging was performed
*/
public boolean report(Logger logger, Level logLevel, String msg) {
return logIt(logger, logLevel, msg, Duration.between(startTime, Instant.now()));
}
/**
* Log a message along with how much time it took since the constructor was called.
* If there is a metrics registry, it will update the timer specified by the meter name.
* @param logger logger instance
* @param logLevel log level
* @param msg message string
* @param meterName name of the meter
* @return whether logging was performed
* @see Metrics#getRegistry()
*/
public boolean report(Logger logger, Level logLevel, String msg, String meterName) {
return report(logger, logLevel, msg, meterName, new String[]{});
}
/**
* Log a message along with how much time it took since the constructor was called.
* If there is a metrics registry, it will update the timer specified by the meter name.
* @param logger logger instance
* @param logLevel log level
* @param msg message string
* @param meterName name of the meter
* @param tags array of tags for the meter
* @return whether logging was performed
* @see Metrics#getRegistry()
*/
public boolean report(Logger logger, Level logLevel, String msg, String meterName, String[] tags) {
Duration duration = Duration.between(startTime, Instant.now());
boolean ret = logIt(logger, logLevel, msg, duration);
MeterRegistry registry = Metrics.getRegistry();
if (registry != null) {
Timer.builder(meterName).
tags(tags).
register(registry).
record(duration);
}
return ret;
}
/**
* Log a message along with how much time it took since the constructor was called.
* If there is a metrics registry, it will update the timer specified by the meter name.
* The log level is {@code INFO}.
* @param logger logger instance
* @param msg message string
* @param meterName name of the meter
* @return whether logging was performed
*/
public boolean report(Logger logger, String msg, String meterName) {
return report(logger, Level.INFO, msg, meterName);
}
/**
* log a message along with how much time it took since the constructor was called.
* The log level is {@code INFO}.
* @param logger logger instance
* @param msg message string
* @return whether logging was performed
*/
public boolean report(Logger logger, String msg) {
return report(logger, Level.INFO, msg);
}
}
|
if (logger.isLoggable(logLevel)) {
String timeStr = StringUtils.getReadableTime(duration.toMillis());
logger.log(logLevel, String.format("%s (took %s)", launderLog(msg), timeStr));
return true;
}
return false;
| 859
| 80
| 939
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/TandemFilename.java
|
TandemFilename
|
maybePackSha
|
class TandemFilename {
private static final int MAX_BYTES = 255;
/**
* One fewer than {@link #MAX_BYTES} as a cap for simple concatenation to
* avoid the possibility of easily fabricating a collision against this
* algorithm. I.e., a 255 byte tandem filename will always include a
* computed hash and not just be the concatenation of original filename
* plus new extension.
*/
private static final int MAX_CAT_BYTES = MAX_BYTES - 1;
/**
* "Instances of Base64.Encoder class are safe for use by multiple
* concurrent threads." --Oracle.
*/
private static final Base64.Encoder encoder = Base64.getUrlEncoder();
/** Private to enforce static. */
private TandemFilename() {
}
/**
* Appends an ASCII extension to the specified {@code filename}, truncating
* and packing in a SHA-256 hash if the UTF-8 encoding would exceed 254
* bytes and arriving at a final size of 255 bytes in that special case.
* @param filename a defined instance
* @param asciiExtension a defined instance that is expected to be only
* ASCII so that its UTF-8 form is the same length
* @return a transformed filename whose UTF-8 encoding is not more than 255
* bytes.
* @throws IllegalArgumentException thrown if {@code filename} has a
* parent or if {@code asciiExtension} is too long to allow packing a
* SHA-256 hash in the transformation.
*/
public static String join(String filename, String asciiExtension) {
File file = new File(filename);
if (file.getParent() != null) {
throw new IllegalArgumentException("filename can't have parent");
}
/*
* If the original filename length * 4 (for longest possible UTF-8
* encoding) plus asciiExtension length is not greater than one less
* than 255, then quickly return the concatenation.
*/
if (filename.length() * 4 + asciiExtension.length() <= MAX_CAT_BYTES) {
return filename + asciiExtension;
}
return maybePackSha(filename, asciiExtension);
}
private static String maybePackSha(String filename, String asciiExtension) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("java:S112")
private static String sha256base64(String value) {
MessageDigest hasher;
try {
hasher = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
/*
* This will not happen since "Every implementation of the Java
* platform is required to support the following standard
* MessageDigest algorithms: MD5, SHA-1, SHA-256."
*/
throw new RuntimeException(e);
}
byte[] digest = hasher.digest(value.getBytes(StandardCharsets.UTF_8));
return encoder.encodeToString(digest);
}
}
|
byte[] uFilename = filename.getBytes(StandardCharsets.UTF_8);
int nBytes = uFilename.length;
if (nBytes + asciiExtension.length() <= MAX_CAT_BYTES) {
// Here the UTF-8 encoding already allows for the new extension.
return filename + asciiExtension;
}
/*
* If filename has an ASCII extension already (of a reasonable length),
* shift it to the new asciiExtension so that it won't be overwritten
* by the packed hash.
*/
int pos = filename.lastIndexOf('.');
int extLength = filename.length() - pos;
if (pos >= 0 && extLength < 30 && extLength > 1) {
int i;
for (i = pos + 1; i < filename.length(); ++i) {
char ch = filename.charAt(i);
if (!Character.isLetterOrDigit(ch) || ch > 'z') {
break;
}
}
if (i >= filename.length()) {
// By this point, we affirmed a letters/numbers extension.
asciiExtension = filename.substring(pos) + asciiExtension;
filename = filename.substring(0, pos);
uFilename = filename.getBytes(StandardCharsets.UTF_8);
nBytes = uFilename.length;
}
}
// Pack the hash just before the file extension.
asciiExtension = sha256base64(filename) + asciiExtension;
/*
* Now trim the filename by code points until the full UTF-8 encoding
* fits within MAX_BYTES.
*/
int newLength = filename.length();
while (nBytes + asciiExtension.length() > MAX_BYTES) {
int cp = filename.codePointBefore(newLength);
int nChars = Character.charCount(cp);
String c = filename.substring(newLength - nChars, newLength);
nBytes -= c.getBytes(StandardCharsets.UTF_8).length;
newLength -= nChars;
if (newLength <= 0) {
throw new IllegalArgumentException("asciiExtension too long");
}
}
// Pad if necessary to exactly MAX_BYTES.
if (nBytes + asciiExtension.length() != MAX_BYTES) {
char[] pad = new char[MAX_BYTES - nBytes - asciiExtension.length()];
Arrays.fill(pad, '_');
asciiExtension = new String(pad) + asciiExtension;
}
return filename.substring(0, newLength) + asciiExtension;
| 812
| 685
| 1,497
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/TandemPath.java
|
TandemPath
|
join
|
class TandemPath {
/** Private to enforce static. */
private TandemPath() {
}
/**
* Appends an ASCII extension to the specified {@code filePath}, truncating
* and packing in a SHA-256 hash if the UTF-8 encoding of the filename
* component of the path would exceed 254 bytes and arriving at a final
* size of 255 bytes in that special case.
* @param filePath a defined instance
* @param asciiExtension a defined instance that is expected to be only
* ASCII so that its UTF-8 form is the same length
* @return a transformed path whose filename component's UTF-8 encoding is
* not more than 255 bytes.
* @throws IllegalArgumentException {@code asciiExtension} is too long to
* allow packing a SHA-256 hash in the transformation.
*/
public static String join(String filePath, String asciiExtension) {<FILL_FUNCTION_BODY>}
}
|
File file = new File(filePath);
String newName = TandemFilename.join(file.getName(), asciiExtension);
File newFile = new File(file.getParent(), newName);
return newFile.getPath();
| 258
| 64
| 322
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/UriUtils.java
|
TrimUriResult
|
trimUri
|
class TrimUriResult {
private final String uri;
private final int pushBackCount;
TrimUriResult(String uri, int pushBackCount) {
this.uri = uri;
this.pushBackCount = pushBackCount;
}
public String getUri() {
return uri;
}
public int getPushBackCount() {
return pushBackCount;
}
}
/**
* Trims a URI, specifying whether to enlist the
* {@link StringUtils#countURIEndingPushback(String)} algorithm or the
* {@link StringUtils#countPushback(String, Pattern)} or both.
* <p>
* If the pushback count is equal to the length of {@code url}, then the
* pushback is set to zero -- in order to avoid a never-ending lexical loop.
*
* @param uri the URI string
* @param shouldCheckEnding a value indicating whether to call
* {@link StringUtils#countURIEndingPushback(String)}
* @param collateralCapture optional pattern to call with
* {@link StringUtils#countPushback(String, Pattern)}
* @return a defined instance
*/
public static TrimUriResult trimUri(String uri, boolean shouldCheckEnding,
Pattern collateralCapture) {<FILL_FUNCTION_BODY>
|
int n = 0;
while (true) {
/*
* An ending-pushback could be present before a collateral capture,
* so detect both in a loop (on a shrinking `url') until no more
* shrinking should occur.
*/
int subN = 0;
if (shouldCheckEnding) {
subN = StringUtils.countURIEndingPushback(uri);
}
int ccn = StringUtils.countPushback(uri, collateralCapture);
if (ccn > subN) {
subN = ccn;
}
// Increment if positive, but not if equal to the current length.
if (subN > 0 && subN < uri.length()) {
uri = uri.substring(0, uri.length() - subN);
n += subN;
} else {
break;
}
}
return new TrimUriResult(uri, n);
| 344
| 241
| 585
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/Version.java
|
Version
|
compareTo
|
class Version implements Comparable<Version> {
private final Integer[] versions;
/**
* Construct the version from integer parts.
* The order is:
* <ol>
* <li>major</li>
* <li>minor</li>
* <li>patch</li>
* <li>... others</li>
* </ol>
*
* @param parts integer values for version partials
*/
public Version(Integer... parts) {
// cut off trailing zeros
int cutOffLength = parts.length;
for (int i = parts.length - 1; i >= 0; i--) {
if (parts[i] != 0) {
break;
}
cutOffLength--;
}
versions = Arrays.copyOf(parts, cutOffLength);
}
/**
* Construct the version from a string.
*
* @param string string representing the version (e. g. 1.2.1)
* @return the new instance of version from the string
* @throws NumberFormatException when parts can not be converted to integers
*/
public static Version from(String string) throws NumberFormatException {
return new Version(
Stream.of(string.trim().split("\\."))
.map(String::trim)
.map(Integer::parseInt)
.toArray(Integer[]::new)
);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Version version = (Version) o;
return Arrays.equals(versions, version.versions);
}
@Override
public int hashCode() {
return Arrays.hashCode(versions);
}
@Override
public int compareTo(Version o) {<FILL_FUNCTION_BODY>}
}
|
if (o == null) {
return 1;
}
// first different number determines the result
for (int i = 0; i < Math.min(versions.length, o.versions.length); i++) {
if (!versions[i].equals(o.versions[i])) {
return Integer.compare(versions[i], o.versions[i]);
}
}
// the comparable parts are the same, the longer has some trailing non-null element which
// makes it greater then the shorter
// e. g. 1.0.0.0.1 vs. 1.0.0
return Integer.compare(versions.length, o.versions.length);
| 504
| 173
| 677
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/util/WhitelistObjectInputFilter.java
|
WhitelistObjectInputFilter
|
checkInput
|
class WhitelistObjectInputFilter implements ObjectInputFilter {
private final Set<Class<?>> whitelist;
public WhitelistObjectInputFilter(@NotNull final Class<?>... whitelist) {
this.whitelist = Set.of(whitelist);
}
@Override
public Status checkInput(final FilterInfo filterInfo) {<FILL_FUNCTION_BODY>}
}
|
if (filterInfo.serialClass() == null || whitelist.contains(filterInfo.serialClass())) {
return Status.ALLOWED;
}
return Status.REJECTED;
| 105
| 50
| 155
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/web/ApiUtils.java
|
ApiUtils
|
waitForAsyncApi
|
class ApiUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiUtils.class);
private static final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
private ApiUtils() {
// utility class
}
/**
* Busy waits for API call to complete by repeatedly querying the status API endpoint passed
* in the {@code Location} header in the response parameter. The overall time is governed
* by the {@link RuntimeEnvironment#getApiTimeout()}, however each individual status check
* uses {@link RuntimeEnvironment#getConnectTimeout()} so in the worst case the total time can be
* {@code getApiTimeout() * getConnectTimeout()}.
* @param response response returned from the server upon asynchronous API request
* @return response from the status API call
* @throws InterruptedException on sleep interruption
* @throws IllegalArgumentException on invalid request (no {@code Location} header)
*/
public static @NotNull Response waitForAsyncApi(@NotNull Response response)
throws InterruptedException, IllegalArgumentException {<FILL_FUNCTION_BODY>}
}
|
if (response.getStatus() != Response.Status.ACCEPTED.getStatusCode()) {
LOGGER.log(Level.WARNING, "API request not accepted: {0}", response);
return response;
}
String location = response.getHeaderString(HttpHeaders.LOCATION);
if (location == null) {
throw new IllegalArgumentException(String.format("no %s header in %s", HttpHeaders.LOCATION, response));
}
LOGGER.log(Level.FINER, "checking asynchronous API result on {0}", location);
for (int i = 0; i < env.getApiTimeout(); i++) {
response = ClientBuilder.newBuilder().
connectTimeout(env.getConnectTimeout(), TimeUnit.SECONDS).build().
target(location).request().get();
if (response.getStatus() == Response.Status.ACCEPTED.getStatusCode()) {
Thread.sleep(1000);
} else {
break;
}
}
if (response.getStatus() == Response.Status.ACCEPTED.getStatusCode()) {
LOGGER.log(Level.WARNING, "API request still not completed: {0}", response);
return response;
}
LOGGER.log(Level.FINER, "making DELETE API request to {0}", location);
try (Response deleteResponse = ClientBuilder.newBuilder().
connectTimeout(env.getConnectTimeout(), TimeUnit.SECONDS).build().
target(location).request().delete()) {
if (deleteResponse.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
LOGGER.log(Level.WARNING, "DELETE API call to {0} failed with HTTP error {1}",
new Object[]{location, response.getStatusInfo()});
}
}
return response;
| 265
| 464
| 729
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/web/EftarFile.java
|
Node
|
write
|
class Node {
private final long hash;
private String tag;
private final Map<Long, Node> children;
private long tagOffset;
private long childOffset;
Node(long hash, String tag) {
this.hash = hash;
this.tag = tag;
children = new TreeMap<>();
}
public Node put(long hash, String desc) {
return children.computeIfAbsent(hash, newNode -> new Node(hash, desc));
}
public Node get(long hash) {
return children.get(hash);
}
}
public static long myHash(String name) {
if (name == null || name.length() == 0) {
return 0;
}
long hash = 2861;
int n = name.length();
if (n > 100) {
n = 100;
}
for (int i = 0; i < n; i++) {
hash = (hash * 641L + name.charAt(i) * 2969 + hash << 6) % 9322397;
}
return hash;
}
private void write(Node n, DataOutputStream out) throws IOException {<FILL_FUNCTION_BODY>
|
if (n.tag != null) {
out.write(n.tag.getBytes());
offset += n.tag.length();
}
for (Node childNode : n.children.values()) {
out.writeLong(childNode.hash);
if (childNode.children.size() > 0) {
out.writeShort((short) (childNode.childOffset - offset));
out.writeShort((short) childNode.children.size());
} else {
out.writeShort(0);
if (childNode.tag == null) {
out.writeShort((short) 0);
} else {
out.writeShort((short) childNode.tag.length());
}
}
if (childNode.tag == null) {
out.writeShort(0);
} else {
out.writeShort((short) (childNode.tagOffset - offset));
}
offset += RECORD_LENGTH;
}
for (Node childNode : n.children.values()) {
write(childNode, out);
}
| 326
| 270
| 596
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/web/EftarFileReader.java
|
FNode
|
get
|
class FNode {
private final long offset;
private long hash;
private int childOffset;
private int numChildren;
private int tagOffset;
public FNode() throws IOException {
offset = f.getFilePointer();
try {
hash = f.readLong();
childOffset = f.readUnsignedShort();
numChildren = f.readUnsignedShort();
tagOffset = f.readUnsignedShort();
} catch (EOFException e) {
numChildren = 0;
tagOffset = 0;
}
}
public FNode(long hash, long offset, int childOffset, int num, int tagOffset) {
this.hash = hash;
this.offset = offset;
this.childOffset = childOffset;
this.numChildren = num;
this.tagOffset = tagOffset;
}
public FNode get(long hash) throws IOException {
if (childOffset == 0 || numChildren == 0) {
return null;
}
return binarySearch(offset + childOffset, numChildren, hash);
}
private FNode binarySearch(long start, int len, long hash) throws IOException {
int b = 0;
int e = len;
while (b <= e) {
int m = (b + e) / 2;
f.seek(start + (long) m * EftarFile.RECORD_LENGTH);
long mhash = f.readLong();
if (hash > mhash) {
b = m + 1;
} else if (hash < mhash) {
e = m - 1;
} else {
return new FNode(mhash, f.getFilePointer() - 8L, f.readUnsignedShort(), f.readUnsignedShort(),
f.readUnsignedShort());
}
}
return null;
}
public String getTag() throws IOException {
if (tagOffset == 0) {
return null;
}
f.seek(offset + tagOffset);
byte[] tagString;
if (childOffset == 0) {
tagString = new byte[numChildren];
} else {
tagString = new byte[childOffset - tagOffset];
}
int len = f.read(tagString);
if (len == -1) {
throw new EOFException();
}
return new String(tagString, 0, len);
}
@Override
public String toString() {
String tagString = null;
try {
tagString = getTag();
} catch (EOFException e) { // NOPMD
// ignore
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Got exception while getting the tag: ", e);
}
return "H[" + hash + "] num = " + numChildren + " tag = " + tagString;
}
public int getChildOffset() {
return childOffset;
}
}
public EftarFileReader(String file) throws FileNotFoundException {
this(new File(file));
}
public EftarFileReader(File file) throws FileNotFoundException {
f = new RandomAccessFile(file, "r");
isOpen = true;
}
public FNode getNode(String path) throws IOException {
StringTokenizer toks = new StringTokenizer(path, "/");
f.seek(0);
FNode n = new FNode();
if (File.separator.equals(path) || path.length() == 0) {
return n;
}
FNode next = null;
while (toks.hasMoreTokens() && ((next = n.get(EftarFile.myHash(toks.nextToken()))) != null)) {
n = next;
}
if (!toks.hasMoreElements()) {
return next;
}
return null;
}
public String getChildTag(FNode fn, String name) throws IOException {
if (fn != null && fn.childOffset != 0 && fn.numChildren != 0) {
FNode ch = fn.binarySearch(fn.offset + fn.childOffset, fn.numChildren, EftarFile.myHash(name));
if (ch != null) {
return ch.getTag();
}
}
return null;
}
/**
* Get description for path.
* @param path path relative to source root
* @return path description string
* @throws IOException I/O
*/
public String get(String path) throws IOException {<FILL_FUNCTION_BODY>
|
f.seek(0);
FNode n = new FNode();
FNode next;
long tagOffset = 0;
int tagLength = 0;
var tokens = Arrays.stream(path.split("/"))
.filter(Objects::nonNull)
.filter(tok -> !tok.isEmpty())
.collect(Collectors.toList());
for (var tok : tokens) {
next = n.get(EftarFile.myHash(tok));
if (next == null) {
break;
}
if (next.tagOffset != 0) {
tagOffset = next.offset + next.tagOffset;
if (next.childOffset == 0) {
tagLength = next.numChildren;
} else {
tagLength = next.childOffset - next.tagOffset;
}
}
n = next;
}
if (tagOffset != 0) {
f.seek(tagOffset);
byte[] desc = new byte[tagLength];
int len = f.read(desc);
if (len == -1) {
throw new EOFException();
}
return new String(desc, 0, len);
}
return "";
| 1,165
| 304
| 1,469
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/web/Laundromat.java
|
Laundromat
|
launderLog
|
class Laundromat {
private static final String ESC_N_R_T_F = "[\\n\\r\\t\\f]";
private static final String ESG_N_R_T_F_1_N = ESC_N_R_T_F + "+";
/**
* Sanitize {@code value} where it will be used in subsequent OpenGrok
* (non-logging) processing.
* @return {@code null} if null or else {@code value} with "pattern-breaking
* characters" (tabs, CR, LF, FF) replaced as underscores (one for one)
*/
public static String launderInput(String value) {
return replaceAll(value, ESC_N_R_T_F, "_");
}
/**
* Sanitize {@code value} where it will be used in a Lucene query.
* @return {@code null} if null or else {@code value} with "pattern-breaking
* characters" (tabs, CR, LF, FF) replaced as spaces. Contiguous matches are
* replaced with one space.
*/
public static String launderQuery(String value) {
return replaceAll(value, ESG_N_R_T_F_1_N, " ");
}
/**
* Sanitize {@code value} where it will be used in a log message only.
* @return {@code null} if null or else {@code value} with "pattern-breaking
* characters" tabs, CR, LF, and FF replaced as {@code "<TAB>"},
* {@code "<CR>"}, {@code "<LF>"}, and {@code "<FF>"} resp.
*/
public static String launderLog(String value) {<FILL_FUNCTION_BODY>}
/**
* Sanitize {@code map} where it will be used in a log message only.
* @return {@code map} with keys and values
* sanitized with {@link #launderLog(String)}. If the sanitizing causes key
* collisions, the colliding keys' values are combined.
*/
@NotNull
public static Map<String, String[]> launderLog(@Nullable Map<String, String[]> map) {
return Optional.ofNullable(map)
.stream()
.map(Map::entrySet)
.flatMap(Collection::stream)
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
entry -> launderLog(entry.getKey()),
entry -> launderLogArray(entry.getValue()),
Laundromat::mergeLogArrays
));
}
@NotNull
private static String[] launderLogArray(@Nullable String[] values) {
return Optional.ofNullable(values)
.stream().flatMap(Arrays::stream)
.map(Laundromat::launderLog)
.toArray(String[]::new);
}
@NotNull
private static String[] mergeLogArrays(@NotNull String[] existingSafeEntries,
@NotNull String[] newSafeEntries) {
return Stream.concat(Arrays.stream(newSafeEntries), Arrays.stream(existingSafeEntries))
.toArray(String[]::new);
}
@Nullable
private static String replaceAll(@Nullable String value, @NotNull String regex,
@NotNull String replacement) {
return Optional.ofNullable(value)
.map(val -> val.replaceAll(regex, replacement))
.orElse(null);
}
/* private to enforce static */
private Laundromat() {
}
}
|
if (value == null) {
return null;
}
return value.replace("\n", "<LF>").
replace("\r", "<CR>").
replace("\t", "<TAB>").
replace("\f", "<FF>");
| 909
| 69
| 978
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/web/Suggestion.java
|
Suggestion
|
isUsable
|
class Suggestion {
/** index name. */
private final String name;
/** freetext search suggestions. */
private String[] freetext;
/** references search suggestions. */
private String[] refs;
/** definitions search suggestions. */
private String[] defs;
/**
* Create a new suggestion.
* @param name index name.
*/
public Suggestion(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String[] getFreetext() {
return freetext;
}
public String[] getRefs() {
return refs;
}
public String[] getDefs() {
return defs;
}
public void setFreetext(String[] freetext) {
this.freetext = freetext;
}
public void setRefs(String[] refs) {
this.refs = refs;
}
public void setDefs(String[] defs) {
this.defs = defs;
}
/**
* @return true if at least one of the properties has some content, false otherwise
*/
public boolean isUsable() {<FILL_FUNCTION_BODY>}
}
|
return (freetext != null && freetext.length > 0)
|| (defs != null && defs.length > 0)
|| (refs != null && refs.length > 0);
| 334
| 56
| 390
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/web/messages/MessagesUtils.java
|
TaggedMessagesContainer
|
messagesToJson
|
class TaggedMessagesContainer implements JSONable {
private final String tag;
private final SortedSet<MessagesContainer.AcceptedMessage> messages;
TaggedMessagesContainer(String tag, SortedSet<MessagesContainer.AcceptedMessage> messages) {
this.tag = tag;
this.messages = messages;
}
public String getTag() {
return tag;
}
public SortedSet<MessagesContainer.AcceptedMessage> getMessages() {
return messages;
}
}
/**
* Print list of messages into output.
*
* @param out output
* @param set set of messages
*/
public static void printMessages(Writer out, SortedSet<MessagesContainer.AcceptedMessage> set) {
printMessages(out, set, false);
}
/**
* Print set of messages into output.
* @param out output
* @param set set of messages
* @param limited if the container should be limited
*/
private static void printMessages(Writer out, SortedSet<MessagesContainer.AcceptedMessage> set, boolean limited) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
if (!set.isEmpty()) {
try {
out.write("<ul class=\"message-group");
if (limited) {
out.write(" limited");
}
out.write("\">\n");
for (MessagesContainer.AcceptedMessage m : set) {
out.write("<li class=\"message-group-item ");
out.write(Util.encode(m.getMessage().getMessageLevel().toString()));
out.write("\" title=\"Expires on ");
out.write(Util.encode(df.format(Date.from(m.getExpirationTime()))));
out.write("\">");
out.write(Util.encode(df.format(Date.from(m.getAcceptedTime()))));
out.write(": ");
out.write(m.getMessage().getText());
out.write("</li>");
}
out.write("</ul>");
} catch (IOException ex) {
LOGGER.log(Level.WARNING,
"An error occurred for a group of messages", ex);
}
}
}
/**
* Print set of tagged messages into JSON object.
*
* @return JSON string or empty string
*/
private static String taggedMessagesToJson(Set<TaggedMessagesContainer> messages) {
if (messages.isEmpty()) {
return JSONable.EMPTY;
}
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(messages);
} catch (JsonProcessingException e) {
LOGGER.log(Level.WARNING, String.format("failed to encode '%s' to JSON: ", messages), e);
return JSONable.EMPTY;
}
}
/**
* Print messages for given tags into JSON array.
*
* @param tags list of tags
* @return JSON array of the messages (the same as the parameter)
*/
public static String messagesToJson(String... tags) {
Set<TaggedMessagesContainer> messages = new HashSet<>();
for (String tag : tags) {
SortedSet<MessagesContainer.AcceptedMessage> messagesWithTag = RuntimeEnvironment.getInstance().getMessages(tag);
if (messagesWithTag.isEmpty()) {
continue;
}
TaggedMessagesContainer container = new TaggedMessagesContainer(tag, messagesWithTag);
messages.add(container);
}
return taggedMessagesToJson(messages);
}
/**
* Print messages for given tags into JSON array.
*
* @param tags list of tags
* @return json array of the messages
* @see #messagesToJson(String...)
*/
private static String messagesToJson(List<String> tags) {
return messagesToJson(tags.toArray(new String[0]));
}
/**
* Convert messages for given project into JSON. These messages are
* tagged by project description or tagged by any of the project's group name.
*
* @param project the project
* @param additionalTags additional list of tags
* @return JSON string
* @see #messagesToJson(String...)
*/
public static String messagesToJson(Project project, String... additionalTags) {<FILL_FUNCTION_BODY>
|
if (Objects.isNull(project)) {
return JSONable.EMPTY;
}
List<String> tags = new ArrayList<>(Arrays.asList(additionalTags));
tags.add(project.getName());
project.getGroups().stream().map(Group::getName).forEach(tags::add);
return messagesToJson(tags);
| 1,112
| 92
| 1,204
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/AuthorizationFilter.java
|
AuthorizationFilter
|
init
|
class AuthorizationFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationFilter.class);
@Override
public void init(FilterConfig fc) {<FILL_FUNCTION_BODY>}
/**
* All RESTful API requests are allowed here because they go through
* {@link org.opengrok.web.api.v1.filter.IncomingFilter}.
* The /search endpoint will go through authorization via SearchEngine.search()
* so does not have to be exempted here.
*/
@Override
public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) sr;
HttpServletResponse httpRes = (HttpServletResponse) sr1;
if (httpReq.getServletPath().startsWith(RestApp.API_PATH)) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "Allowing request to {0} in {1}",
new Object[] {Laundromat.launderLog(httpReq.getServletPath()),
AuthorizationFilter.class.getName()});
}
fc.doFilter(sr, sr1);
return;
}
PageConfig config = PageConfig.get(httpReq);
Project p = config.getProject();
if (p != null && !config.isAllowed(p)) {
if (LOGGER.isLoggable(Level.INFO)) {
if (httpReq.getRemoteUser() != null) {
LOGGER.log(Level.INFO, "Access denied for user ''{0}'' for URI: {1}",
new Object[] {Laundromat.launderLog(httpReq.getRemoteUser()),
Laundromat.launderLog(httpReq.getRequestURI())});
} else {
LOGGER.log(Level.INFO, "Access denied for URI: {0}",
Laundromat.launderLog(httpReq.getRequestURI()));
}
}
if (!config.getEnv().getIncludeFiles().getForbiddenIncludeFileContent(false).isEmpty()) {
sr.getRequestDispatcher("/eforbidden").forward(sr, sr1);
return;
}
httpRes.sendError(HttpServletResponse.SC_FORBIDDEN, "Access forbidden");
return;
}
fc.doFilter(sr, sr1);
}
@Override
public void destroy() {
// Empty since there is No specific destroy configuration.
}
}
|
// Empty since there is No specific init configuration.
| 680
| 16
| 696
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/CookieFilter.java
|
CookieFilter
|
doFilter
|
class CookieFilter implements Filter {
private FilterConfig fc;
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {<FILL_FUNCTION_BODY>}
private String getSuffix() {
StringBuilder sb = new StringBuilder();
for (Enumeration<String> e = fc.getInitParameterNames(); e.hasMoreElements();) {
String attributeName = e.nextElement();
if (sb.length() > 0) {
sb.append("; ");
}
sb.append(attributeName);
String attributeValue = fc.getInitParameter(attributeName);
if (!attributeValue.isEmpty()) {
sb.append("=");
sb.append(attributeValue);
}
}
return sb.toString();
}
@Override
public void init(FilterConfig filterConfig) {
this.fc = filterConfig;
}
@Override
public void destroy() {
// pass
}
}
|
HttpServletResponse response = (HttpServletResponse) res;
chain.doFilter(req, response);
// Change the existing cookies to use the attributes and values from the configuration.
String cookieName = HttpHeaders.SET_COOKIE;
Collection<String> headers = response.getHeaders(cookieName);
if (headers == null) {
return;
}
boolean firstHeader = true;
String suffix = getSuffix();
for (String header : headers) { // there can be multiple Set-Cookie attributes
if (firstHeader) {
response.setHeader(cookieName, String.format("%s; %s", header, suffix));
firstHeader = false;
continue;
}
response.addHeader(cookieName, String.format("%s; %s", header, suffix));
}
| 264
| 207
| 471
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/GetFile.java
|
GetFile
|
service
|
class GetFile extends HttpServlet {
public static final long serialVersionUID = -1;
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>}
}
|
PageConfig cfg = PageConfig.get(request);
cfg.checkSourceRootExistence();
String redir = cfg.canProcess();
if (redir == null || redir.length() > 0) {
if (redir != null) {
response.sendRedirect(redir);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return;
}
File f = cfg.getResourceFile();
String revision = cfg.getRequestedRevision();
if (revision.length() == 0) {
revision = null;
}
InputStream in;
try {
if (revision != null) {
in = HistoryGuru.getInstance().getRevision(f.getParent(),
f.getName(), revision);
} else {
long flast = cfg.getLastModified();
if (request.getDateHeader("If-Modified-Since") >= flast) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
response.setContentLength((int) f.length());
response.setDateHeader("Last-Modified", f.lastModified());
in = new FileInputStream(f);
}
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
try {
String mimeType = getServletContext().getMimeType(f.getAbsolutePath());
response.setContentType(mimeType);
if (cfg.getPrefix() == Prefix.DOWNLOAD_P) {
response.setHeader("content-disposition", "attachment; filename="
+ f.getName());
} else {
response.setHeader("content-type", "text/plain");
}
OutputStream o = response.getOutputStream();
byte[] buffer = new byte[8192];
int nr;
while ((nr = in.read(buffer)) > 0) {
o.write(buffer, 0, nr);
}
o.flush();
o.close();
} finally {
in.close();
}
| 62
| 561
| 623
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/ResponseHeaderFilter.java
|
ResponseHeaderFilter
|
doFilter
|
class ResponseHeaderFilter implements Filter {
FilterConfig fc;
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
throws IOException, ServletException {<FILL_FUNCTION_BODY>}
@Override
public void init(FilterConfig filterConfig) {
this.fc = filterConfig;
}
@Override
public void destroy() {
this.fc = null;
}
}
|
HttpServletResponse response = (HttpServletResponse) res;
// set the provided HTTP response parameters
for (Enumeration<String> e = fc.getInitParameterNames(); e.hasMoreElements();) {
String headerName = e.nextElement();
if (!response.containsHeader(headerName)) {
response.addHeader(headerName, fc.getInitParameter(headerName));
}
}
// pass the request/response on
chain.doFilter(req, response);
| 117
| 127
| 244
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/Scripts.java
|
FileScript
|
toHtml
|
class FileScript extends Script {
public FileScript(String script, int priority) {
super(script, priority);
}
@Override
public String toHtml() {<FILL_FUNCTION_BODY>}
}
|
return "\t<script type=\"text/javascript\" src=\"" +
this.getScriptData() +
"\" data-priority=\"" +
this.getPriority() +
"\"></script>\n";
| 61
| 62
| 123
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/StatisticsFilter.java
|
StatisticsFilter
|
measure
|
class StatisticsFilter implements Filter {
static final String REQUESTS_METRIC = "requests";
private static final String CATEGORY_TAG = "category";
private final DistributionSummary requests = Metrics.getPrometheusRegistry().summary(REQUESTS_METRIC);
@Override
public void init(FilterConfig fc) throws ServletException {
//No init config Operation
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc)
throws IOException, ServletException {
requests.record(1);
HttpServletRequest httpReq = (HttpServletRequest) servletRequest;
Instant start = Instant.now();
PageConfig config = PageConfig.get(httpReq);
fc.doFilter(servletRequest, servletResponse);
measure((HttpServletResponse) servletResponse, httpReq, Duration.between(start, Instant.now()), config);
}
private void measure(HttpServletResponse httpResponse, HttpServletRequest httpReq,
Duration duration, PageConfig config) {<FILL_FUNCTION_BODY>}
@NotNull
private String getCategory(HttpServletRequest httpReq, PageConfig config) {
String category;
if (isRoot(httpReq)) {
category = "root";
} else {
String prefix = config.getPrefix().toString();
if (prefix.isEmpty()) {
category = "unknown";
} else {
category = prefix.substring(1);
if (category.equals("xref") && httpReq.getParameter(QueryParameters.ANNOTATION_PARAM) != null) {
category = "annotate";
}
}
}
return category;
}
private boolean isRoot(final HttpServletRequest httpReq) {
return httpReq.getRequestURI().replace(httpReq.getContextPath(), "").equals("/")
|| httpReq.getRequestURI().replace(httpReq.getContextPath(), "").equals("");
}
@Override
public void destroy() {
//No destroy Operation
}
}
|
String category;
category = getCategory(httpReq, config);
Timer categoryTimer = Timer.builder("requests.latency").
tags(CATEGORY_TAG, category, "code", String.valueOf(httpResponse.getStatus())).
register(Metrics.getPrometheusRegistry());
categoryTimer.record(duration);
SearchHelper helper = (SearchHelper) config.getRequestAttribute(SearchHelper.REQUEST_ATTR);
MeterRegistry registry = Metrics.getRegistry();
if (helper != null && registry != null) {
if (helper.getHits() == null || helper.getHits().length == 0) {
Timer.builder("search.latency").
tags(CATEGORY_TAG, "ui", "outcome", "empty").
register(registry).
record(duration);
} else {
Timer.builder("search.latency").
tags(CATEGORY_TAG, "ui", "outcome", "success").
register(registry).
record(duration);
}
}
| 543
| 268
| 811
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/WebappListener.java
|
WebappListener
|
indexCheck
|
class WebappListener implements ServletContextListener, ServletRequestListener {
private static final Logger LOGGER = LoggerFactory.getLogger(WebappListener.class);
private final Timer startupTimer = Timer.builder("webapp.startup.latency").
description("web application startup latency").
register(Metrics.getPrometheusRegistry());
/**
* {@inheritDoc}
*/
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
Instant start = Instant.now();
ServletContext context = servletContextEvent.getServletContext();
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
LOGGER.log(Level.INFO, "Starting webapp with version {0} ({1})",
new Object[]{Info.getVersion(), Info.getRevision()});
String configPath = Optional.ofNullable(context.getInitParameter("CONFIGURATION"))
.orElseThrow(() -> new WebappError("CONFIGURATION parameter missing in the web.xml file"));
try {
env.readConfiguration(new File(configPath), CommandTimeoutType.WEBAPP_START);
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Configuration error. Failed to read config file: ", ex);
}
String serverInfo = context.getServerInfo();
LOGGER.log(Level.INFO, "running inside {0}", serverInfo);
if (serverInfo.startsWith("Apache Tomcat")) {
int idx;
if ((idx = serverInfo.indexOf('/')) > 0) {
String version = serverInfo.substring(idx + 1);
if (!version.startsWith("10.")) {
LOGGER.log(Level.SEVERE, "Unsupported Tomcat version: {0}", version);
throw new WebappError("Unsupported Tomcat version");
}
}
}
/*
* Create a new instance of authorization framework. If the code above
* (reading the configuration) failed then the plugin directory is
* possibly {@code null} causing the framework to allow every request.
*/
env.setAuthorizationFramework(new AuthorizationFramework(env.getPluginDirectory(), env.getPluginStack()));
env.getAuthorizationFramework().reload();
if (env.isWebappCtags() && !env.validateUniversalCtags()) {
LOGGER.warning("Didn't find Universal Ctags for --webappCtags");
}
String pluginDirectory = env.getPluginDirectory();
if (pluginDirectory != null && env.isAuthorizationWatchdog()) {
env.getWatchDog().start(new File(pluginDirectory));
}
indexCheck(configPath, env);
env.startExpirationTimer();
ApiTaskManager.getInstance().setContextPath(context.getContextPath());
// register API task queues
ApiTaskManager.getInstance().addPool(ProjectsController.PROJECTS_PATH, 1);
// Used by ConfigurationController#reloadAuthorization()
ApiTaskManager.getInstance().addPool("authorization", 1);
ApiTaskManager.getInstance().addPool(ConfigurationController.PATH, 1);
startupTimer.record(Duration.between(start, Instant.now()));
}
/**
* Check index(es). If projects are enabled, those which failed the test will be marked as not indexed.
* @param configPath path to configuration
* @param env {@link RuntimeEnvironment} instance
*/
private static void indexCheck(String configPath, RuntimeEnvironment env) {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
public void contextDestroyed(final ServletContextEvent servletContextEvent) {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
env.getIndexerParallelizer().bounce();
env.getWatchDog().stop();
env.stopExpirationTimer();
try {
env.shutdownRevisionExecutor();
env.shutdownSearchExecutor();
env.shutdownDirectoryListingExecutor();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "Could not shutdown revision executor", e);
}
// need to explicitly close the suggester service because it might have scheduled rebuild which could prevent
// the web application from closing
SuggesterServiceFactory.getDefault().close();
// destroy queue(s) of API tasks
try {
ApiTaskManager.getInstance().shutdown();
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "could not shutdown API task manager cleanly", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void requestInitialized(ServletRequestEvent e) {
// pass
}
/**
* {@inheritDoc}
*/
@Override
public void requestDestroyed(ServletRequestEvent e) {
PageConfig.cleanup(e.getServletRequest());
SearchHelper sh = (SearchHelper) e.getServletRequest().getAttribute(SearchHelper.REQUEST_ATTR);
if (sh != null) {
sh.destroy();
}
AnalyzerGuru.returnAnalyzers();
}
}
|
try (IndexCheck indexCheck = new IndexCheck(Configuration.read(new File(configPath)))) {
indexCheck.check(IndexCheck.IndexCheckMode.VERSION);
} catch (IOException e) {
LOGGER.log(Level.WARNING, "could not perform index check", e);
} catch (IndexCheckException e) {
if (env.isProjectsEnabled()) {
LOGGER.log(Level.INFO, "marking projects that failed the index check as not indexed");
for (Path path : e.getFailedPaths()) {
Project project = Project.getProject(path.toFile());
if (project != null) {
project.setIndexed(false);
}
}
} else {
// Fail the deployment. The index check would fail only on legitimate version discrepancy.
throw new WebappError("index version check failed", e);
}
}
| 1,302
| 225
| 1,527
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/ApiTask.java
|
ApiTask
|
getResponse
|
class ApiTask {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiTask.class);
private final Callable<Object> callable;
enum ApiTaskState {
INITIAL,
SUBMITTED,
COMPLETED,
}
private ApiTaskState state;
private final UUID uuid;
private final String path;
private final Response.Status responseStatus;
private Future<Object> future;
private final Map<Class<?>, Response.Status> exceptionStatusMap = new HashMap<>();
/**
* @param path request path (for identification)
* @param callable Callable object
*/
public ApiTask(String path, Callable<Object> callable) {
this(path, callable, Response.Status.OK);
}
/**
* @param path request path (for identification)
* @param callable Callable object
* @param status request status to return after the runnable is done
*/
public ApiTask(String path, Callable<Object> callable, Response.Status status) {
this(path, callable, status, null);
}
/**
* @param path request path (for identification)
* @param callable Callable object
* @param status request status to return after the runnable is done
* @param exceptionStatusMap map of {@link Exception} to {@link Response.Status}
*/
public ApiTask(String path, Callable<Object> callable, Response.Status status,
Map<Class<?>, Response.Status> exceptionStatusMap) {
this.callable = callable;
this.uuid = UUID.randomUUID();
this.responseStatus = status;
this.path = path;
this.state = ApiTaskState.INITIAL;
if (exceptionStatusMap != null) {
this.exceptionStatusMap.putAll(exceptionStatusMap);
}
}
/**
* The UUID is randomly generated in the constructor.
* @return UUID
*/
public UUID getUuid() {
return uuid;
}
/**
* @return response status to be used when the task was successfully completed
*/
Response.Status getResponseStatus() {
return responseStatus;
}
/**
* Set status as submitted.
*/
void setSubmitted() {
state = ApiTaskState.SUBMITTED;
}
/**
* @return whether the API task successfully completed
*/
public boolean isCompleted() {
return state.equals(ApiTaskState.COMPLETED);
}
void setCompleted() {
state = ApiTaskState.COMPLETED;
}
/**
* @param future Future object used for tracking the progress of the API task
*/
void setFuture(Future<Object> future) {
this.future = future;
}
/**
* @return whether the task is finished (normally or with exception)
*/
public boolean isDone() {
if (future != null) {
return future.isDone();
} else {
return false;
}
}
/**
* Provides simple Exception to status code mapping. The Exception match is exact, i.e. exception class hierarchy
* is not considered.
* @param exception Exception
* @return Response status
*/
private Response.Status mapExceptionToStatus(ExecutionException exception) {
return exceptionStatusMap.getOrDefault(exception.getCause().getClass(), Response.Status.INTERNAL_SERVER_ERROR);
}
/**
* This method assumes that the API task is finished.
* @return {@link Response} object corresponding to the state of the API task. If the task returns
* non-{@code null} object, its JSON representation will be sent in the response payload.
* @throws IllegalStateException if the API task is not finished
*/
public Response getResponse() {<FILL_FUNCTION_BODY>}
/**
* @return {@link Callable} object that contains the work that needs to be completed for this API request
*/
public Callable<Object> getCallable() {
synchronized (this) {
if (state.equals(ApiTaskState.SUBMITTED)) {
throw new IllegalStateException(String.format("API task %s already submitted", this));
}
return () -> {
LOGGER.log(Level.FINE, "API task {0} started", this);
setSubmitted();
Object ret = callable.call();
setCompleted();
LOGGER.log(Level.FINE, "API task {0} done", this);
return ret;
};
}
}
@Override
public String toString() {
return "{uuid=" + uuid + ",path=" + path + ",state=" + state + ",responseStatus=" + responseStatus + "}";
}
}
|
// Avoid thread being blocked in future.get() below.
if (!isDone()) {
throw new IllegalStateException(String.format("task %s not yet done", this));
}
Object obj;
try {
obj = future.get();
} catch (InterruptedException ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (ExecutionException ex) {
return Response.status(mapExceptionToStatus(ex)).entity(ex.toString()).build();
}
if (obj != null) {
return Response.status(getResponseStatus()).
type(MediaType.APPLICATION_JSON_TYPE).
entity(obj).
build();
}
return Response.status(getResponseStatus()).build();
| 1,247
| 199
| 1,446
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/ApiTaskManager.java
|
ApiTaskManager
|
shutdown
|
class ApiTaskManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiTaskManager.class);
private final Map<String, ExecutorService> queues = new ConcurrentHashMap<>(); // queue name -> ExecutorService
private final Map<UUID, ApiTask> apiTasks = new ConcurrentHashMap<>(); // UUID -> ApiTask
private static final ApiTaskManager apiTaskManager = new ApiTaskManager();
private String contextPath;
private ApiTaskManager() {
// singleton
}
public static ApiTaskManager getInstance() {
return apiTaskManager;
}
/**
* @param uuid UUID
* @return ApiTask object or null
*/
public ApiTask getApiTask(String uuid) {
return apiTasks.get(UUID.fromString(uuid));
}
/**
* Set context path. This is used to construct status URLs in {@link #submitApiTask(String, ApiTask)}
* @param path context path
*/
public void setContextPath(String path) {
this.contextPath = path;
}
static String getQueueName(String name) {
String suffix = name.replaceAll("^/", "").replace("/", "-");
if (!suffix.startsWith("-")) {
suffix = "-" + suffix;
}
return "api_task" + suffix;
}
/**
* Submit an API task for processing.
* @param name name of the API endpoint
* @param apiTask ApiTask object
* @return Response status
*/
public Response submitApiTask(String name, ApiTask apiTask) {
String queueName = getQueueName(name);
if (queues.get(queueName) == null) {
LOGGER.log(Level.WARNING, "cannot find queue ''{0}''", queueName);
return Response.status(Response.Status.BAD_REQUEST).build();
}
apiTask.setFuture(queues.get(queueName).submit(apiTask.getCallable()));
apiTasks.put(apiTask.getUuid(), apiTask);
// This is useful for testing where there is no context path.
var uriStringBuilder = Optional.ofNullable(contextPath)
.map(StringBuilder::new)
.map(stringBuilder -> stringBuilder.append("/api/v1"))
.orElseGet(StringBuilder::new);
uriStringBuilder.append("/");
uriStringBuilder.append(StatusController.PATH);
uriStringBuilder.append("/");
uriStringBuilder.append(apiTask.getUuid());
return Response.status(Response.Status.ACCEPTED).
location(URI.create(uriStringBuilder.toString())).build();
}
/**
* Delete API task.
* @param uuid task UUID
*/
public void deleteApiTask(String uuid) {
apiTasks.remove(UUID.fromString(uuid));
}
/**
* Add new thread pool.
* @param name name of the thread pool
* @param threadCount thread count
*/
public void addPool(String name, int threadCount) {
String queueName = getQueueName(name);
if (queues.get(queueName) != null) {
throw new IllegalStateException(String.format("queue %s already present", queueName));
}
queues.put(queueName, Executors.newFixedThreadPool(threadCount,
new OpenGrokThreadFactory(queueName)));
}
/**
* Shutdown all executor services and wait 60 seconds for pending tasks.
* @throws InterruptedException on termination
*/
public synchronized void shutdown() throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
for (ExecutorService executorService : queues.values()) {
executorService.shutdown();
}
for (Map.Entry<String, ExecutorService> entry : queues.entrySet()) {
boolean shutdownResult = entry.getValue().awaitTermination(60, TimeUnit.SECONDS);
if (!shutdownResult) {
LOGGER.log(Level.WARNING, "abnormal termination for executor service for queue ''{0}''",
entry.getKey());
}
}
| 954
| 129
| 1,083
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/error/GenericExceptionMapper.java
|
GenericExceptionMapper
|
toResponse
|
class GenericExceptionMapper implements ExceptionMapper<Exception> {
private static final Logger logger = LoggerFactory.getLogger(GenericExceptionMapper.class);
@Override
public Response toResponse(final Exception e) {<FILL_FUNCTION_BODY>}
}
|
logger.log(Level.WARNING, "Exception while processing request", e);
return ExceptionMapperUtils.toResponse(Response.Status.INTERNAL_SERVER_ERROR, e);
| 68
| 46
| 114
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/AnnotationController.java
|
AnnotationDTO
|
getContent
|
class AnnotationDTO {
@JsonProperty
private String revision;
@JsonProperty
private String author;
@JsonProperty
private String description;
@JsonProperty
private String version;
// for testing
AnnotationDTO() {
}
AnnotationDTO(String revision, String author, String description, String version) {
this.revision = revision;
this.author = author;
this.description = description;
this.version = version;
}
// for testing
public String getAuthor() {
return this.author;
}
// for testing
public String getRevision() {
return this.revision;
}
// for testing
public String getDescription() {
return this.description;
}
// for testing
public String getVersion() {
return this.version;
}
}
@GET
@CorsEnable
@PathAuthorized
@Produces(MediaType.APPLICATION_JSON)
public List<AnnotationDTO> getContent(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@QueryParam("path") final String path,
@QueryParam("revision") final String revision)
throws IOException, NoPathParameterException {<FILL_FUNCTION_BODY>
|
File file = toFile(path);
Annotation annotation = HistoryGuru.getInstance().annotate(file,
revision == null || revision.isEmpty() ? null : revision);
ArrayList<AnnotationDTO> annotationList = new ArrayList<>();
for (int i = 1; i <= annotation.size(); i++) {
annotationList.add(new AnnotationDTO(annotation.getRevision(i),
annotation.getAuthor(i),
annotation.getDesc(annotation.getRevision(i)),
annotation.getFileVersion(annotation.getRevision(i)) + "/" + annotation.getRevisions().size()));
}
return annotationList;
| 331
| 166
| 497
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/ConfigurationController.java
|
ConfigurationController
|
getConfigurationValueException
|
class ConfigurationController {
private final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
public static final String PATH = "configuration";
private final SuggesterService suggesterService;
@Inject
public ConfigurationController(SuggesterService suggesterService) {
this.suggesterService = suggesterService;
}
@GET
@Produces(MediaType.APPLICATION_XML)
public String get() {
return env.getConfigurationXML();
}
@PUT
@Consumes(MediaType.APPLICATION_XML)
public Response set(@Context HttpServletRequest request,
@QueryParam("reindex") final boolean reindex) throws IOException {
String body;
try (InputStream inputStream = request.getInputStream()) {
body = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
return ApiTaskManager.getInstance().submitApiTask(PATH,
new ApiTask(request.getRequestURI(), () -> {
env.applyConfig(body, reindex, CommandTimeoutType.RESTFUL);
suggesterService.refresh();
return null;
}, Response.Status.CREATED));
}
@GET
@Path("/{field}")
@Produces(MediaType.APPLICATION_JSON)
public Object getField(@PathParam("field") final String field) {
return getConfigurationValueException(field);
}
@PUT
@Path("/{field}")
public Response setField(@Context HttpServletRequest request,
@PathParam("field") final String field, final String value) {
setConfigurationValueException(field, value);
return ApiTaskManager.getInstance().submitApiTask(PATH,
new ApiTask(request.getRequestURI(), () -> {
// apply the configuration - let the environment reload the configuration if necessary
env.applyConfig(false, CommandTimeoutType.RESTFUL);
suggesterService.refresh();
return null;
}, Response.Status.NO_CONTENT));
}
@POST
@Path("/authorization/reload")
public Response reloadAuthorization(@Context HttpServletRequest request) {
return ApiTaskManager.getInstance().submitApiTask("authorization",
new ApiTask(request.getRequestURI(),
() -> {
env.getAuthorizationFramework().reload();
return null;
},
Response.Status.NO_CONTENT));
}
private Object getConfigurationValueException(String fieldName) throws WebApplicationException {<FILL_FUNCTION_BODY>}
private void setConfigurationValueException(String fieldName, String value)
throws WebApplicationException {
final IOException[] capture = new IOException[1];
final int IOE_INDEX = 0;
env.syncWriteConfiguration(value, (configuration, v) -> {
try {
ClassUtil.setFieldValue(configuration, fieldName, v);
} catch (IOException ex) {
capture[IOE_INDEX] = ex;
}
});
if (capture[IOE_INDEX] != null) {
throw new WebApplicationException(capture[IOE_INDEX], Response.Status.BAD_REQUEST);
}
}
}
|
final IOException[] capture = new IOException[1];
final int IOE_INDEX = 0;
Object result = env.syncReadConfiguration(configuration -> {
try {
return ClassUtil.getFieldValue(configuration, fieldName);
} catch (IOException ex) {
capture[IOE_INDEX] = ex;
return null;
}
});
if (capture[IOE_INDEX] != null) {
throw new WebApplicationException(capture[IOE_INDEX], Response.Status.BAD_REQUEST);
}
return result;
| 807
| 142
| 949
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/DirectoryListingController.java
|
DirectoryEntryDTO
|
equals
|
class DirectoryEntryDTO implements JSONable {
@JsonProperty
String path;
@JsonProperty
Long numLines;
@JsonProperty
Long loc;
@JsonProperty
Date date;
@JsonProperty
String description;
@JsonProperty
String pathDescription;
@JsonProperty
boolean isDirectory;
@JsonProperty
Long size;
// Needed for deserialization when testing.
DirectoryEntryDTO() {
}
DirectoryEntryDTO(DirectoryEntry entry) throws ForbiddenSymlinkException, IOException {
path = Util.fixPathIfWindows(RuntimeEnvironment.getInstance().getPathRelativeToSourceRoot(entry.getFile()));
NullableNumLinesLOC extra = entry.getExtra();
if (extra != null) {
loc = entry.getExtra().getLOC();
numLines = entry.getExtra().getNumLines();
}
date = entry.getDate();
description = entry.getDescription();
pathDescription = entry.getPathDescription();
isDirectory = entry.getFile().isDirectory();
if (isDirectory) {
size = null;
} else {
size = entry.getFile().length();
}
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(path, date, numLines, loc, description, pathDescription, isDirectory);
}
@Override
public String toString() {
return "{" + "path=" + path + ",date=" + date + ",numLines=" + numLines + ",loc=" + loc +
",description=" + description + ",pathDescription=" + pathDescription +
",isDirectory=" + isDirectory + "}";
}
}
|
return Optional.ofNullable(obj)
.filter(other -> getClass() == other.getClass())
.map(DirectoryEntryDTO.class::cast)
.filter(other -> Objects.equals(this.path, other.path))
.filter(other -> Objects.equals(this.date, other.date))
.filter(other -> Objects.equals(this.numLines, other.numLines))
.filter(other -> Objects.equals(this.loc, other.loc))
.filter(other -> Objects.equals(this.description, other.description))
.filter(other -> Objects.equals(this.pathDescription, other.pathDescription))
.filter(other -> this.isDirectory == other.isDirectory)
.isPresent();
| 461
| 200
| 661
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/FileController.java
|
FileController
|
transfer
|
class FileController {
public static final String PATH = "file";
private StreamingOutput transfer(File file) throws FileNotFoundException {<FILL_FUNCTION_BODY>}
@GET
@CorsEnable
@PathAuthorized
@Path("/content")
@Produces(MediaType.TEXT_PLAIN)
public StreamingOutput getContentPlain(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@QueryParam("path") final String path) throws IOException, ParseException, NoPathParameterException {
File file = toFile(path);
Document doc;
if ((doc = getDocument(file)) == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot get document for file");
return null;
}
String fileType = doc.get(QueryBuilder.T);
if (!AbstractAnalyzer.Genre.PLAIN.typeName().equals(fileType)) {
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Not a text file");
return null;
}
return transfer(file);
}
@GET
@CorsEnable
@PathAuthorized
@Path("/content")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public StreamingOutput getContentOctets(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@QueryParam("path") final String path) throws IOException, NoPathParameterException {
File file = toFile(path);
try {
return transfer(file);
} catch (FileNotFoundException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot find file");
return null;
}
}
@GET
@CorsEnable
@PathAuthorized
@Path("/genre")
@Produces(MediaType.TEXT_PLAIN)
public String getGenre(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@QueryParam("path") final String path) throws IOException, ParseException, NoPathParameterException {
File file = toFile(path);
Document doc;
if ((doc = getDocument(file)) == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot get document for file");
return null;
}
AbstractAnalyzer.Genre genre = AbstractAnalyzer.Genre.get(doc.get(QueryBuilder.T));
if (genre == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot get genre from the document");
return null;
}
return genre.toString();
}
@GET
@CorsEnable
@PathAuthorized
@Path("/defs")
@Produces(MediaType.APPLICATION_JSON)
public List<Object> getDefinitions(@Context HttpServletRequest request,
@Context HttpServletResponse response,
@QueryParam("path") final String path)
throws IOException, NoPathParameterException, ParseException, ClassNotFoundException {
File file = toFile(path);
Definitions defs = IndexDatabase.getDefinitions(file);
return Optional.ofNullable(defs).
map(Definitions::getTags).
stream().
flatMap(Collection::stream).
map(DTOUtil::createDTO).
collect(Collectors.toList());
}
}
|
if (!file.exists()) {
throw new FileNotFoundException(String.format("file %s does not exist", file));
}
return out -> {
try (InputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
}
};
| 871
| 126
| 997
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/GroupsController.java
|
GroupsController
|
matchProject
|
class GroupsController {
public static final String GROUPS_PATH = "groups";
private final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<String> listGroups() {
if (env.hasGroups()) {
return Objects.requireNonNull(env.getGroups()).values()
.stream()
.map(Group::getName)
.collect(Collectors.toList());
} else {
return Collections.emptyList();
}
}
@GET
@Path("/{group}/allprojects")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllProjectsForGroup(@PathParam("group") String groupName) {
// Avoid classification as a taint bug.
groupName = Laundromat.launderInput(groupName);
Group group;
group = Group.getByName(groupName);
if (group == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if (group.getAllProjects().isEmpty()) {
return Response.ok().entity(Collections.emptyList()).build();
} else {
List<String> projectNameList = group.getAllProjects().stream().
map(Project::getName).collect(Collectors.toList());
return Response.ok().entity(projectNameList).build();
}
}
@GET
@Path("/{group}/pattern")
@Produces(MediaType.TEXT_PLAIN)
public Response getPattern(@PathParam("group") String groupName) {
// Avoid classification as a taint bug.
groupName = Laundromat.launderInput(groupName);
Group group;
group = Group.getByName(groupName);
if (group == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok().entity(group.getPattern()).build();
}
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Path("/{group}/match")
public Response matchProject(@PathParam("group") String groupName, String projectNameParam) {<FILL_FUNCTION_BODY>}
}
|
// Avoid classification as a taint bug.
final String projectName = Laundromat.launderInput(projectNameParam);
// Avoid classification as a taint bug.
groupName = Laundromat.launderInput(groupName);
Group group;
group = Group.getByName(groupName);
if (group == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if (group.match(projectName)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NO_CONTENT).build();
}
| 571
| 161
| 732
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/HistoryController.java
|
HistoryDTO
|
equals
|
class HistoryDTO implements JSONable {
@JsonProperty
private final List<HistoryEntryDTO> entries;
@JsonProperty
private int start;
@JsonProperty
private int count;
@JsonProperty
private int total;
@TestOnly
HistoryDTO() {
this.entries = new ArrayList<>();
}
HistoryDTO(List<HistoryEntryDTO> entries, int start, int count, int total) {
this.entries = entries;
this.start = start;
this.count = count;
this.total = total;
}
@TestOnly
public List<HistoryEntryDTO> getEntries() {
return entries;
}
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(entries, start, count, total);
}
}
|
return Optional.ofNullable(obj)
.filter(other -> getClass() == other.getClass())
.map(HistoryDTO.class::cast)
.filter(other -> Objects.equals(this.entries, other.entries))
.filter(other -> Objects.equals(this.start, other.start))
.filter(other -> Objects.equals(this.count, other.count))
.filter(other -> Objects.equals(this.total, other.total))
.isPresent();
| 237
| 135
| 372
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/MessagesController.java
|
MessagesController
|
removeMessagesWithTag
|
class MessagesController {
private final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addMessage(@Valid final Message message) {
env.addMessage(message);
return Response.status(Response.Status.CREATED).build();
}
@DELETE
@Consumes(MediaType.TEXT_PLAIN)
public void removeMessagesWithTag(@QueryParam("tag") final String tag, final String text) {<FILL_FUNCTION_BODY>}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Set<AcceptedMessage> getMessages(@QueryParam("tag") final String tag) {
if (tag != null) {
return env.getMessages(tag);
} else {
return env.getAllMessages();
}
}
}
|
if (tag == null) {
throw new WebApplicationException("Message tag has to be specified", Response.Status.BAD_REQUEST);
}
env.removeAnyMessage(Collections.singleton(tag), text);
| 223
| 56
| 279
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/RepositoriesController.java
|
RepositoriesController
|
getRepositoryInfoData
|
class RepositoriesController {
private final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
private Object getRepositoryInfoData(String repositoryPath) {<FILL_FUNCTION_BODY>}
@GET
@Path("/property/{field}")
@Produces(MediaType.APPLICATION_JSON)
public Object get(@QueryParam("repository") final String repositoryPath, @PathParam("field") final String field)
throws IOException {
Object ri = getRepositoryInfoData(repositoryPath);
if (ri == null) {
throw new WebApplicationException("cannot find repository with path: " + repositoryPath,
Response.Status.NOT_FOUND);
}
return ClassUtil.getFieldValue(ri, field);
}
}
|
for (RepositoryInfo ri : env.getRepositories()) {
if (ri.getDirectoryNameRelative().equals(repositoryPath)) {
return DTOUtil.createDTO(ri);
}
}
return null;
| 186
| 63
| 249
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/SearchController.java
|
SearchEngineWrapper
|
search
|
class SearchEngineWrapper implements AutoCloseable {
private final SearchEngine engine = new SearchEngine();
private int numResults;
private SearchEngineWrapper(
final String full,
final String def,
final String symbol,
final String path,
final String hist,
final String type
) {
engine.setFreetext(full);
engine.setDefinition(def);
engine.setSymbol(symbol);
engine.setFile(path);
engine.setHistory(hist);
engine.setType(type);
}
public List<Hit> search(
final HttpServletRequest req,
final List<String> projects,
final int startDocIndex,
final int maxResults
) {<FILL_FUNCTION_BODY>}
private boolean isValid() {
return engine.isValidQuery();
}
private Query getQuery() {
return engine.getQueryObject();
}
@Override
public void close() {
engine.destroy();
}
}
|
Set<Project> allProjects = PageConfig.get(req).getProjectHelper().getAllProjects();
if (projects == null || projects.isEmpty()) {
numResults = engine.search(new ArrayList<>(allProjects));
} else {
numResults = engine.search(allProjects.stream()
.filter(p -> projects.contains(p.getName()))
.collect(Collectors.toList()));
}
if (startDocIndex > numResults) {
return Collections.emptyList();
}
int resultSize = numResults - startDocIndex;
if (resultSize > maxResults) {
resultSize = maxResults;
}
List<Hit> results = new ArrayList<>();
engine.results(startDocIndex, startDocIndex + resultSize, results);
return results;
| 260
| 209
| 469
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/StatusController.java
|
StatusController
|
delete
|
class StatusController {
public static final String PATH = "status";
private static final Logger LOGGER = LoggerFactory.getLogger(StatusController.class);
@GET
@Path("/{uuid}")
public Response getStatus(@PathParam("uuid") String uuid) {
ApiTask apiTask = ApiTaskManager.getInstance().getApiTask(uuid);
if (apiTask == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if (apiTask.isDone()) {
return apiTask.getResponse();
} else {
return Response.status(Response.Status.ACCEPTED).build();
}
}
@DELETE
@Path("/{uuid}")
public Response delete(@PathParam("uuid") String uuid) {<FILL_FUNCTION_BODY>}
}
|
ApiTask apiTask = ApiTaskManager.getInstance().getApiTask(uuid);
if (apiTask == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if (!apiTask.isDone()) {
LOGGER.log(Level.WARNING, "API task {0} not yet done", apiTask);
return Response.status(Response.Status.BAD_REQUEST).build();
}
ApiTaskManager.getInstance().deleteApiTask(uuid);
return Response.ok().build();
| 217
| 138
| 355
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/controller/SystemController.java
|
SystemController
|
getIndexTime
|
class SystemController {
public static final String PATH = "system";
private final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
private static final Logger LOGGER = LoggerFactory.getLogger(SystemController.class);
@PUT
@Path("/includes/reload")
public void reloadIncludes() {
env.getIncludeFiles().reloadIncludeFiles();
}
@POST
@Path("/pathdesc")
@Consumes(MediaType.APPLICATION_JSON)
public void loadPathDescriptions(@Valid final PathDescription[] descriptions) throws IOException {
EftarFile ef = new EftarFile();
ef.create(Set.of(descriptions), env.getDtagsEftarPath().toString());
LOGGER.log(Level.INFO, "reloaded path descriptions with {0} entries", descriptions.length);
}
@GET
@Path("/indextime")
@Produces(MediaType.APPLICATION_JSON)
public String getIndexTime() throws JsonProcessingException {<FILL_FUNCTION_BODY>}
@GET
@Path("/version")
@Produces(MediaType.TEXT_PLAIN)
public String getVersion() {
return String.format("%s (%s)", Info.getVersion(), Info.getRevision());
}
@GET
@Path("/ping")
public String ping() {
return "";
}
}
|
Date date = new IndexTimestamp().getDateForLastIndexRun();
ObjectMapper mapper = new ObjectMapper();
// StdDateFormat is ISO8601 since jackson 2.9
mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
return mapper.writeValueAsString(date);
| 358
| 87
| 445
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/filter/CorsFilter.java
|
CorsFilter
|
filter
|
class CorsFilter implements ContainerResponseFilter {
public static final String ALLOW_CORS_HEADER = "Access-Control-Allow-Origin";
public static final String CORS_REQUEST_HEADER = "Origin";
/**
* Method for ContainerResponseFilter.
*/
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {<FILL_FUNCTION_BODY>}
}
|
// if there is no Origin header, then it is not a
// cross origin request. We don't do anything.
if (request.getHeaderString(CORS_REQUEST_HEADER) == null) {
return;
}
response.getHeaders().add(ALLOW_CORS_HEADER, "*");
| 106
| 84
| 190
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/filter/IncomingFilter.java
|
IncomingFilter
|
filter
|
class IncomingFilter implements ContainerRequestFilter, ConfigurationChangedListener {
private static final Logger LOGGER = LoggerFactory.getLogger(IncomingFilter.class);
/**
* Endpoint paths that are exempted from this filter.
* @see SearchController#search(HttpServletRequest, String, String, String, String, String, String,
* java.util.List, int, int)
* @see SuggesterController#getSuggestions(org.opengrok.web.api.v1.suggester.model.SuggesterQueryData)
* @see SuggesterController#getConfig()
*/
private static final Set<String> allowedPaths = new HashSet<>(Arrays.asList(
SearchController.PATH, SuggesterController.PATH, SuggesterController.PATH + "/config",
HistoryController.PATH, FileController.PATH, AnnotationController.PATH,
SystemController.PATH + "/ping"));
@Context
private HttpServletRequest request;
private final Set<String> localAddresses = new HashSet<>(Arrays.asList(
"127.0.0.1", "0:0:0:0:0:0:0:1", "localhost"
));
static final String BEARER = "Bearer "; // Authorization header value prefix
private Set<String> tokens;
private Set<String> getTokens() {
return tokens;
}
private void setTokens(Set<String> tokens) {
this.tokens = tokens;
}
@PostConstruct
public void init() {
try {
localAddresses.add(InetAddress.getLocalHost().getHostAddress());
for (InetAddress inetAddress : InetAddress.getAllByName("localhost")) {
localAddresses.add(inetAddress.getHostAddress());
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Could not get localhost addresses", e);
}
// Cache the tokens to avoid locking.
setTokens(RuntimeEnvironment.getInstance().getAuthenticationTokens());
RuntimeEnvironment.getInstance().registerListener(this);
}
@Override
public void onConfigurationChanged() {
LOGGER.log(Level.FINER, "refreshing token cache");
setTokens(RuntimeEnvironment.getInstance().getAuthenticationTokens());
}
@Override
public void filter(final ContainerRequestContext context) {<FILL_FUNCTION_BODY>}
}
|
if (request == null) { // happens in tests
return;
}
String path = context.getUriInfo().getPath();
boolean isTokenValid = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION))
.filter(authHeaderValue -> authHeaderValue.startsWith(BEARER))
.map(authHeaderValue -> authHeaderValue.substring(BEARER.length()))
.filter(getTokens()::contains)
.isPresent();
if (isTokenValid) {
var sanitizedPath = path.replaceAll("[\n\r]", "_");
if (request.isSecure() || RuntimeEnvironment.getInstance().isAllowInsecureTokens()) {
LOGGER.log(Level.FINEST, "allowing request to {0} based on authentication token", sanitizedPath);
return;
} else {
LOGGER.log(Level.FINEST, "request to {0} has a valid token however is not secure", sanitizedPath);
}
}
if (allowedPaths.contains(path)) {
LOGGER.log(Level.FINEST, "allowing request to {0} based on allow listed path", path);
return;
}
// In a reverse proxy environment the connection appears to be coming from localhost.
// These request should really be using tokens.
if (request.getHeader("X-Forwarded-For") != null || request.getHeader("Forwarded") != null) {
LOGGER.log(Level.FINEST, "denying request to {0} due to existence of forwarded header in the request",
path);
context.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
return;
}
if (localAddresses.contains(request.getRemoteAddr())) {
LOGGER.log(Level.FINEST, "allowing request to {0} based on localhost IP address", path);
return;
}
context.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
| 631
| 522
| 1,153
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/filter/PathAuthorizationFilter.java
|
PathAuthorizationFilter
|
isPathAuthorized
|
class PathAuthorizationFilter implements ContainerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(PathAuthorizationFilter.class);
private static final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
public static final String PATH_PARAM = "path";
@Context
private HttpServletRequest request;
private static boolean isPathAuthorized(String path, HttpServletRequest request) {<FILL_FUNCTION_BODY>}
@Override
public void filter(final ContainerRequestContext context) {
if (request == null) { // happens in tests
return;
}
String path = request.getParameter(PATH_PARAM);
if (path == null || path.isEmpty()) {
logger.log(Level.WARNING, "request does not contain \"{0}\" parameter: {1}",
new Object[]{PATH_PARAM, request});
// This should align with whatever NoPathExceptionMapper does.
// We cannot throw the exception here as it would not match the filter() signature.
context.abortWith(Response.status(Response.Status.NOT_ACCEPTABLE).build());
return;
}
if (!isPathAuthorized(path, request)) {
// TODO: this should probably update statistics for denied requests like in AuthorizationFilter
context.abortWith(Response.status(Response.Status.FORBIDDEN).build());
}
}
}
|
if (request != null) {
AuthorizationFramework auth = env.getAuthorizationFramework();
if (auth != null) {
Project p = Project.getProject(path.startsWith("/") ? path : "/" + path);
return p == null || auth.isAllowed(request, p);
}
}
return false;
| 343
| 91
| 434
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/suggester/parser/SuggesterQueryDataParser.java
|
SuggesterQueryDataParser
|
getFieldQueries
|
class SuggesterQueryDataParser {
private static final int IDENTIFIER_LENGTH = 5;
private static final Logger logger = LoggerFactory.getLogger(SuggesterQueryDataParser.class);
private SuggesterQueryDataParser() {
}
/**
* Parses the {@link SuggesterQueryData}.
* @param data data to parse
* @return parsed data for the suggester use
* @throws ParseException could not parse the search data into a valid {@link Query}
*/
public static SuggesterData parse(final SuggesterQueryData data) throws ParseException {
List<String> projectList = data.getProjects().stream().
filter(p -> RuntimeEnvironment.getInstance().getProjectNames().contains(p)).
collect(Collectors.toList());
Map<String, String> fieldQueries = getFieldQueries(data);
ProcessedQueryData queryData = processQuery(fieldQueries.get(data.getField()), data.getCaretPosition());
fieldQueries.put(data.getField(), queryData.query);
SuggesterQueryBuilder builder = new SuggesterQueryBuilder(data.getField(), queryData.identifier);
builder.setFreetext(fieldQueries.get(QueryBuilder.FULL))
.setDefs(fieldQueries.get(QueryBuilder.DEFS))
.setRefs(fieldQueries.get(QueryBuilder.REFS))
.setPath(fieldQueries.get(QueryBuilder.PATH))
.setHist(fieldQueries.get(QueryBuilder.HIST))
.setType(fieldQueries.get(QueryBuilder.TYPE));
Query query;
try {
query = builder.build();
} catch (ParseException e) {
// remove identifier from the message
// the position might be still wrong if the parse error was at the end of the identifier
throw new ParseException(e.getMessage().replaceAll(queryData.identifier, ""));
}
SuggesterQuery suggesterQuery = builder.getSuggesterQuery();
// builder can return the suggester query if it was simple query, we ignore it in that case
if (query.equals(suggesterQuery)) {
query = null;
}
return new SuggesterData(suggesterQuery, projectList, query, builder.getQueryTextWithPlaceholder(),
builder.getIdentifier());
}
@SuppressWarnings("java:S2245")
private static ProcessedQueryData processQuery(final String text, final int caretPosition) {
if (text == null) {
throw new IllegalArgumentException("Cannot process null text");
}
if (caretPosition > text.length()) {
throw new IllegalArgumentException("Caret position has greater value than text length");
}
logger.log(Level.FINEST, "Processing suggester query: {0} at {1}", new Object[] {text, caretPosition});
String randomIdentifier = RandomStringUtils.
randomAlphabetic(IDENTIFIER_LENGTH).toLowerCase(); // OK no ROOT
while (text.contains(randomIdentifier)) {
randomIdentifier = RandomStringUtils.
randomAlphabetic(IDENTIFIER_LENGTH).toLowerCase(); // OK no ROOT
}
String newText = new StringBuilder(text).insert(caretPosition, randomIdentifier).toString();
return new ProcessedQueryData(randomIdentifier, newText);
}
private static Map<String, String> getFieldQueries(final SuggesterQueryData data) {<FILL_FUNCTION_BODY>}
private static class ProcessedQueryData {
final String identifier;
final String query;
ProcessedQueryData(final String identifier, final String query) {
this.identifier = identifier;
this.query = query;
}
}
}
|
Map<String, String> map = new HashMap<>();
map.put(QueryBuilder.FULL, data.getFull());
map.put(QueryBuilder.DEFS, data.getDefs());
map.put(QueryBuilder.REFS, data.getRefs());
map.put(QueryBuilder.PATH, data.getPath());
map.put(QueryBuilder.HIST, data.getHist());
map.put(QueryBuilder.TYPE, data.getType());
return map;
| 973
| 127
| 1,100
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/suggester/provider/filter/AuthorizationFilter.java
|
AuthorizationFilter
|
filter
|
class AuthorizationFilter implements ContainerRequestFilter {
public static final String PROJECTS_PARAM = "projects[]";
private final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
@Context
private HttpServletRequest request;
/**
* Checks if the request contains {@link #PROJECTS_PARAM} and if so then checks if the user has access to the
* specified projects.
* @param context request context
*/
@Override
public void filter(final ContainerRequestContext context) {<FILL_FUNCTION_BODY>}
}
|
if (request == null) { // happens in tests
return;
}
AuthorizationFramework auth = env.getAuthorizationFramework();
if (auth != null) {
String[] projects = request.getParameterValues(PROJECTS_PARAM);
if (projects != null) {
for (String project : projects) {
Project p = Project.getByName(project);
if (!auth.isAllowed(request, p)) {
context.abortWith(Response.status(Response.Status.FORBIDDEN).build());
}
}
}
}
| 139
| 149
| 288
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/api/v1/suggester/query/SuggesterQueryBuilder.java
|
SuggesterQueryBuilder
|
buildQuery
|
class SuggesterQueryBuilder extends QueryBuilder {
private final String suggestField;
private final String identifier;
private SuggesterQueryParser suggesterQueryParser;
/**
* @param suggestField field that contain the {@link SuggesterQuery}
* @param identifier identifier that was inserted into the query to detect the {@link SuggesterQuery}
*/
public SuggesterQueryBuilder(final String suggestField, final String identifier) {
this.suggestField = suggestField;
this.identifier = identifier;
}
public SuggesterQuery getSuggesterQuery() {
return suggesterQueryParser.getSuggesterQuery();
}
public String getIdentifier() {
return suggesterQueryParser.getIdentifier();
}
public String getQueryTextWithPlaceholder() {
return suggesterQueryParser.getQueryTextWithPlaceholder();
}
/** {@inheritDoc} */
@Override
protected Query buildQuery(final String field, final String queryText)
throws ParseException {<FILL_FUNCTION_BODY>}
}
|
if (field.equals(suggestField)) {
suggesterQueryParser = new SuggesterQueryParser(field, identifier);
return suggesterQueryParser.parse(queryText);
} else {
return new CustomQueryParser(field).parse(queryText);
}
| 274
| 71
| 345
|
<methods>public non-sealed void <init>() ,public Query build() throws ParseException,public List<java.lang.String> getContextFields() ,public java.lang.String getDefs() ,public java.lang.String getDirPath() ,public java.lang.String getFreetext() ,public java.lang.String getHist() ,public java.lang.String getPath() ,public Map<java.lang.String,java.lang.String> getQueries() ,public java.lang.String getRefs() ,public static List<java.lang.String> getSearchFields() ,public int getSize() ,public java.lang.String getType() ,public boolean isDefSearch() ,public boolean isPathSearch() ,public static boolean isSearchField(java.lang.String) ,public static java.lang.String normalizeDirPath(java.lang.String) ,public org.opengrok.indexer.search.QueryBuilder reset(org.opengrok.indexer.search.QueryBuilder) ,public org.opengrok.indexer.search.QueryBuilder setDefs(java.lang.String) ,public org.opengrok.indexer.search.QueryBuilder setDirPath(java.lang.String) ,public org.opengrok.indexer.search.QueryBuilder setFreetext(java.lang.String) ,public org.opengrok.indexer.search.QueryBuilder setHist(java.lang.String) ,public org.opengrok.indexer.search.QueryBuilder setPath(java.lang.String) ,public org.opengrok.indexer.search.QueryBuilder setRefs(java.lang.String) ,public org.opengrok.indexer.search.QueryBuilder setType(java.lang.String) <variables>public static final java.lang.String D,public static final java.lang.String DATE,public static final java.lang.String DEFS,public static final java.lang.String DIRPATH,private static final java.lang.String DIRPATH_HASH_ALGORITHM,public static final java.lang.String FULL,public static final java.lang.String FULLPATH,public static final java.lang.String HIST,public static final java.lang.String LASTREV,public static final java.lang.String LOC,public static final java.lang.String NUML,public static final java.lang.String OBJSER,public static final java.lang.String OBJUID,public static final java.lang.String OBJVER,public static final java.lang.String PATH,public static final java.lang.String PROJECT,public static final java.lang.String REFS,public static final java.lang.String SCOPES,public static final java.lang.String T,public static final java.lang.String TAGS,public static final java.lang.String TYPE,public static final java.lang.String U,private final Map<java.lang.String,java.lang.String> queries,protected static final List<java.lang.String> searchFields,private static final HashSet<java.lang.String> searchFieldsSet
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/util/DTOUtil.java
|
DTOUtil
|
createDTO
|
class DTOUtil {
private DTOUtil() {
// private to ensure static
}
// ModelMapper is thread-safe and we only need to convert different object types for now
// so it should be safe to reuse its instance.
private static final ModelMapper modelMapper = new ModelMapper();
/**
* Generate Data Transfer Object from an object. Any field in the input object
* that is annotated with <code>DTOElement</code> will be brought along.
* @param object object to use as input
* @return DTO with values and generated getters/setters from input object
*/
public static Object createDTO(Object object) {<FILL_FUNCTION_BODY>}
}
|
// ModelMapper assumes getters/setters so use BeanGenerator to provide them.
BeanGenerator beanGenerator = new BeanGenerator();
for (Field field : object.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(DTOElement.class)) {
beanGenerator.addProperty(field.getName(), field.getType());
}
}
Object bean = beanGenerator.create();
return modelMapper.map(object, bean.getClass());
| 178
| 120
| 298
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-web/src/main/java/org/opengrok/web/util/FileUtil.java
|
FileUtil
|
toFile
|
class FileUtil {
private static final RuntimeEnvironment env = RuntimeEnvironment.getInstance();
// private to enforce static
private FileUtil() {
}
/**
* @param path path relative to source root
* @return file object corresponding to the file under source root
* @throws FileNotFoundException if the file constructed from the {@code path} parameter and source root
* does not exist
* @throws InvalidPathException if the file constructed from the {@code path} parameter and source root
* leads outside source root
* @throws NoPathParameterException if the {@code path} parameter is null
*/
@SuppressWarnings("lgtm[java/path-injection]")
public static File toFile(String path) throws NoPathParameterException, IOException {<FILL_FUNCTION_BODY>}
}
|
if (path == null) {
throw new NoPathParameterException("Missing path parameter");
}
File file = new File(env.getSourceRootFile(), path);
if (!file.getCanonicalPath().startsWith(env.getSourceRootPath() + File.separator)) {
throw new InvalidPathException(path, "File points to outside of source root");
}
if (!file.exists()) {
throw new FileNotFoundException("File " + file + " not found");
}
return file;
| 199
| 134
| 333
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/entity/LdapUser.java
|
LdapUser
|
toString
|
class LdapUser implements Serializable {
private String dn; // Distinguished Name
private final Map<String, Set<String>> attributes;
private static final long serialVersionUID = 1L;
public LdapUser() {
this(null, null);
}
public LdapUser(String dn, Map<String, Set<String>> attrs) {
this.dn = dn;
this.attributes = Objects.requireNonNullElseGet(attrs, HashMap::new);
}
/**
* Set attribute value.
*
* @param key the key
* @param value set of values
* @return the value previously associated with the key
*/
public Object setAttribute(String key, Set<String> value) {
return attributes.put(key, value);
}
public Set<String> getAttribute(String key) {
return attributes.get(key);
}
public Map<String, Set<String>> getAttributes() {
return this.attributes;
}
public void setDn(String dn) {
this.dn = dn;
}
public String getDn() {
return dn;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "LdapUser{dn=" + dn + "; attributes=" + attributes + '}';
| 335
| 29
| 364
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/LdapAttrPlugin.java
|
LdapAttrPlugin
|
init
|
class LdapAttrPlugin extends AbstractLdapPlugin {
private static final Logger LOGGER = Logger.getLogger(LdapAttrPlugin.class.getName());
/**
* List of configuration names.
* <ul>
* <li><code>attribute</code> is LDAP attribute to check (mandatory)</li>
* <li><code>file</code> whitelist file (mandatory)</li>
* <li><code>instance</code> is number of <code>LdapUserInstance</code> plugin to use (optional)</li>
* </ul>
*/
static final String ATTR_PARAM = "attribute";
static final String FILE_PARAM = "file";
static final String INSTANCE_PARAM = "instance";
private static final String SESSION_ALLOWED_PREFIX = "opengrok-ldap-attr-plugin-allowed";
private String sessionAllowed = SESSION_ALLOWED_PREFIX;
private String ldapAttr;
private final Set<String> whitelist = new TreeSet<>();
private Integer ldapUserInstance;
private String filePath;
public LdapAttrPlugin() {
sessionAllowed += "-" + nextId++;
}
// for testing
void load(Map<String, Object> parameters, AbstractLdapProvider provider) {
super.load(provider);
init(parameters);
}
@Override
public void load(Map<String, Object> parameters) {
super.load(parameters);
init(parameters);
}
private void init(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
@Override
protected boolean sessionExists(HttpServletRequest req) {
return super.sessionExists(req)
&& req.getSession().getAttribute(sessionAllowed) != null;
}
String getSessionAllowedAttrName() {
return sessionAllowed;
}
@Override
public void fillSession(HttpServletRequest req, User user) {
updateSession(req, false);
LdapUser ldapUser = (LdapUser) req.getSession().getAttribute(LdapUserPlugin.getSessionAttrName(ldapUserInstance));
if (ldapUser == null) {
LOGGER.log(Level.WARNING, "cannot get {0} attribute from {1}",
new Object[]{LdapUserPlugin.SESSION_ATTR, user});
return;
}
// Check attributes cached in LDAP user object first, then query LDAP server
// (and if found, cache the result in the LDAP user object).
Set<String> attributeValues = ldapUser.getAttribute(ldapAttr);
if (attributeValues == null) {
Map<String, Set<String>> records = null;
AbstractLdapProvider ldapProvider = getLdapProvider();
try {
String dn = ldapUser.getDn();
if (dn != null) {
LOGGER.log(Level.FINEST, "searching with dn={0} on {1}",
new Object[]{dn, ldapProvider});
AbstractLdapProvider.LdapSearchResult<Map<String, Set<String>>> res;
if ((res = ldapProvider.lookupLdapContent(dn, new String[]{ldapAttr})) == null) {
LOGGER.log(Level.WARNING, "cannot lookup attributes {0} for user {1} on {2})",
new Object[]{ldapAttr, ldapUser, ldapProvider});
return;
}
records = res.getAttrs();
} else {
LOGGER.log(Level.FINE, "no DN for LDAP user {0} on {1}",
new Object[]{ldapUser, ldapProvider});
}
} catch (LdapException ex) {
throw new AuthorizationException(ex);
}
if (records == null || records.isEmpty() || (attributeValues = records.get(ldapAttr)) == null) {
LOGGER.log(Level.WARNING, "empty records or attribute values {0} for user {1} on {2}",
new Object[]{ldapAttr, ldapUser, ldapProvider});
return;
}
ldapUser.setAttribute(ldapAttr, attributeValues);
}
boolean isAttrInWhitelist = attributeValues.stream().anyMatch(whitelist::contains);
LOGGER.log(Level.FINEST, "LDAP user {0} {1} against {2}",
new Object[]{ldapUser, isAttrInWhitelist ? "allowed" : "denied", filePath});
updateSession(req, isAttrInWhitelist);
}
/**
* Add a new allowed value into the session.
*
* @param req the request
* @param allowed the new value
*/
private void updateSession(HttpServletRequest req, boolean allowed) {
req.getSession().setAttribute(sessionAllowed, allowed);
}
@Override
public boolean checkEntity(HttpServletRequest request, Project project) {
return ((Boolean) Objects.requireNonNullElse(request.getSession().getAttribute(sessionAllowed), false));
}
@Override
public boolean checkEntity(HttpServletRequest request, Group group) {
return ((Boolean) Objects.requireNonNullElse(request.getSession().getAttribute(sessionAllowed), false));
}
}
|
if ((ldapAttr = (String) parameters.get(ATTR_PARAM)) == null) {
throw new NullPointerException("Missing param [" + ATTR_PARAM + "] in the setup");
}
if ((filePath = (String) parameters.get(FILE_PARAM)) == null) {
throw new NullPointerException("Missing param [" + FILE_PARAM + "] in the setup");
}
String instance = (String) parameters.get(INSTANCE_PARAM);
if (instance != null) {
ldapUserInstance = Integer.parseInt(instance);
}
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.forEach(whitelist::add);
} catch (IOException e) {
throw new IllegalArgumentException(String.format("Unable to read the file \"%s\"", filePath), e);
}
LOGGER.log(Level.FINE, "LdapAttrPlugin plugin loaded with attr={0}, whitelist={1} ({2} entries), " +
"instance={3}", new Object[]{ldapAttr, filePath, whitelist.size(), ldapUserInstance});
| 1,392
| 295
| 1,687
|
<methods>public abstract boolean checkEntity(HttpServletRequest, org.opengrok.indexer.configuration.Project) ,public abstract boolean checkEntity(HttpServletRequest, org.opengrok.indexer.configuration.Group) ,public abstract void fillSession(HttpServletRequest, opengrok.auth.plugin.entity.User) ,public opengrok.auth.plugin.configuration.Configuration getConfiguration() ,public opengrok.auth.plugin.ldap.AbstractLdapProvider getLdapProvider() ,public boolean isAllowed(HttpServletRequest, org.opengrok.indexer.configuration.Project) ,public boolean isAllowed(HttpServletRequest, org.opengrok.indexer.configuration.Group) ,public void load(Map<java.lang.String,java.lang.Object>) ,public void unload() <variables>protected static final java.lang.String CONFIGURATION_PARAM,private static final Map<java.lang.String,opengrok.auth.plugin.configuration.Configuration> LOADED_CONFIGURATIONS,private static final java.lang.String SESSION_PREFIX,private opengrok.auth.plugin.configuration.Configuration cfg,private opengrok.auth.plugin.ldap.AbstractLdapProvider ldapProvider,protected static long nextId,protected java.lang.String sessionEstablished,protected java.lang.String sessionUsername
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/LdapFilterPlugin.java
|
LdapFilterPlugin
|
load
|
class LdapFilterPlugin extends AbstractLdapPlugin {
private static final Logger LOGGER = Logger.getLogger(LdapFilterPlugin.class.getName());
protected static final String FILTER_PARAM = "filter";
protected static final String TRANSFORMS_PARAM = "transforms";
private static final String SESSION_ALLOWED_PREFIX = "opengrok-filter-plugin-allowed";
static final String INSTANCE = "instance";
private String sessionAllowed = SESSION_ALLOWED_PREFIX;
/**
* List of configuration names.
* <ul>
* <li><code>filter</code> is LDAP filter used for searching (mandatory)</li>
* <li><code>instance</code> is number of <code>LdapUserInstance</code> plugin to use (optional)</li>
* <li><code>transforms</code> are comma separated string transforms, where each transform is name:value pair,
* allowed values: <code>toLowerCase</code>, <code>toUpperCase</code></li>
* </ul>
*/
private String ldapFilter;
private Integer ldapUserInstance;
private Map<String, String> transforms;
public LdapFilterPlugin() {
sessionAllowed += "-" + nextId++;
}
@Override
public void load(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
void loadTransforms(String transformsString) throws NullPointerException {
transforms = new TreeMap<>();
String[] transformsArray = transformsString.split(",");
for (String elem: transformsArray) {
String[] tran = elem.split(":");
transforms.put(tran[0], tran[1]);
}
FilterUtil.checkTransforms(transforms);
}
@Override
protected boolean sessionExists(HttpServletRequest req) {
return super.sessionExists(req)
&& req.getSession().getAttribute(sessionAllowed) != null;
}
private String getSessionAttr() {
return (LdapUserPlugin.SESSION_ATTR + (ldapUserInstance != null ? ldapUserInstance.toString() : ""));
}
@Override
public void fillSession(HttpServletRequest req, User user) {
LdapUser ldapUser;
updateSession(req, false);
if ((ldapUser = (LdapUser) req.getSession().getAttribute(getSessionAttr())) == null) {
LOGGER.log(Level.WARNING, "failed to get LDAP attribute ''{0}'' from session for user {1}",
new Object[]{LdapUserPlugin.SESSION_ATTR, user});
return;
}
String expandedFilter = expandFilter(ldapFilter, ldapUser, user);
LOGGER.log(Level.FINEST, "expanded filter ''{0}'' for user {1} and LDAP user {2} into ''{3}''",
new Object[]{ldapFilter, user, ldapUser, expandedFilter});
AbstractLdapProvider ldapProvider = getLdapProvider();
try {
if ((ldapProvider.lookupLdapContent(null, expandedFilter)) == null) {
LOGGER.log(Level.FINER,
"empty content for LDAP user {0} with filter ''{1}'' on {2}",
new Object[]{ldapUser, expandedFilter, ldapProvider});
return;
}
} catch (LdapException ex) {
throw new AuthorizationException(ex);
}
LOGGER.log(Level.FINER, "LDAP user {0} allowed on {1}",
new Object[]{ldapUser, ldapProvider});
updateSession(req, true);
}
/**
* Expand {@code LdapUser} / {@code User} object attribute values into the filter.
* Use \% for printing the '%' character.
*
* @param filter basic filter containing the special values
* @param ldapUser user from LDAP
* @param user user from the request
* @return the filter with replacements
* @see opengrok.auth.plugin.util.FilterUtil
*/
String expandFilter(String filter, LdapUser ldapUser, User user) {
filter = expandUserFilter(user, filter, transforms);
for (Entry<String, Set<String>> entry : ldapUser.getAttributes().entrySet()) {
if (entry.getValue().size() == 1) {
String name = entry.getKey();
String value = entry.getValue().iterator().next();
try {
filter = replace(filter, name, value, transforms);
} catch (PatternSyntaxException ex) {
LOGGER.log(Level.WARNING,
String.format("Failed to expand filter ''%s'' with name ''%s'' and value ''%s''",
filter, name, value), ex);
}
}
}
filter = filter.replace("\\%", "%");
return filter;
}
/**
* Add a new allowed value into the session.
*
* @param req the request
* @param allowed the new value
*/
protected void updateSession(HttpServletRequest req, boolean allowed) {
req.getSession().setAttribute(sessionAllowed, allowed);
}
@Override
public boolean checkEntity(HttpServletRequest request, Project project) {
return ((Boolean) Objects.requireNonNullElse(request.getSession().getAttribute(sessionAllowed), false));
}
@Override
public boolean checkEntity(HttpServletRequest request, Group group) {
return ((Boolean) Objects.requireNonNullElse(request.getSession().getAttribute(sessionAllowed), false));
}
}
|
super.load(parameters);
if ((ldapFilter = (String) parameters.get(FILTER_PARAM)) == null) {
throw new NullPointerException("Missing param [" + FILTER_PARAM + "] in the setup");
}
String instance = (String) parameters.get(INSTANCE);
if (instance != null) {
ldapUserInstance = Integer.parseInt(instance);
}
String transformsString = (String) parameters.get(TRANSFORMS_PARAM);
if (transformsString != null) {
loadTransforms(transformsString);
}
LOGGER.log(Level.FINE, "LdapFilter plugin loaded with filter={0}, instance={1}, transforms={2}",
new Object[]{ldapFilter, ldapUserInstance, transforms});
| 1,482
| 211
| 1,693
|
<methods>public abstract boolean checkEntity(HttpServletRequest, org.opengrok.indexer.configuration.Project) ,public abstract boolean checkEntity(HttpServletRequest, org.opengrok.indexer.configuration.Group) ,public abstract void fillSession(HttpServletRequest, opengrok.auth.plugin.entity.User) ,public opengrok.auth.plugin.configuration.Configuration getConfiguration() ,public opengrok.auth.plugin.ldap.AbstractLdapProvider getLdapProvider() ,public boolean isAllowed(HttpServletRequest, org.opengrok.indexer.configuration.Project) ,public boolean isAllowed(HttpServletRequest, org.opengrok.indexer.configuration.Group) ,public void load(Map<java.lang.String,java.lang.Object>) ,public void unload() <variables>protected static final java.lang.String CONFIGURATION_PARAM,private static final Map<java.lang.String,opengrok.auth.plugin.configuration.Configuration> LOADED_CONFIGURATIONS,private static final java.lang.String SESSION_PREFIX,private opengrok.auth.plugin.configuration.Configuration cfg,private opengrok.auth.plugin.ldap.AbstractLdapProvider ldapProvider,protected static long nextId,protected java.lang.String sessionEstablished,protected java.lang.String sessionUsername
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/UserPlugin.java
|
UserPlugin
|
load
|
class UserPlugin implements IAuthorizationPlugin {
private static final Logger LOGGER = Logger.getLogger(UserPlugin.class.getName());
static final String DECODER_CLASS_PARAM = "decoder";
public static final String REQUEST_ATTR = "opengrok-user-plugin-user";
private IUserDecoder decoder;
public UserPlugin() {
}
// for testing
protected UserPlugin(IUserDecoder decoder) {
this.decoder = decoder;
}
private IUserDecoder getDecoder(String name) throws ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> clazz = Class.forName(name);
Constructor<?> constructor = clazz.getConstructor();
Object instance = constructor.newInstance();
return (IUserDecoder) instance;
}
@Override
public void load(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
@Override
public void unload() {
// no state to free
}
private User getUser(HttpServletRequest request) {
User user;
if ((user = (User) request.getAttribute(REQUEST_ATTR)) == null) {
user = decoder.fromRequest(request);
request.setAttribute(REQUEST_ATTR, user);
}
return user;
}
@Override
public boolean isAllowed(HttpServletRequest request, Project project) {
return getUser(request) != null;
}
@Override
public boolean isAllowed(HttpServletRequest request, Group group) {
return getUser(request) != null;
}
}
|
String decoderName;
if ((decoderName = (String) parameters.get(DECODER_CLASS_PARAM)) == null) {
throw new NullPointerException(String.format("missing " +
"parameter '%s' in %s configuration",
DECODER_CLASS_PARAM, UserPlugin.class.getName()));
}
LOGGER.log(Level.INFO, "loading decoder: {0}", decoderName);
try {
decoder = getDecoder(decoderName);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException |
InvocationTargetException | InstantiationException e) {
throw new UserDecoderException(decoderName, e);
}
| 437
| 177
| 614
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/UserWhiteListPlugin.java
|
UserWhiteListPlugin
|
load
|
class UserWhiteListPlugin implements IAuthorizationPlugin {
private static final String CLASS_NAME = UserWhiteListPlugin.class.getName();
private static final Logger LOGGER = Logger.getLogger(CLASS_NAME);
// configuration parameters
static final String FILE_PARAM = "file";
static final String FIELD_PARAM = "fieldName";
// valid values for the FIELD_NAME parameter
static final String USERNAME_FIELD = "username";
static final String ID_FIELD = "id";
private final Set<String> whitelist = new TreeSet<>();
private String fieldName;
@Override
public void load(Map<String, Object> parameters) {<FILL_FUNCTION_BODY>}
@TestOnly
Set<String> getWhitelist() {
return whitelist;
}
@Override
public void unload() {
whitelist.clear();
}
private boolean checkWhitelist(HttpServletRequest request) {
User user;
String attrName = UserPlugin.REQUEST_ATTR;
if ((user = (User) request.getAttribute(attrName)) == null) {
LOGGER.log(Level.WARNING, "cannot get {0} attribute", attrName);
return false;
}
if (fieldName.equals(USERNAME_FIELD)) {
return user.getUsername() != null && whitelist.contains(user.getUsername());
} else if (fieldName.equals(ID_FIELD)) {
return user.getId() != null && whitelist.contains(user.getId());
}
return false;
}
@Override
public boolean isAllowed(HttpServletRequest request, Project project) {
return checkWhitelist(request);
}
@Override
public boolean isAllowed(HttpServletRequest request, Group group) {
return checkWhitelist(request);
}
}
|
if (parameters == null) {
throw new IllegalArgumentException("Null parameter");
}
String filePath;
if ((filePath = (String) parameters.get(FILE_PARAM)) == null) {
throw new IllegalArgumentException("Missing parameter [" + FILE_PARAM + "] in the configuration");
}
if ((fieldName = (String) parameters.get(FIELD_PARAM)) == null) {
fieldName = USERNAME_FIELD;
} else if (!fieldName.equals(USERNAME_FIELD) && !fieldName.equals(ID_FIELD)) {
throw new IllegalArgumentException("Invalid value of parameter [" + FIELD_PARAM +
"] in the configuration: only " + USERNAME_FIELD + " or " + ID_FIELD + " are supported");
}
// Load whitelist from file to memory.
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.map(String::strip).forEach(whitelist::add);
} catch (IOException e) {
throw new IllegalArgumentException(String.format("Unable to read the file \"%s\"", filePath), e);
}
LOGGER.log(Level.FINE, "UserWhiteList plugin loaded with filePath={0} ({1} entries), fieldName={2}",
new Object[]{filePath, whitelist.size(), fieldName});
| 482
| 340
| 822
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/configuration/Configuration.java
|
Configuration
|
encodeObject
|
class Configuration implements Serializable {
private static final long serialVersionUID = -1;
private List<LdapServer> servers = new ArrayList<>();
private int interval;
private String searchBase;
private WebHooks webHooks;
private int searchTimeout;
private int connectTimeout;
private int readTimeout;
private int countLimit;
public void setServers(List<LdapServer> servers) {
this.servers = servers;
}
public List<LdapServer> getServers() {
return servers;
}
public void setWebHooks(WebHooks webHooks) {
this.webHooks = webHooks;
}
public WebHooks getWebHooks() {
return webHooks;
}
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public int getSearchTimeout() {
return this.searchTimeout;
}
public void setSearchTimeout(int timeout) {
this.searchTimeout = timeout;
}
public int getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(int timeout) {
this.connectTimeout = timeout;
}
public int getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(int timeout) {
this.readTimeout = timeout;
}
public int getCountLimit() {
return this.countLimit;
}
public void setCountLimit(int limit) {
this.countLimit = limit;
}
public String getSearchBase() {
return searchBase;
}
public void setSearchBase(String base) {
this.searchBase = base;
}
public String getXMLRepresentationAsString() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
this.encodeObject(bos);
return bos.toString();
}
private void encodeObject(OutputStream out) {<FILL_FUNCTION_BODY>}
/**
* Read a configuration from a file in XML format.
*
* @param file input file
* @return the new configuration object
* @throws IOException if any error occurs
*/
public static Configuration read(File file) throws IOException {
try (FileInputStream in = new FileInputStream(file)) {
return decodeObject(in);
}
}
/**
* Read a configuration from a string in xml format.
*
* @param xmlconfig input string
* @return the new configuration object
* @throws IOException if any error occurs
*/
public static Configuration makeXMLStringAsConfiguration(String xmlconfig) throws IOException {
final Configuration ret;
final ByteArrayInputStream in = new ByteArrayInputStream(xmlconfig.getBytes());
ret = decodeObject(in);
return ret;
}
private static Configuration decodeObject(InputStream in) throws IOException {
final Object ret;
try (XMLDecoder d = new XMLDecoder(new BufferedInputStream(in), null, null,
new PluginConfigurationClassLoader())) {
ret = d.readObject();
}
if (!(ret instanceof Configuration)) {
throw new IOException("Not a valid configuration file");
}
return (Configuration) ret;
}
}
|
try (XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out))) {
e.writeObject(this);
}
| 852
| 41
| 893
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/configuration/PluginConfigurationClassLoader.java
|
PluginConfigurationClassLoader
|
loadClass
|
class PluginConfigurationClassLoader extends ClassLoader {
private static final Set<String> allowedClasses = Set.of(
Collections.class,
Configuration.class,
LdapServer.class,
String.class,
WebHook.class,
WebHooks.class,
XMLDecoder.class
).stream().map(Class::getName).collect(Collectors.toSet());
@Override
public Class<?> loadClass(final String name) throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
}
|
if (!allowedClasses.contains(name)) {
throw new IllegalAccessError(name + " is not allowed to be used in configuration");
}
return getClass().getClassLoader().loadClass(name);
| 135
| 54
| 189
|
<methods>public void clearAssertionStatus() ,public final java.lang.Package getDefinedPackage(java.lang.String) ,public final java.lang.Package[] getDefinedPackages() ,public java.lang.String getName() ,public final java.lang.ClassLoader getParent() ,public static java.lang.ClassLoader getPlatformClassLoader() ,public java.net.URL getResource(java.lang.String) ,public java.io.InputStream getResourceAsStream(java.lang.String) ,public Enumeration<java.net.URL> getResources(java.lang.String) throws java.io.IOException,public static java.lang.ClassLoader getSystemClassLoader() ,public static java.net.URL getSystemResource(java.lang.String) ,public static java.io.InputStream getSystemResourceAsStream(java.lang.String) ,public static Enumeration<java.net.URL> getSystemResources(java.lang.String) throws java.io.IOException,public final java.lang.Module getUnnamedModule() ,public final boolean isRegisteredAsParallelCapable() ,public Class<?> loadClass(java.lang.String) throws java.lang.ClassNotFoundException,public Stream<java.net.URL> resources(java.lang.String) ,public void setClassAssertionStatus(java.lang.String, boolean) ,public void setDefaultAssertionStatus(boolean) ,public void setPackageAssertionStatus(java.lang.String, boolean) <variables>static final boolean $assertionsDisabled,final java.lang.Object assertionLock,Map<java.lang.String,java.lang.Boolean> classAssertionStatus,private volatile ConcurrentHashMap<?,?> classLoaderValueMap,private final ArrayList<Class<?>> classes,private boolean defaultAssertionStatus,private final java.security.ProtectionDomain defaultDomain,private final jdk.internal.loader.NativeLibraries libraries,private final java.lang.String name,private final java.lang.String nameAndId,private static final java.security.cert.Certificate[] nocerts,private final ConcurrentHashMap<java.lang.String,java.security.cert.Certificate[]> package2certs,private Map<java.lang.String,java.lang.Boolean> packageAssertionStatus,private final ConcurrentHashMap<java.lang.String,java.lang.NamedPackage> packages,private final ConcurrentHashMap<java.lang.String,java.lang.Object> parallelLockMap,private final java.lang.ClassLoader parent,private static volatile java.lang.ClassLoader scl,private final java.lang.Module unnamedModule
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/decoders/MellonHeaderDecoder.java
|
MellonHeaderDecoder
|
fromRequest
|
class MellonHeaderDecoder implements IUserDecoder {
private static final Logger LOGGER = Logger.getLogger(MellonHeaderDecoder.class.getName());
static final String MELLON_EMAIL_HEADER = "MELLON_email";
static final String MELLON_USERNAME_HEADER = "MELLON_username";
@Override
public User fromRequest(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
}
|
// e-mail is mandatory.
String id = request.getHeader(MELLON_EMAIL_HEADER);
if (id == null || id.isEmpty()) {
LOGGER.log(Level.WARNING,
"Can not construct User object: header ''{1}'' not found in request headers: {0}",
new Object[]{String.join(",", Collections.list(request.getHeaderNames())),
MELLON_EMAIL_HEADER});
return null;
}
// username is optional.
String username = request.getHeader(MELLON_USERNAME_HEADER);
return new User(username, id);
| 120
| 165
| 285
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/decoders/OSSOHeaderDecoder.java
|
OSSOHeaderDecoder
|
fromRequest
|
class OSSOHeaderDecoder implements IUserDecoder {
private static final Logger LOGGER = Logger.getLogger(OSSOHeaderDecoder.class.getName());
protected static final String OSSO_COOKIE_TIMESTAMP_HEADER = "osso-cookie-timestamp";
protected static final String OSSO_TIMEOUT_EXCEEDED_HEADER = "osso-idle-timeout-exceeded";
protected static final String OSSO_SUBSCRIBER_DN_HEADER = "osso-subscriber-dn";
protected static final String OSSO_SUBSCRIBER_HEADER = "osso-subscriber";
protected static final String OSSO_USER_DN_HEADER = "osso-user-dn";
protected static final String OSSO_USER_GUID_HEADER = "osso-user-guid";
@Override
public User fromRequest(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
}
|
Date cookieTimestamp = null;
// Avoid classification as a taint bug.
var username = Laundromat.launderInput(request.getHeader(OSSO_USER_DN_HEADER));
var timeouted = Laundromat.launderInput(request.getHeader(OSSO_TIMEOUT_EXCEEDED_HEADER));
var timestamp = Laundromat.launderInput(request.getHeader(OSSO_COOKIE_TIMESTAMP_HEADER));
var userguid = Laundromat.launderInput(request.getHeader(OSSO_USER_GUID_HEADER));
if (username == null || username.isEmpty()) {
LOGGER.log(Level.WARNING,
"Can not construct an user: username could not be extracted from headers: {0}",
String.join(",", Collections.list(request.getHeaderNames())));
return null;
}
if (userguid == null || userguid.isEmpty()) {
LOGGER.log(Level.WARNING,
"Can not construct an user: userguid could not be extracted from headers: {0}",
String.join(",", Collections.list(request.getHeaderNames())));
return null;
}
/*
The timestamp cookie can be corrupted.
*/
try {
cookieTimestamp = Timestamp.decodeTimeCookie(timestamp);
} catch (NumberFormatException ex) {
LOGGER.log(Level.WARNING,
String.format("Unparseable timestamp cookie \"%s\" for user \"%s\"",
timestamp, username), ex);
}
/*
Creating new user entity with provided information. The entity can be
checked if the timeout expired via {@link User#isTimeouted()}.
*/
User user = new User(username, userguid, cookieTimestamp,
"true".equalsIgnoreCase(timeouted));
user.setAttribute("subscriber-dn", request.getHeader(OSSO_SUBSCRIBER_DN_HEADER));
user.setAttribute("subscriber", request.getHeader(OSSO_SUBSCRIBER_HEADER));
if (user.isTimeouted()) {
LOGGER.log(Level.WARNING, "Can not construct an user \"{0}\": header is timeouted",
username);
return null;
}
return user;
| 249
| 590
| 839
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/decoders/UserPrincipalDecoder.java
|
UserPrincipalDecoder
|
fromRequest
|
class UserPrincipalDecoder implements IUserDecoder {
private static final Logger LOGGER = Logger.getLogger(UserPrincipalDecoder.class.getName());
@Override
public User fromRequest(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
}
|
if (request.getUserPrincipal() == null) {
return null;
}
String username = request.getUserPrincipal().getName();
if (username == null || username.isEmpty()) {
LOGGER.log(Level.WARNING,
"Can not construct User object: cannot get user principal from: {0}",
request);
return null;
}
return new User(username);
| 72
| 105
| 177
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/entity/User.java
|
User
|
toString
|
class User {
private String id;
private String username;
private Date cookieTimestamp;
private boolean timeouted;
private final Map<String, Object> attrs = new HashMap<>();
public User(String username) {
this.username = username;
}
/**
* Construct User object.
* @param username username
* @param id user ID
*/
public User(String username, String id) {
this.username = username;
this.id = id;
}
/**
* Construct User object.
* @param username username
* @param id user ID
* @param cookieTimestamp cookie time stamp
* @param timeouted is the user timed out
*/
public User(String username, String id, Date cookieTimestamp, boolean timeouted) {
this(username, id);
this.cookieTimestamp = cookieTimestamp;
this.timeouted = timeouted;
}
public String getId() {
return id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getCookieTimestamp() {
return cookieTimestamp;
}
public boolean getTimeouted() {
return isTimeouted();
}
public boolean isTimeouted() {
return timeouted;
}
/**
* Set custom user property.
*
* @param key the key
* @param value the value
* @return the value previously associated with the key
*/
public Object setAttribute(String key, Object value) {
return attrs.put(key, value);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "User{" + "id=" + id + ", username=" + username + ", cookieTimestamp=" + cookieTimestamp +
", timeouted=" + timeouted + ", attrs=" + attrs + '}';
| 454
| 56
| 510
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/ldap/FakeLdapFacade.java
|
FakeLdapFacade
|
lookupLdapContent
|
class FakeLdapFacade extends AbstractLdapProvider {
@Override
public LdapSearchResult<Map<String, Set<String>>> lookupLdapContent(String dn, String filter, String[] values) {<FILL_FUNCTION_BODY>}
@Override
public boolean isConfigured() {
return true;
}
@Override
public void close() {
// No need to close anything as this is fake plugin.
}
}
|
Map<String, Set<String>> map = new TreeMap<>();
filter = filter == null ? "objectclass=*" : filter;
values = values == null ? new String[]{"dn", "ou"} : values;
if ("objectclass=*".equals(filter)) {
List<String> v = Arrays.asList(values);
if (v.isEmpty()) {
map.put("mail", new TreeSet<>(List.of("james@bond.com")));
map.put("ou", new TreeSet<>(List.of("MI6")));
} else {
for (String x : v) {
if (x.equals("uid")) {
map.put("uid", new TreeSet<>(List.of("bondjame")));
}
}
}
return new LdapSearchResult<>("fakedn", map);
}
if (filter.contains("objectclass")) {
map.put("dn", new TreeSet<>(Arrays.asList("cn=mi6,cn=mi6,cn=james,dc=bond,dc=com",
"cn=mi7,cn=mi7,cn=james,dc=bond,dc=com")));
}
return new LdapSearchResult<>("fakedn", map);
| 122
| 327
| 449
|
<methods>public non-sealed void <init>() ,public abstract void close() ,public abstract boolean isConfigured() ,public LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String) throws opengrok.auth.plugin.ldap.LdapException,public LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String, java.lang.String) throws opengrok.auth.plugin.ldap.LdapException,public LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String, java.lang.String[]) throws opengrok.auth.plugin.ldap.LdapException,public abstract LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String, java.lang.String, java.lang.String[]) throws opengrok.auth.plugin.ldap.LdapException<variables>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/ldap/LdapFacade.java
|
ContentAttributeMapper
|
isConfigured
|
class ContentAttributeMapper implements AttributeMapper<Map<String, Set<String>>> {
private final String[] values;
/**
* Create a new mapper which retrieves the given values in the resulting
* set.
*
* @param values include these values in the result
*/
ContentAttributeMapper(String[] values) {
this.values = values;
}
@Override
public Map<String, Set<String>> mapFromAttributes(Attributes attrs) throws NamingException {
Map<String, Set<String>> map = new HashMap<>();
if (values == null) {
for (NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); attrEnum.hasMore();) {
Attribute attr = attrEnum.next();
addAttrToMap(map, attr);
}
} else {
for (String value : values) {
Attribute attr = attrs.get(value);
if (attr == null) {
continue;
}
addAttrToMap(map, attr);
}
}
return map;
}
private void addAttrToMap(Map<String, Set<String>> map, Attribute attr) throws NamingException {
map.computeIfAbsent(attr.getID(), key -> new TreeSet<>());
final Set<String> valueSet = map.get(attr.getID());
for (NamingEnumeration<?> attrAll = attr.getAll(); attrAll.hasMore(); ) {
valueSet.add((String) attrAll.next());
}
}
}
public LdapFacade(Configuration cfg) {
setServers(cfg.getServers(), cfg.getConnectTimeout(), cfg.getReadTimeout());
setInterval(cfg.getInterval());
setSearchBase(cfg.getSearchBase());
setWebHooks(cfg.getWebHooks());
// Anti-pattern: do some non trivial stuff in the constructor.
prepareSearchControls(cfg.getSearchTimeout(), cfg.getCountLimit());
prepareServers();
}
private void setWebHooks(WebHooks webHooks) {
this.webHooks = webHooks;
}
/**
* Go through all servers in the pool and record the first working.
*/
void prepareServers() {
LOGGER.log(Level.FINER, "checking servers for {0}", this);
for (int i = 0; i < servers.size(); i++) {
LdapServer server = servers.get(i);
if (server.isWorking() && actualServer == -1) {
actualServer = i;
}
}
// Close the connections to the inactive servers.
LOGGER.log(Level.FINER, "closing unused servers");
for (int i = 0; i < servers.size(); i++) {
if (i != actualServer) {
servers.get(i).close();
}
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, String.format("server check done (current server: %s)",
actualServer != -1 ? servers.get(actualServer) : "N/A"));
}
}
/**
* Closes all available servers.
*/
@Override
public void close() {
for (LdapServer server : servers) {
server.close();
}
}
public List<LdapServer> getServers() {
return servers;
}
public LdapFacade setServers(List<LdapServer> servers, int connectTimeout, int readTimeout) {
this.servers = servers;
// Inherit timeout values from server pool configuration.
for (LdapServer server : servers) {
if (server.getConnectTimeout() == 0 && connectTimeout != 0) {
server.setConnectTimeout(connectTimeout);
}
if (server.getReadTimeout() == 0 && readTimeout != 0) {
server.setReadTimeout(readTimeout);
}
}
return this;
}
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
for (LdapServer server : servers) {
server.setInterval(interval);
}
}
public String getSearchBase() {
return searchBase;
}
public void setSearchBase(String base) {
this.searchBase = base;
}
@Override
public boolean isConfigured() {<FILL_FUNCTION_BODY>
|
return servers != null && !servers.isEmpty() && searchBase != null && actualServer != -1;
| 1,183
| 30
| 1,213
|
<methods>public non-sealed void <init>() ,public abstract void close() ,public abstract boolean isConfigured() ,public LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String) throws opengrok.auth.plugin.ldap.LdapException,public LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String, java.lang.String) throws opengrok.auth.plugin.ldap.LdapException,public LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String, java.lang.String[]) throws opengrok.auth.plugin.ldap.LdapException,public abstract LdapSearchResult<Map<java.lang.String,Set<java.lang.String>>> lookupLdapContent(java.lang.String, java.lang.String, java.lang.String[]) throws opengrok.auth.plugin.ldap.LdapException<variables>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/util/FilterUtil.java
|
FilterUtil
|
replace
|
class FilterUtil {
private FilterUtil() {
// utility class
}
private static final String LOWER_CASE = "toLowerCase";
private static final String UPPER_CASE = "toUpperCase";
/**
* Verify the names of the transforms in the map.
* @param transforms map of attribute transforms. Valid values: <code>toLowerCase, toUpperCase</code>
* @throws UnsupportedOperationException in case of invalid transform name
*/
public static void checkTransforms(Map<String, String> transforms) {
Set<String> possibleTransforms = new HashSet<>(Arrays.asList(LOWER_CASE, UPPER_CASE));
for (String transform : transforms.values()) {
if (!possibleTransforms.contains(transform)) {
throw new UnsupportedOperationException(String.format("invalid transform: %s", transform));
}
}
}
static String doTransform(String value, String transform) {
switch (transform) {
case LOWER_CASE:
return value.toLowerCase(Locale.ROOT);
case UPPER_CASE:
return value.toUpperCase(Locale.ROOT);
default:
throw new UnsupportedOperationException(String.format("transform '%s' is unsupported", transform));
}
}
/**
* Expand attributes in filter string.
* @param filter input string
* @param name attribute name
* @param value value to replace
* @param transforms map of transformations to be potentially applied on the value
* @return new value of the string
*/
public static String replace(String filter, String name, String value, Map<String, String> transforms) {<FILL_FUNCTION_BODY>}
/**
* Replace attribute names with values in filter string.
* @param user User object
* @param filter filter string
* @return filter with the values replaced
* @see #expandUserFilter(User, String, Map)
*/
public static String expandUserFilter(User user, String filter) {
return expandUserFilter(user, filter, null);
}
/**
* Expand {@code User} object attribute values into the filter.
*
* Special values are:
* <ul>
* <li>%username% - to be replaced with username value from the User object</li>
* <li>%guid% - to be replaced with guid value from the User object</li>
* </ul>
*
* @param user User object from the request (created by {@code UserPlugin})
* @param filter filter
* @param transforms map of transforms
* @return replaced result
*/
public static String expandUserFilter(User user, String filter, Map<String, String> transforms) {
if (user.getUsername() != null) {
filter = replace(filter, "username", user.getUsername(), transforms);
}
if (user.getId() != null) {
filter = replace(filter, "guid", user.getId(), transforms);
}
return filter;
}
}
|
if (transforms != null) {
String transform;
if ((transform = transforms.get(name)) != null) {
value = doTransform(value, transform);
}
}
return filter.replaceAll("(?<!\\\\)%" + name + "(?<!\\\\)%", value);
| 794
| 86
| 880
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/util/RestfulClient.java
|
RestfulClient
|
postIt
|
class RestfulClient {
private static final Logger LOGGER = Logger.getLogger(RestfulClient.class.getName());
private RestfulClient() {
// private to ensure static
}
/**
* Perform HTTP POST request.
* @param uri URI
* @param input JSON string contents
* @return HTTP status or -1
*/
public static int postIt(String uri, String input) {<FILL_FUNCTION_BODY>}
}
|
int result;
try {
try (Client client = ClientBuilder.newBuilder().
connectTimeout(RuntimeEnvironment.getInstance().getConnectTimeout(), TimeUnit.SECONDS).build()) {
LOGGER.log(Level.FINEST, "sending REST POST request to {0}: {1}",
new Object[]{uri, input});
try (Response response = client.target(uri)
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(input, MediaType.APPLICATION_JSON))) {
int status = response.getStatus();
if (status != HttpServletResponse.SC_CREATED) {
LOGGER.log(Level.WARNING, "REST request failed: HTTP error code : {0}", status);
}
result = status;
}
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "REST request failed", e);
result = -1;
}
return result;
| 120
| 248
| 368
|
<no_super_class>
|
oracle_opengrok
|
opengrok/plugins/src/main/java/opengrok/auth/plugin/util/WebHook.java
|
WebHook
|
post
|
class WebHook implements Serializable {
private static final long serialVersionUID = -1;
private String uri;
private String content;
public WebHook() {
}
WebHook(String uri, String content) {
this.uri = uri;
this.content = content;
}
public void setURI(String uri) {
this.uri = uri;
}
public String getURI() {
return uri;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public Future<String> post() {<FILL_FUNCTION_BODY>}
}
|
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool(new OpenGrokThreadFactory("webhook-")).submit(() -> {
int status = RestfulClient.postIt(getURI(), getContent());
completableFuture.complete(String.valueOf(status));
return null;
});
return completableFuture;
| 180
| 100
| 280
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/LookupPriorityQueue.java
|
LookupPriorityQueue
|
getResult
|
class LookupPriorityQueue extends PriorityQueue<LookupResultItem> {
private final int maxSize;
LookupPriorityQueue(final int maxSize) {
super(maxSize);
this.maxSize = maxSize;
}
/** {@inheritDoc} */
@Override
protected boolean lessThan(final LookupResultItem item1, final LookupResultItem item2) {
return item1.getScore() < item2.getScore();
}
/**
* Transforms queue values into list sorted from highest scores to the lowest.
* @return list of the values
*/
List<LookupResultItem> getResult() {<FILL_FUNCTION_BODY>}
/**
* Determines whether element with {@code score} would be inserted into this queue.
* @param score score of the element to insert
* @return {@code true} if the element would be inserted. {@code false} otherwise.
*/
boolean canInsert(final long score) {
if (size() < maxSize) {
return true;
}
return size() > 0 && score >= top().getScore();
}
}
|
int size = this.size();
LookupResultItem[] res = new LookupResultItem[size];
for (int i = size - 1; i >= 0; i--) { // iterate from top so results are ordered in descending order
res[i] = this.pop();
}
return Arrays.asList(res);
| 286
| 89
| 375
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/LookupResultItem.java
|
LookupResultItem
|
combine
|
class LookupResultItem implements Comparable<LookupResultItem> {
private final String phrase;
private final Set<String> projects = new HashSet<>();
private long score;
LookupResultItem(final String phrase, final String project, final long score) {
this.phrase = phrase;
this.projects.add(project);
this.score = score;
}
public String getPhrase() {
return phrase;
}
public Set<String> getProjects() {
return Collections.unmodifiableSet(projects);
}
public long getScore() {
return score;
}
/**
* Combines score and projects with the other instance with the same {@code phrase}.
* @param other instance to combine with
*/
void combine(final LookupResultItem other) {<FILL_FUNCTION_BODY>}
private boolean canBeCombinedWith(final LookupResultItem other) {
return phrase.equals(other.phrase);
}
@Override
public int compareTo(final LookupResultItem other) {
return Long.compare(score, other.score);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LookupResultItem that = (LookupResultItem) o;
return score == that.score &&
Objects.equals(phrase, that.phrase) &&
Objects.equals(projects, that.projects);
}
@Override
public int hashCode() {
return Objects.hash(phrase, projects, score);
}
@Override
public String toString() {
return "LookupResultItem{phrase='" + phrase + "', projects=" + projects + ", score=" + score + '}';
}
}
|
if (other == null || !canBeCombinedWith(other)) {
throw new IllegalArgumentException("Cannot combine with " + other);
}
projects.addAll(other.projects);
score += other.score;
| 491
| 58
| 549
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/SuggestResultCollector.java
|
SuggesterLeafCollector
|
setScorer
|
class SuggesterLeafCollector implements LeafCollector {
private final LeafReaderContext context;
private final int docBase;
private SuggesterLeafCollector(LeafReaderContext context) {
this.context = context;
docBase = this.context.docBase;
}
/**
* Called before successive calls to {@link #collect(int)}. Implementations that need the score of
* the current document (passed-in to {@link #collect(int)}), should save the passed-in Scorer and
* call scorer.score() when needed.
*
* @param scorer scorer
*/
@Override
public void setScorer(Scorable scorer) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Called once for every document matching a query, with the unbased document number.
*
* <p>Note: The collection of the current segment can be terminated by throwing a {@link
* CollectionTerminatedException}. In this case, the last docs of the current {@link
* LeafReaderContext} will be skipped and {@link IndexSearcher} will
* swallow the exception and continue collection with the next leaf.
*
* <p>Note: This is called in an inner search loop. For good search performance, implementations
* of this method should not call {@link StoredFields#document} on every hit. Doing so can slow
* searches by an order of magnitude or more.
*
* @param doc documentId
*/
@Override
public void collect(int doc) throws IOException {
if (leafReaderContext == context) {
documentIds.set(docBase + doc);
}
}
}
|
if (leafReaderContext == context) {
if (scorer instanceof PhraseScorer) {
data.scorer = (PhraseScorer) scorer;
} else {
try {
// it is mentioned in the documentation that #getChildren should not be called
// in #setScorer but no better way was found
for (var childScorer : scorer.getChildren()) {
if (childScorer.child instanceof PhraseScorer) {
data.scorer = (PhraseScorer) childScorer.child;
}
}
} catch (Exception e) {
// ignore
}
}
}
| 427
| 162
| 589
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/SuggesterUtils.java
|
SuggesterUtils
|
intoTerms
|
class SuggesterUtils {
public static final int NORMALIZED_DOCUMENT_FREQUENCY_MULTIPLIER = 1000;
private static final Logger logger = Logger.getLogger(SuggesterUtils.class.getName());
private static final long DEFAULT_TERM_WEIGHT = 0;
private SuggesterUtils() {
}
/**
* Combines the suggestions from multiple suggesters with the same {@code phrase} and returns the
* {@code resultSize} of the ones with the highest scores.
* @param results suggestions
* @param resultSize the size of the list to return
* @return combined results from multiple suggesters
*/
static List<LookupResultItem> combineResults(final List<LookupResultItem> results, final int resultSize) {
LookupPriorityQueue queue = new LookupPriorityQueue(resultSize);
Map<String, LookupResultItem> map = new HashMap<>();
for (LookupResultItem item : results) {
LookupResultItem storedItem = map.get(item.getPhrase());
if (storedItem == null) {
map.put(item.getPhrase(), item);
} else {
storedItem.combine(item);
}
}
// `queue` holds only `resultSize` items with the highest score
map.values().forEach(queue::insertWithOverflow);
return queue.getResult();
}
/**
* Computes score of the of the specified term.
* @param indexReader reader where the term occurs
* @param field term field
* @param bytesRef term text
* @return score for the term
*/
static long computeScore(final IndexReader indexReader, final String field, final BytesRef bytesRef) {
try {
Term term = new Term(field, bytesRef);
double normalizedDocumentFrequency = computeNormalizedDocumentFrequency(indexReader, term);
return (long) (normalizedDocumentFrequency * NORMALIZED_DOCUMENT_FREQUENCY_MULTIPLIER);
} catch (IOException e) {
logger.log(Level.WARNING, e, () -> "Could not compute weight for " + bytesRef);
}
return DEFAULT_TERM_WEIGHT;
}
private static double computeNormalizedDocumentFrequency(final IndexReader indexReader, final Term term)
throws IOException {
int documentFrequency = indexReader.docFreq(term);
return ((double) documentFrequency) / indexReader.numDocs();
}
/**
* Decomposes the provided {@code query} into terms.
* @param query query to decompose
* @return terms that were in the {@code query}
*/
public static List<Term> intoTerms(final Query query) {<FILL_FUNCTION_BODY>}
/**
* Decomposes the provided {@code query} into terms with the exception of {@link PhraseQuery}. Is useful when
* determining which terms should not be suggested. {@link PhraseQuery} is exempted because not suggesting some
* term which were contained in it is invalid.
* @param query query to decompose
* @return terms that were in the {@code query}
*/
public static List<Term> intoTermsExceptPhraseQuery(final Query query) {
if (query == null) {
return Collections.emptyList();
}
List<Term> terms = new LinkedList<>();
LinkedList<Query> queue = new LinkedList<>();
queue.add(query);
while (!queue.isEmpty()) {
Query q = queue.poll();
if (q instanceof BooleanQuery) {
for (BooleanClause bc : ((BooleanQuery) q).clauses()) {
queue.add(bc.getQuery());
}
} else if (q instanceof TermQuery) {
terms.add(((TermQuery) q).getTerm());
}
}
return terms;
}
/**
* Determines if the query is deemed complex by the suggester standards. Complex means that it needs to search in
* the index rather than WFST data structure.
* @param query dependent query
* @param suggesterQuery suggester query
* @return {@code true} if complex, {@code false} otherwise
*/
public static boolean isComplexQuery(final Query query, final SuggesterQuery suggesterQuery) {
return query != null || !(suggesterQuery instanceof SuggesterPrefixQuery);
}
}
|
if (query == null) {
return Collections.emptyList();
}
List<Term> terms = new LinkedList<>();
LinkedList<Query> queue = new LinkedList<>();
queue.add(query);
while (!queue.isEmpty()) {
Query q = queue.poll();
if (q instanceof BooleanQuery) {
for (BooleanClause bc : ((BooleanQuery) q).clauses()) {
queue.add(bc.getQuery());
}
} else if (q instanceof TermQuery) {
terms.add(((TermQuery) q).getTerm());
} else if (q instanceof PhraseQuery) {
terms.addAll(Arrays.asList(((PhraseQuery) q).getTerms()));
}
}
return terms;
| 1,135
| 202
| 1,337
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/popular/impl/chronicle/BytesRefDataAccess.java
|
BytesRefDataAccess
|
getUsing
|
class BytesRefDataAccess extends AbstractData<BytesRef> implements DataAccess<BytesRef> {
/** Cache field. */
private transient BytesStore<?, ?> bs;
/** State field. */
private transient byte[] array;
public BytesRefDataAccess() {
initTransients();
}
private void initTransients() {
bs = null;
}
@Override
public RandomDataInput bytes() {
return bs;
}
@Override
public long offset() {
return bs.start();
}
@Override
public long size() {
return bs.capacity();
}
@Override
public BytesRef get() {
return new BytesRef(array);
}
@Override
public BytesRef getUsing(@Nullable BytesRef using) {<FILL_FUNCTION_BODY>}
@Override
public Data<BytesRef> getData(@NotNull BytesRef instance) {
if (instance.bytes.length == instance.length) {
array = instance.bytes;
} else {
array = new byte[instance.length];
System.arraycopy(instance.bytes, instance.offset, array, 0, instance.length);
}
bs = BytesStore.wrap(array);
return this;
}
@Override
public void uninit() {
array = null;
bs = null;
}
@Override
public DataAccess<BytesRef> copy() {
return new BytesRefDataAccess();
}
@Override
public void writeMarshallable(@NotNull WireOut wireOut) {
// no fields to write
}
@Override
public void readMarshallable(@NotNull WireIn wireIn) {
// no fields to read
initTransients();
}
}
|
using = Optional.ofNullable(using)
.orElseGet( () ->
new BytesRef(new byte[array.length])
);
if (using.bytes.length < array.length) {
using.bytes = new byte[array.length];
}
System.arraycopy(array, 0, using.bytes, 0, array.length);
using.offset = 0;
using.length = array.length;
return using;
| 472
| 119
| 591
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/popular/impl/chronicle/BytesRefSizedReader.java
|
BytesRefSizedReader
|
read
|
class BytesRefSizedReader implements SizedReader<BytesRef>, Marshallable, ReadResolvable<BytesRefSizedReader> {
public static final BytesRefSizedReader INSTANCE = new BytesRefSizedReader();
private BytesRefSizedReader() {
}
@NotNull
@Override
@SuppressWarnings({"rawtypes"})
public BytesRef read(Bytes in, long size, @Nullable BytesRef using) {<FILL_FUNCTION_BODY>}
@Override
public void writeMarshallable(@NotNull WireOut wireOut) {
// no fields to write
}
@Override
public void readMarshallable(@NotNull WireIn wireIn) {
// no fields to read
}
@NotNull
@Override
public BytesRefSizedReader readResolve() {
return INSTANCE;
}
}
|
if (size < 0L || size > Integer.MAX_VALUE) {
throw new IORuntimeException("byte[] size should be non-negative int, " +
size + " given. Memory corruption?");
}
int arrayLength = (int) size;
using = Optional.ofNullable(using)
.orElseGet( () ->
new BytesRef(new byte[arrayLength])
);
if (using.bytes.length < arrayLength) {
using.bytes = new byte[arrayLength];
}
in.read(using.bytes, 0, arrayLength);
using.offset = 0;
using.length = arrayLength;
return using;
| 227
| 172
| 399
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/popular/impl/chronicle/ChronicleMapAdapter.java
|
ChronicleMapAdapter
|
getPopularityData
|
class ChronicleMapAdapter implements PopularityMap {
private ChronicleMap<BytesRef, Integer> map;
private final File chronicleMapFile;
public ChronicleMapAdapter(final String name, final double averageKeySize, final int entries, final File file)
throws IOException {
map = ChronicleMap.of(BytesRef.class, Integer.class)
.name(name)
.averageKeySize(averageKeySize)
.keyReaderAndDataAccess(BytesRefSizedReader.INSTANCE, new BytesRefDataAccess())
.entries(entries)
.createOrRecoverPersistedTo(file);
this.chronicleMapFile = file;
}
/** {@inheritDoc} */
@Override
public int get(final BytesRef key) {
return map.getOrDefault(key, 0);
}
/** {@inheritDoc} */
@Override
public void increment(final BytesRef key, final int value) {
if (value < 0) {
throw new IllegalArgumentException("Cannot increment by negative value " + value);
}
map.merge(key, value, Integer::sum);
}
/** {@inheritDoc} */
@Override
public List<Entry<BytesRef, Integer>> getPopularityData(final int page, final int pageSize) {<FILL_FUNCTION_BODY>}
/**
* Removes the entries with key that meets the predicate.
* @param predicate predicate which tests which entries should be removed
*/
public void removeIf(final Predicate<BytesRef> predicate) {
map.entrySet().removeIf(e -> predicate.test(e.getKey()));
}
/**
* Resizes the underlying {@link ChronicleMap}.
* @param newMapSize new entries count
* @param newMapAvgKey new average key size
* @throws IOException if some error occurred
*/
@SuppressWarnings("java:S2095")
public void resize(final int newMapSize, final double newMapAvgKey) throws IOException {
if (newMapSize < 0) {
throw new IllegalArgumentException("Cannot resize chronicle map to negative size");
}
if (newMapAvgKey < 0) {
throw new IllegalArgumentException("Cannot resize chronicle map to map with negative key size");
}
Path tempFile = Files.createTempFile("opengrok", "chronicle");
try {
map.getAll(tempFile.toFile());
String field = map.name();
map.close();
Files.delete(chronicleMapFile.toPath());
ChronicleMap<BytesRef, Integer> m = ChronicleMap.of(BytesRef.class, Integer.class)
.name(field)
.averageKeySize(newMapAvgKey)
.entries(newMapSize)
.keyReaderAndDataAccess(BytesRefSizedReader.INSTANCE, new BytesRefDataAccess())
.createOrRecoverPersistedTo(chronicleMapFile);
m.putAll(tempFile.toFile());
map = m;
} finally {
Files.delete(tempFile);
}
}
/**
* Closes the opened {@link ChronicleMap}.
*/
@Override
public void close() {
map.close();
}
}
|
if (page < 0) {
throw new IllegalArgumentException("Cannot retrieve popularity data for negative page: " + page);
}
if (pageSize < 0) {
throw new IllegalArgumentException("Cannot retrieve negative number of results: " + pageSize);
}
List<Entry<BytesRef, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Entry.<BytesRef, Integer>comparingByValue().reversed());
int startIndex = page * pageSize;
if (startIndex >= list.size()) {
return Collections.emptyList();
}
int endIndex = startIndex + pageSize;
if (endIndex > list.size()) {
endIndex = list.size();
}
return list.subList(startIndex, endIndex);
| 836
| 199
| 1,035
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/popular/impl/chronicle/ChronicleMapConfiguration.java
|
ChronicleMapConfiguration
|
load
|
class ChronicleMapConfiguration implements Serializable {
private static final long serialVersionUID = -18408710536443827L;
private static final Logger logger = Logger.getLogger(ChronicleMapConfiguration.class.getName());
private static final String FILE_NAME_SUFFIX = "_map.cfg";
private int entries;
private double averageKeySize;
public ChronicleMapConfiguration(final int entries, final double averageKeySize) {
this.entries = entries;
this.averageKeySize = averageKeySize;
}
public int getEntries() {
return entries;
}
public double getAverageKeySize() {
return averageKeySize;
}
public void setEntries(int entries) {
this.entries = entries;
}
public void setAverageKeySize(double averageKeySize) {
this.averageKeySize = averageKeySize;
}
/**
* Stores this into a file.
* @param dir directory where to store the file
* @param field field this configuration is for
*/
public void save(final Path dir, final String field) {
try (FileOutputStream fos = new FileOutputStream(getFile(dir, field));
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(this);
} catch (IOException e) {
logger.log(Level.SEVERE, "Could not save chronicle map configuration", e);
}
}
/**
* Loads configuration from file.
* @param dir directory from which to load the configuration
* @param field field this configuration is for
* @return loaded configuration or {@code null} if this configuration could not be loaded
*/
public static ChronicleMapConfiguration load(final Path dir, final String field) {<FILL_FUNCTION_BODY>}
private static File getFile(final Path dir, final String field) {
return dir.resolve(field + FILE_NAME_SUFFIX).toFile();
}
}
|
File f = getFile(dir, field);
if (!f.exists()) {
return null;
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
ois.setObjectInputFilter(filterInfo ->
filterInfo.serialClass() == null || filterInfo.serialClass() == ChronicleMapConfiguration.class ?
Status.ALLOWED : Status.REJECTED);
return (ChronicleMapConfiguration) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
logger.log(Level.SEVERE, "Could not load chronicle map configuration", e);
}
return null;
| 517
| 165
| 682
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/SuggesterFuzzyQuery.java
|
SuggesterFuzzyQuery
|
getTermsEnumForSuggestions
|
class SuggesterFuzzyQuery extends FuzzyQuery implements SuggesterQuery {
public SuggesterFuzzyQuery(final Term term, final int maxEdits, final int prefixLength) {
super(term, maxEdits, prefixLength);
}
/** {@inheritDoc} */
@Override
public TermsEnum getTermsEnumForSuggestions(final Terms terms) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public int length() {
return getTerm().text().length();
}
}
|
if (terms == null) {
return TermsEnum.EMPTY;
}
return getTermsEnum(terms, new AttributeSource());
| 149
| 40
| 189
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/SuggesterPhraseQuery.java
|
SuggesterPhraseQuery
|
toString
|
class SuggesterPhraseQuery extends Query {
private enum SuggestPosition {
START, MIDDLE, END;
private static SuggestPosition from(final int pos, final int size) {
if (pos == 0) {
return SuggestPosition.START;
} else if (pos == size - 1) {
return SuggestPosition.END;
} else {
return SuggestPosition.MIDDLE;
}
}
}
private final CustomPhraseQuery phraseQuery;
private final SuggesterQuery suggesterQuery;
/**
* @param field term field
* @param identifier unique String which identifies the token for which the suggestions should be made
* @param tokens all the tokens of the phrase query
* @param slop word Levenshtein's distance
*/
public SuggesterPhraseQuery(
final String field,
final String identifier,
final List<String> tokens,
final int slop
) {
String prefix = null;
int pos = -1;
int i = 0;
List<Integer> positions = new ArrayList<>();
List<Term> terms = new ArrayList<>();
for (String token : tokens) {
if (token.contains(identifier)) {
prefix = token.replace(identifier, "");
pos = i;
} else {
positions.add(i);
terms.add(new Term(field, token));
}
i++;
}
if (pos < 0 || pos > tokens.size()) {
throw new IllegalStateException();
}
SuggestPosition p = SuggestPosition.from(pos, tokens.size());
if (p == SuggestPosition.START) {
phraseQuery = new CustomPhraseQuery(slop, field, tokens.stream().filter(t -> !t.contains(identifier)).toArray(String[]::new));
phraseQuery.setOffset(-1);
} else if (p == SuggestPosition.MIDDLE) {
phraseQuery = new CustomPhraseQuery(slop, terms.toArray(new Term[0]), positions.stream().mapToInt(in -> in).toArray());
phraseQuery.setOffset(pos);
} else {
phraseQuery = new CustomPhraseQuery(slop, field, tokens.stream().filter(t -> !t.contains(identifier)).toArray(String[]::new));
phraseQuery.setOffset(tokens.size() - 1);
}
suggesterQuery = new SuggesterPrefixQuery(new Term(field, prefix));
}
public SuggesterQuery getSuggesterQuery() {
return suggesterQuery;
}
public CustomPhraseQuery getPhraseQuery() {
return phraseQuery;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SuggesterPhraseQuery that = (SuggesterPhraseQuery) o;
return Objects.equals(phraseQuery, that.phraseQuery) &&
Objects.equals(suggesterQuery, that.suggesterQuery);
}
@Override
public int hashCode() {
return Objects.hash(phraseQuery, suggesterQuery);
}
@Override
public String toString(final String field) {<FILL_FUNCTION_BODY>}
@Override
public Query rewrite(IndexSearcher indexSearcher) {
return phraseQuery.rewrite(indexSearcher);
}
@Override
public void visit(QueryVisitor visitor) {
visitor.visitLeaf(this);
}
}
|
return "SuggesterPhraseQuery{" +
"phraseQuery=" + phraseQuery +
", suggesterQuery=" + suggesterQuery +
'}';
| 948
| 45
| 993
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/SuggesterPrefixQuery.java
|
SuggesterPrefixQuery
|
getTermsEnumForSuggestions
|
class SuggesterPrefixQuery extends PrefixQuery implements SuggesterQuery {
/**
* @param prefix term prefix
*/
public SuggesterPrefixQuery(final Term prefix) {
super(prefix);
}
/** {@inheritDoc} */
@Override
public TermsEnum getTermsEnumForSuggestions(final Terms terms) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public int length() {
return getPrefix().text().length();
}
}
|
if (terms == null) {
return TermsEnum.EMPTY;
}
return super.getTermsEnum(terms, new AttributeSource());
| 140
| 42
| 182
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/SuggesterRangeQuery.java
|
SuggesterRangeQuery
|
getTermsEnumForSuggestions
|
class SuggesterRangeQuery extends TermRangeQuery implements SuggesterQuery {
private static final Logger logger = Logger.getLogger(SuggesterRangeQuery.class.getName());
private final SuggestPosition suggestPosition;
/**
* @param field term field
* @param lowerTerm term on the left side of the range query
* @param upperTerm term on the right side of the range query
* @param includeLower if the lower term should be included in the result
* @param includeUpper if the upper term should be included in the result
* @param suggestPosition if the suggestions are for the lower or upper term
*/
public SuggesterRangeQuery(
final String field,
final BytesRef lowerTerm,
final BytesRef upperTerm,
final boolean includeLower,
final boolean includeUpper,
final SuggestPosition suggestPosition
) {
super(field, lowerTerm, upperTerm, includeLower, includeUpper);
this.suggestPosition = suggestPosition;
if (suggestPosition == null) {
throw new IllegalArgumentException("Suggest position cannot be null");
}
}
/** {@inheritDoc} */
@Override
public TermsEnum getTermsEnumForSuggestions(final Terms terms) {<FILL_FUNCTION_BODY>}
private BytesRef getPrefix() {
if (suggestPosition == SuggestPosition.LOWER) {
return getLowerTerm();
} else {
return getUpperTerm();
}
}
/** {@inheritDoc} */
@Override
public int length() {
BytesRef prefix = getPrefix();
if (prefix == null) {
return 0;
}
return prefix.utf8ToString().length();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
SuggesterRangeQuery that = (SuggesterRangeQuery) o;
return suggestPosition == that.suggestPosition;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), suggestPosition);
}
/**
* SuggestPosition type values.
*/
public enum SuggestPosition {
LOWER, UPPER
}
}
|
if (terms == null) {
return TermsEnum.EMPTY;
}
BytesRef prefix = getPrefix();
if (prefix != null) {
Automaton prefixAutomaton = PrefixQuery.toAutomaton(prefix);
Automaton finalAutomaton;
if (suggestPosition == SuggestPosition.LOWER) {
Automaton binaryInt = Automata.makeBinaryInterval(
getLowerTerm(), includesLower(), getUpperTerm(), includesUpper());
finalAutomaton = Operations.intersection(binaryInt, prefixAutomaton);
} else {
Automaton binaryInt = Automata.makeBinaryInterval(null, true, getLowerTerm(), !includesLower());
finalAutomaton = Operations.minus(prefixAutomaton, binaryInt, Integer.MIN_VALUE);
}
CompiledAutomaton compiledAutomaton = new CompiledAutomaton(finalAutomaton);
try {
return compiledAutomaton.getTermsEnum(terms);
} catch (IOException e) {
logger.log(Level.WARNING, "Could not compile automaton for range suggestions", e);
}
}
return TermsEnum.EMPTY;
| 618
| 298
| 916
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/SuggesterRegexpQuery.java
|
SuggesterRegexpQuery
|
getTermsEnumForSuggestions
|
class SuggesterRegexpQuery extends RegexpQuery implements SuggesterQuery {
/**
* @param term term with regexp symbols
*/
public SuggesterRegexpQuery(final Term term) {
super(term);
}
/** {@inheritDoc} */
@Override
public TermsEnum getTermsEnumForSuggestions(final Terms terms) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public int length() {
return getRegexp().text().length();
}
}
|
if (terms == null) {
return TermsEnum.EMPTY;
}
return super.getTermsEnum(terms);
| 150
| 37
| 187
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/SuggesterWildcardQuery.java
|
SuggesterWildcardQuery
|
getTermsEnumForSuggestions
|
class SuggesterWildcardQuery extends WildcardQuery implements SuggesterQuery {
/**
* @param term term with wildcard symbols
*/
public SuggesterWildcardQuery(final Term term) {
super(term);
}
/** {@inheritDoc} */
@Override
public TermsEnum getTermsEnumForSuggestions(final Terms terms) throws IOException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public int length() {
return getTerm().text().length();
}
}
|
if (terms == null) {
return TermsEnum.EMPTY;
}
return super.getTermsEnum(terms, new AttributeSource());
| 147
| 42
| 189
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/customized/CustomExactPhraseScorer.java
|
PostingsAndPosition
|
toString
|
class PostingsAndPosition {
private final PostingsEnum postings;
private final int offset;
private int freq;
private int upTo;
private int pos;
PostingsAndPosition(PostingsEnum postings, int offset) {
this.postings = postings;
this.offset = offset;
}
}
// custom begins – only necessary attributes
private final Map<Integer, IntsHolder> documentToPositionsMap = new HashMap<>();
private final int offset;
private final DocIdSetIterator conjunction;
private final PostingsAndPosition[] postings;
// custom ends
// custom – constructor parameters
/**
* Creates custom exact phrase scorer which remembers the positions of the found matches.
* @param weight query weight
* @param postings postings of the terms
* @param offset the offset that is added to the found match position
*/
CustomExactPhraseScorer(
final Weight weight,
final CustomPhraseQuery.PostingsAndFreq[] postings,
final int offset
) {
super(weight);
this.offset = offset; // custom
// custom begins – support for single term
conjunction = generateDocIdSetIterator(Arrays.stream(postings)
.map(p -> p.postings).collect(Collectors.toList()));
// custom ends
assert TwoPhaseIterator.unwrap(conjunction) == null;
this.postings = Arrays.stream(postings)
.map(p -> new PostingsAndPosition(p.postings, p.position))
.toArray(PostingsAndPosition[]::new);
}
private DocIdSetIterator generateDocIdSetIterator(@NotNull List<DocIdSetIterator> listOfDocIdSetIterator) {
return Optional.of(listOfDocIdSetIterator)
.filter(p -> p.size() > 1)
.map(ConjunctionUtils::intersectIterators)
.orElse(listOfDocIdSetIterator.get(0));
}
@Override
public TwoPhaseIterator twoPhaseIterator() {
return new TwoPhaseIterator(conjunction) {
@Override
public boolean matches() throws IOException {
// custom – interrupt handler
if (Thread.currentThread().isInterrupted()) {
throw new IOException("Interrupted while scoring documents");
}
return phraseFreq() > 0; // custom – only necessary part left
}
@Override
public float matchCost() {
return 0; // custom – default value
}
};
}
@Override
public float getMaxScore(int i) throws IOException {
return 0;
}
@Override
public DocIdSetIterator iterator() {
return TwoPhaseIterator.asDocIdSetIterator(twoPhaseIterator());
}
@Override
public String toString() {<FILL_FUNCTION_BODY>
|
return "CustomExactPhraseScorer(" + weight + ")"; // custom – renamed class
| 736
| 27
| 763
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/customized/CustomPhraseQuery.java
|
CustomPhraseWeight
|
scorer
|
class CustomPhraseWeight extends Weight {
private final CustomPhraseQuery query;
private final TermStates[] states;
CustomPhraseWeight(IndexSearcher searcher, CustomPhraseQuery query) throws IOException {
super(query);
this.query = query;
this.states = new TermStates[query.terms.length];
for(int i = 0; i < query.terms.length; ++i) {
Term term = query.terms[i];
this.states[i] = TermStates.build(searcher, term, false);
}
}
@Override
public Explanation explain(LeafReaderContext leafReaderContext, int i) {
throw new UnsupportedOperationException();
}
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public boolean isCacheable(LeafReaderContext leafReaderContext) {
return false;
}
}
|
LeafReader reader = context.reader();
CustomPhraseQuery.PostingsAndFreq[] postingsFreqs = new CustomPhraseQuery.PostingsAndFreq[query.terms.length];
String field = query.terms[0].field();
Terms fieldTerms = reader.terms(field);
if (fieldTerms == null) {
return null;
} else if (!fieldTerms.hasPositions()) {
throw new IllegalStateException("field \"" +field +
"\" was indexed without position data; cannot run CustomPhraseQuery (phrase=" + this.getQuery() + ")");
} else {
TermsEnum te = fieldTerms.iterator();
for(int i = 0; i < query.terms.length; ++i) {
Term t = query.terms[i];
TermState state = this.states[i].get(context);
if (state == null) {
return null;
}
te.seekExact(t.bytes(), state);
PostingsEnum postingsEnum = te.postings(null, 24);
postingsFreqs[i] = new CustomPhraseQuery.PostingsAndFreq(postingsEnum, query.positions[i], t);
}
if (query.slop == 0) {
ArrayUtil.timSort(postingsFreqs);
return new CustomExactPhraseScorer(this, postingsFreqs, query.offset);
} else {
return new CustomSloppyPhraseScorer(this, postingsFreqs, query.slop, query.offset);
}
}
| 252
| 404
| 656
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.