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/analysis/verilog/VerilogLexer.java
|
VerilogLexer
|
chkLOC
|
class VerilogLexer extends JFlexSymbolMatcher
implements JFlexJointLexer, Resettable {
/**
* Calls {@link #phLOC()} if the yystate is not COMMENT or SCOMMENT.
*/
public void chkLOC() {<FILL_FUNCTION_BODY>}
/**
* Subclasses must override to get the constant value created by JFlex to
* represent COMMENT.
*/
@SuppressWarnings("java:S100")
abstract int COMMENT();
/**
* Subclasses must override to get the constant value created by JFlex to
* represent SCOMMENT.
*/
@SuppressWarnings("java:S100")
abstract int SCOMMENT();
}
|
if (yystate() != COMMENT() && yystate() != SCOMMENT()) {
phLOC();
}
| 199
| 36
| 235
|
<methods>public non-sealed void <init>() ,public void clearNonSymbolMatchedListener() ,public void clearSymbolMatchedListener() ,public void setNonSymbolMatchedListener(org.opengrok.indexer.analysis.NonSymbolMatchedListener) ,public void setSymbolMatchedListener(org.opengrok.indexer.analysis.SymbolMatchedListener) <variables>private java.lang.String disjointSpanClassName,private org.opengrok.indexer.analysis.NonSymbolMatchedListener nonSymbolListener,private org.opengrok.indexer.analysis.SymbolMatchedListener symbolListener
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/CanonicalRootValidator.java
|
CanonicalRootValidator
|
validate
|
class CanonicalRootValidator {
/**
* Validates the specified setting, returning an error message if validation
* fails.
* @return a defined instance if not valid or {@code null} otherwise
*/
public static String validate(String setting, String elementDescription) {<FILL_FUNCTION_BODY>}
/** Private to enforce static. */
private CanonicalRootValidator() {
}
}
|
// Test that the value ends with the system separator.
if (!setting.endsWith(File.separator)) {
return elementDescription + " must end with a separator";
}
// Test that the value is not like a Windows root (e.g. C:\ or Z:/).
if (setting.matches("\\w:(?:[/\\\\]*)")) {
return elementDescription + " cannot be a root directory";
}
// Test that some character other than separators is in the value.
if (!setting.matches(".*[^/\\\\].*")) {
return elementDescription + " cannot be the root directory";
}
/*
* There is no need to validate that the caller has not specified e.g.
* "/./" (i.e. an alias to the root "/") because --canonicalRoot values
* are matched via string comparison against true canonical values got
* via File.getCanonicalPath(). An alias like "/./" is therefore a
* never-matching value and hence inactive.
*/
return null;
| 103
| 263
| 366
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/ConfigMerge.java
|
ConfigMerge
|
main
|
class ConfigMerge {
private static final String NAME = "ConfigMerge";
private ConfigMerge() {
}
/**
* Merge base and new configuration.
* @param cfgBase base configuration
* @param cfgNew new configuration, will receive properties from the base configuration
* @throws Exception exception
*/
public static void merge(Configuration cfgBase, Configuration cfgNew) throws Exception {
Configuration cfgDefault = new Configuration();
// Basic strategy: take all non-static/transient fields that have a setter
// from cfgBase that are not of default value and set them to cfgNew.
var fields = Arrays.stream(cfgBase.getClass().getDeclaredFields())
.filter(ConfigMerge::isCopyable)
.collect(Collectors.toList());
for (Field field : fields) {
String fieldName = field.getName();
PropertyDescriptor desc;
try {
desc = new PropertyDescriptor(fieldName, Configuration.class);
} catch (IntrospectionException ex) {
throw new Exception("cannot get property descriptor for '" + fieldName + "'");
}
Method setter = desc.getWriteMethod();
if (setter == null) {
throw new Exception("no setter for '" + fieldName + "'");
}
Method getter = desc.getReadMethod();
if (getter == null) {
throw new Exception("no getter for '" + fieldName + "'");
}
try {
Object obj = getter.invoke(cfgBase);
if (Objects.equals(obj, getter.invoke(cfgDefault))) {
continue;
}
} catch (Exception ex) {
throw new Exception("failed to invoke getter for " + fieldName + ": " + ex);
}
try {
setter.invoke(cfgNew, getter.invoke(cfgBase));
} catch (Exception ex) {
throw new Exception("failed to invoke setter for '" + fieldName + "'");
}
}
}
private static boolean isCopyable(Field field) {
int modifiers = field.getModifiers();
return !Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) &&
!Modifier.isFinal(modifiers);
}
public static void main(String[] argv) {<FILL_FUNCTION_BODY>}
private static void aUsage(PrintStream out) {
out.println("Usage:");
out.println(NAME + " [-h] <config_file_base> <config_file_new> <output_file>");
out.println();
out.println("OPTIONS:");
out.println("Help");
out.println("-? print this help message");
out.println("-h print this help message");
out.println();
}
private static void bUsage(PrintStream out) {
out.println("Maybe try to run " + NAME + " -h");
}
}
|
Getopt getopt = new Getopt(argv, "h?");
try {
getopt.parse();
} catch (ParseException ex) {
System.err.println(NAME + ": " + ex.getMessage());
bUsage(System.err);
System.exit(1);
}
int cmd;
getopt.reset();
while ((cmd = getopt.getOpt()) != -1) {
switch (cmd) {
case '?':
case 'h':
aUsage(System.out);
System.exit(0);
break;
default:
System.err.println("Internal Error - Not implemented option: " + (char) cmd);
bUsage(System.err);
System.exit(1);
break;
}
}
int optind = getopt.getOptind();
if (optind < 0 || argv.length - optind != 3) {
aUsage(System.err);
System.exit(1);
}
Configuration cfgBase = null;
try {
cfgBase = Configuration.read(new File(argv[optind]));
} catch (IOException ex) {
System.err.println("cannot read base file " + argv[optind] + ":" + ex);
System.exit(1);
}
Configuration cfgNew = null;
try {
cfgNew = Configuration.read(new File(argv[optind + 1]));
} catch (IOException ex) {
System.err.println("cannot read file " + argv[optind + 1] + ":" + ex);
System.exit(1);
}
try {
merge(cfgBase, cfgNew);
} catch (Exception ex) {
System.err.print(ex);
System.exit(1);
}
// Write the resulting XML representation to the output file.
try (OutputStream os = new FileOutputStream(argv[optind + 2])) {
cfgNew.encodeObject(os);
} catch (IOException ex) {
System.err.print(ex);
System.exit(1);
}
| 750
| 545
| 1,295
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/ConfigurationClassLoader.java
|
ConfigurationClassLoader
|
loadClass
|
class ConfigurationClassLoader extends ClassLoader {
private static final Set<String> allowedClasses = Set.of(
ArrayList.class,
AuthControlFlag.class,
AuthorizationEntity.class,
AuthorizationPlugin.class,
AuthorizationStack.class,
Collections.class,
Configuration.class,
Enum.class,
Filter.class,
Group.class,
HashMap.class,
HashSet.class,
IAuthorizationPlugin.class,
IgnoredNames.class,
LuceneLockName.class,
Project.class,
RemoteSCM.class,
RepositoryInfo.class,
Set.class,
StatsdConfig.class,
StatsdFlavor.class,
String.class,
SuggesterConfig.class,
TreeMap.class,
TreeSet.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);
| 277
| 54
| 331
|
<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/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/Filter.java
|
PatternList
|
add
|
class PatternList extends ArrayList<String> {
private static final long serialVersionUID = -6883390970972775838L;
private final Filter owner;
public PatternList(Filter owner) {
this.owner = owner;
}
@Override
public boolean add(String pattern) {<FILL_FUNCTION_BODY>}
}
|
boolean ret = super.add(pattern);
if (ret) {
owner.addPattern(pattern);
}
return ret;
| 105
| 38
| 143
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/Group.java
|
Group
|
getAllProjects
|
class Group implements Comparable<Group>, Nameable {
static {
ClassUtil.remarkTransientFields(Group.class);
}
private String name;
/**
* Group regexp pattern.
*
* No project matches the empty pattern of "" however this group can still
* be used as a superior group for other groups (without duplicating the
* projects).
*/
private String pattern = "";
/**
* Compiled group pattern.
*
* We set up the empty compiled pattern by default to "()" to reduce code
* complexity when performing a match for a group without a pattern.
*
* This pattern is updated whenever the string pattern {@link #pattern} is
* updated.
*
* @see #setPattern(String)
*/
private Pattern compiledPattern = Pattern.compile("()");
private Group parent;
private Set<Group> subgroups = new TreeSet<>();
private transient int flag;
private transient Set<Group> descendants = new TreeSet<>();
private transient Set<Project> projects = new TreeSet<>();
private transient Set<Project> repositories = new TreeSet<>();
private transient Set<Group> parents;
/**
* No-arg constructor is needed for deserialization.
*/
public Group() {
}
public Group(String name) {
this(name, "");
}
public Group(String name, String pattern) {
this.name = name;
this.setPattern(pattern);
}
public Set<Project> getProjects() {
return projects;
}
public void addProject(Project p) {
this.projects.add(p);
}
public void addRepository(Project p) {
this.repositories.add(p);
}
public Set<Group> getDescendants() {
return descendants;
}
public void setDescendants(Set<Group> descendants) {
this.descendants = descendants;
}
public void addDescendant(Group g) {
this.descendants.add(g);
}
public void removeDescendant(Group g) {
this.descendants.remove(g);
}
public Set<Project> getRepositories() {
return repositories;
}
public void setSubgroups(Set<Group> subgroups) {
this.subgroups = subgroups;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
public void setRepositories(Set<Project> repositories) {
this.repositories = repositories;
}
public Set<Group> getSubgroups() {
return subgroups;
}
public void addGroup(Group g) {
g.setParent(this);
subgroups.add(g);
descendants.add(g);
}
public Set<Group> getParents() {
if (parents == null) {
parents = new TreeSet<>();
Group tmp = parent;
while (tmp != null) {
parents.add(tmp);
tmp = tmp.getParent();
}
}
return parents;
}
/**
* Collect all related groups to this group. A related group is
* <ul>
* <li>any ancestor</li>
* <li>any subgroup</li>
* </ul>
*
* @return all collected related groups to this group
*/
public Set<Group> getRelatedGroups() {
Set<Group> groupsTmp = new TreeSet<>();
groupsTmp.addAll(getDescendants());
groupsTmp.addAll(getParents());
return groupsTmp;
}
/**
* Collect all group's projects and repositories included in this group and
* in any subgroup.
*
* @return all collected projects and repositories
*/
public Set<Project> getAllProjects() {<FILL_FUNCTION_BODY>}
public Group getParent() {
return parent;
}
public void setParent(Group parent) {
this.parent = parent;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
public String getPattern() {
return pattern;
}
/**
* Set the group pattern.
*
* @param pattern the regexp pattern for this group
* @throws PatternSyntaxException when the pattern is invalid
*/
public final void setPattern(String pattern) throws PatternSyntaxException {
this.compiledPattern = Pattern.compile("(" + pattern + ")");
this.pattern = pattern;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
/**
* Test group for a match.
*
* @param p project
* @return true if project's name matches the group pattern
*/
public boolean match(Project p) {
return match(p.getName());
}
/**
* Test group for a match.
*
* @param name string to match
* @return true if given name matches the group pattern
*/
public boolean match(String name) {
return compiledPattern.matcher(name).matches();
}
@Override
public int compareTo(Group o) {
return getName().compareTo(o.getName());
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Group other = (Group) obj;
return Objects.equals(name, other.name);
}
/**
* Returns group object by its name.
*
* @param name name of a group
* @return group that fits the name
*/
@Nullable
public static Group getByName(String name) {
Group ret = null;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.hasGroups()) {
for (Group grp : env.getGroups().values()) {
if (name.equals(grp.getName())) {
ret = grp;
}
}
}
return ret;
}
/**
* Reduce the group set to only those which match the given project based on
* the project's description.
*
* @param project the project
* @param groups set of groups
* @return set of groups matching the project
*/
public static Set<Group> matching(Project project, Set<Group> groups) {
Set<Group> copy = new TreeSet<>(groups);
copy.removeIf(g -> !g.match(project));
return copy;
}
}
|
Set<Project> projectsTmp = new TreeSet<>();
projectsTmp.addAll(getRepositories());
projectsTmp.addAll(getProjects());
for (Group grp : getDescendants()) {
projectsTmp.addAll(grp.getAllProjects());
}
return projectsTmp;
| 1,825
| 87
| 1,912
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/IgnoredNames.java
|
IgnoredNames
|
ignore
|
class IgnoredNames implements Serializable {
private static final long serialVersionUID = 1L;
private static final String FILE_PREFIX = "f:";
private static final String DIR_PREFIX = "d:";
private IgnoredFiles ignoredFiles;
private IgnoredDirs ignoredDirs;
public IgnoredNames() {
ignoredFiles = new IgnoredFiles();
ignoredDirs = new IgnoredDirs();
}
public List<String> getItems() {
List<String> twoLists = new ArrayList<>();
twoLists.addAll(ignoredFiles.getItems());
twoLists.addAll(ignoredDirs.getItems());
return twoLists;
}
public void setItems(List<String> item) {
clear();
for (String s : item) {
add(s);
}
}
/**
* Adds the specified {@code pattern} if it follows the expected naming
* convention (or else ignored).
* @param pattern defined pattern starting either with {@code "f:"} for
* ignore-file or with {@code "d:"} for an ignore-directory
*/
public void add(String pattern) {
if (pattern.startsWith(FILE_PREFIX)) {
ignoredFiles.add(pattern.substring(FILE_PREFIX.length()));
} else if (pattern.startsWith(DIR_PREFIX)) {
ignoredDirs.add(pattern.substring(DIR_PREFIX.length()));
} else {
// backward compatibility
ignoredFiles.add(pattern);
}
}
/**
* Should the file be ignored or not?
*
* @param file the file to check
* @return true if this file should be ignored, false otherwise
*/
public boolean ignore(File file) {<FILL_FUNCTION_BODY>}
/**
* Should the file name be ignored or not ?
*
* @param name the name of the file to check
* @return true if this pathname should be ignored, false otherwise
*/
public boolean ignore(String name) {
return ignoredFiles.match(name) || ignoredDirs.match(name);
}
public void clear() {
ignoredFiles.clear();
ignoredDirs.clear();
}
public IgnoredDirs getIgnoredDirs() {
return ignoredDirs;
}
public IgnoredFiles getIgnoredFiles() {
return ignoredFiles;
}
public void setIgnoredDirs(IgnoredDirs i) {
ignoredDirs = i;
}
public void setIgnoredFiles(IgnoredFiles i) {
ignoredFiles = i;
}
}
|
if (file.isFile()) {
return ignoredFiles.match(file);
} else {
return ignoredDirs.match(file);
}
| 679
| 42
| 721
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/IncludeFiles.java
|
IncludeFiles
|
getFooterIncludeFileContent
|
class IncludeFiles {
/**
* Reload the content of all include files.
*/
public void reloadIncludeFiles() {
getBodyIncludeFileContent(true);
getHeaderIncludeFileContent(true);
getFooterIncludeFileContent(true);
getForbiddenIncludeFileContent(true);
getHttpHeaderIncludeFileContent(true);
}
private transient String footer = null;
/**
* Get the contents of the footer include file.
*
* @param force if true, reload even if already set
* @return an empty string if it could not be read successfully, the
* contents of the file otherwise.
* @see Configuration#FOOTER_INCLUDE_FILE
*/
public String getFooterIncludeFileContent(boolean force) {<FILL_FUNCTION_BODY>}
private transient String header = null;
/**
* Get the contents of the header include file.
*
* @param force if true, reload even if already set
* @return an empty string if it could not be read successfully, the
* contents of the file otherwise.
* @see Configuration#HEADER_INCLUDE_FILE
*/
public String getHeaderIncludeFileContent(boolean force) {
if (header == null || force) {
header = getFileContent(new File(RuntimeEnvironment.getInstance().getIncludeRootPath(),
Configuration.HEADER_INCLUDE_FILE));
}
return header;
}
private transient String body = null;
/**
* Get the contents of the body include file.
*
* @param force if true, reload even if already set
* @return an empty string if it could not be read successfully, the
* contents of the file otherwise.
* @see Configuration#BODY_INCLUDE_FILE
*/
public String getBodyIncludeFileContent(boolean force) {
if (body == null || force) {
body = getFileContent(new File(RuntimeEnvironment.getInstance().getIncludeRootPath(),
Configuration.BODY_INCLUDE_FILE));
}
return body;
}
private transient String eforbidden_content = null;
/**
* Get the contents of the page for forbidden error page (403 Forbidden)
* include file.
*
* @param force if true, reload even if already set
* @return an empty string if it could not be read successfully, the
* contents of the file otherwise.
* @see Configuration#E_FORBIDDEN_INCLUDE_FILE
*/
public String getForbiddenIncludeFileContent(boolean force) {
if (eforbidden_content == null || force) {
eforbidden_content = getFileContent(new File(RuntimeEnvironment.getInstance().getIncludeRootPath(),
Configuration.E_FORBIDDEN_INCLUDE_FILE));
}
return eforbidden_content;
}
private transient String http_header = null;
/**
* Get the contents of the HTTP header include file.
*
* @param force if true, reload even if already set
* @return an empty string if it could not be read successfully, the
* contents of the file otherwise.
* @see Configuration#HTTP_HEADER_INCLUDE_FILE
*/
public String getHttpHeaderIncludeFileContent(boolean force) {
if (http_header == null || force) {
http_header = getFileContent(new File(RuntimeEnvironment.getInstance().getIncludeRootPath(),
Configuration.HTTP_HEADER_INCLUDE_FILE));
}
return http_header;
}
}
|
if (footer == null || force) {
footer = getFileContent(new File(RuntimeEnvironment.getInstance().getIncludeRootPath(),
Configuration.FOOTER_INCLUDE_FILE));
}
return footer;
| 930
| 61
| 991
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/IndexSearcherFactory.java
|
IndexSearcherFactory
|
newSearcher
|
class IndexSearcherFactory extends SearcherFactory {
public IndexSearcher newSearcher(IndexReader reader) {
return newSearcher(reader, null);
}
@Override
public IndexSearcher newSearcher(IndexReader reader, IndexReader prev) {<FILL_FUNCTION_BODY>}
}
|
// The previous IndexReader is not used here.
return new IndexSearcher(reader, RuntimeEnvironment.getInstance().getSearchExecutor());
| 85
| 35
| 120
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/IndexTimestamp.java
|
IndexTimestamp
|
stamp
|
class IndexTimestamp {
private Date lastModified;
private static final Logger LOGGER = LoggerFactory.getLogger(IndexTimestamp.class);
/**
* Get the date of the last index update.
*
* @return the time of the last index update.
*/
public Date getDateForLastIndexRun() {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (lastModified == null) {
File timestamp = new File(env.getDataRootFile(), "timestamp");
if (timestamp.exists()) {
lastModified = new Date(timestamp.lastModified());
}
}
return lastModified;
}
public void refreshDateForLastIndexRun() {
lastModified = null;
}
public void stamp() throws IOException {<FILL_FUNCTION_BODY>}
}
|
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File timestamp = new File(env.getDataRootFile(), "timestamp");
String purpose = "used for timestamping the index database.";
if (timestamp.exists()) {
if (!timestamp.setLastModified(System.currentTimeMillis())) {
LOGGER.log(Level.WARNING, "Failed to set last modified time on ''{0}'', {1}",
new Object[]{timestamp.getAbsolutePath(), purpose});
}
} else {
if (!timestamp.createNewFile()) {
LOGGER.log(Level.WARNING, "Failed to create file ''{0}'', {1}",
new Object[]{timestamp.getAbsolutePath(), purpose});
}
}
| 211
| 181
| 392
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/OpenGrokThreadFactory.java
|
OpenGrokThreadFactory
|
newThread
|
class OpenGrokThreadFactory implements ThreadFactory {
private final String threadPrefix;
public static final String PREFIX = "OpenGrok-";
public OpenGrokThreadFactory(String name) {
if (!name.endsWith("-")) {
threadPrefix = name + "-";
} else {
threadPrefix = name;
}
}
@Override
public Thread newThread(@NotNull Runnable runnable) {<FILL_FUNCTION_BODY>}
}
|
Thread thread = Executors.defaultThreadFactory().newThread(Objects.requireNonNull(runnable, "runnable"));
thread.setName(PREFIX + threadPrefix + thread.getId());
return thread;
| 127
| 55
| 182
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/PathAccepter.java
|
PathAccepter
|
accept
|
class PathAccepter {
private static final Logger LOGGER = LoggerFactory.getLogger(PathAccepter.class);
private final IgnoredNames ignoredNames;
private final Filter includedNames;
/**
* Package-private to be initialized from the runtime environment.
*/
PathAccepter(IgnoredNames ignoredNames, Filter includedNames) {
this.ignoredNames = ignoredNames;
this.includedNames = includedNames;
}
/**
* Evaluates the specified {@code file} versus the runtime configuration of
* ignored files and directories or of specified inclusive filtering, and
* returns a value whether the {@code file} is to be accepted.
* @param file a defined instance under the source root
*/
public boolean accept(File file) {<FILL_FUNCTION_BODY>}
}
|
if (!includedNames.isEmpty()
&& // the filter should not affect directory names
(!(file.isDirectory() || includedNames.match(file)))) {
LOGGER.finer(() -> String.format("not including '%s'", launderLog(file.getAbsolutePath())));
return false;
}
if (ignoredNames.ignore(file)) {
LOGGER.finer(() -> String.format("ignoring '%s'", launderLog(file.getAbsolutePath())));
return false;
}
return true;
| 207
| 144
| 351
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/PatternUtil.java
|
PatternUtil
|
compilePattern
|
class PatternUtil {
private PatternUtil() {
// private to enforce static
}
/**
* A check if a pattern contains at least one pair of parentheses meaning
* that there is at least one capture group. This group must not be empty.
*/
private static final String PATTERN_SINGLE_GROUP = ".*\\([^\\)]+\\).*";
/**
* Error string for invalid patterns without a single group. This is passed
* as a first argument to the constructor of PatternSyntaxException and in
* the output it is followed by the invalid pattern.
*
* @see PatternSyntaxException
* @see #PATTERN_SINGLE_GROUP
*/
private static final String PATTERN_MUST_CONTAIN_GROUP = "The pattern must contain at least one non-empty group -";
/**
* Check and compile the bug pattern.
*
* @param pattern the new pattern
* @throws PatternSyntaxException when the pattern is not a valid regexp or
* does not contain at least one capture group and the group does not
* contain a single character
*/
public static String compilePattern(String pattern) throws PatternSyntaxException {<FILL_FUNCTION_BODY>}
}
|
if (!pattern.matches(PATTERN_SINGLE_GROUP)) {
throw new PatternSyntaxException(PATTERN_MUST_CONTAIN_GROUP, pattern, 0);
}
return Pattern.compile(pattern).toString();
| 310
| 65
| 375
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/StatsdConfig.java
|
StatsdConfig
|
getForHelp
|
class StatsdConfig {
private int port;
private String host;
private boolean enabled;
private StatsdFlavor flavor;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public StatsdFlavor getFlavor() {
return flavor;
}
public void setFlavor(StatsdFlavor flavor) {
this.flavor = flavor;
}
public boolean isEnabled() {
return port != 0 && host != null && !host.isEmpty() && flavor != null;
}
/**
* Gets an instance version suitable for helper documentation by shifting
* most default properties slightly.
*/
static StatsdConfig getForHelp() {<FILL_FUNCTION_BODY>}
}
|
StatsdConfig res = new StatsdConfig();
res.setHost("foo.bar");
res.setPort(8125);
res.setFlavor(StatsdFlavor.ETSY);
return res;
| 255
| 61
| 316
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/SuperIndexSearcherFactory.java
|
SuperIndexSearcherFactory
|
newSearcher
|
class SuperIndexSearcherFactory extends SearcherFactory {
@Override
public SuperIndexSearcher newSearcher(IndexReader r, IndexReader prev) {<FILL_FUNCTION_BODY>}
}
|
// The previous IndexReader is not used here.
return new SuperIndexSearcher(r, RuntimeEnvironment.getInstance().getSearchExecutor());
| 55
| 36
| 91
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/configuration/WatchDogService.java
|
WatchDogService
|
start
|
class WatchDogService {
private static final Logger LOGGER = LoggerFactory.getLogger(WatchDogService.class);
private Thread watchDogThread;
private WatchService watchDogWatcher;
public static final int THREAD_SLEEP_TIME = 2000;
WatchDogService() {
}
/**
* Starts a watch dog service for a directory. It automatically reloads the
* AuthorizationFramework if there was a change in <b>real-time</b>.
* Suitable for plugin development.
*
* You can control start of this service by a configuration parameter
* {@link Configuration#authorizationWatchdogEnabled}
*
* @param directory root directory for plugins
*/
public void start(File directory) {<FILL_FUNCTION_BODY>}
/**
* Stops the watch dog service.
*/
public void stop() {
if (watchDogWatcher != null) {
try {
watchDogWatcher.close();
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Cannot close WatchDogService: ", ex);
}
}
if (watchDogThread != null) {
watchDogThread.interrupt();
try {
watchDogThread.join();
} catch (InterruptedException ex) {
LOGGER.log(Level.WARNING, "Cannot join WatchDogService thread: ", ex);
}
}
LOGGER.log(Level.INFO, "Watchdog stopped");
}
}
|
stop();
if (directory == null || !directory.isDirectory() || !directory.canRead()) {
LOGGER.log(Level.INFO, "Watch dog cannot be started - invalid directory: {0}", directory);
return;
}
LOGGER.log(Level.INFO, "Starting watchdog in: {0}", directory);
watchDogThread = new Thread(() -> {
try {
watchDogWatcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get(directory.getAbsolutePath());
Files.walkFileTree(dir, new SimpleFileVisitor<>() {
@Override
public FileVisitResult postVisitDirectory(Path d, IOException exc) throws IOException {
// attach monitor
LOGGER.log(Level.FINEST, "Watchdog registering {0}", d);
d.register(watchDogWatcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
return CONTINUE;
}
});
LOGGER.log(Level.INFO, "Watch dog started {0}", directory);
while (!Thread.currentThread().isInterrupted()) {
final WatchKey key;
try {
key = watchDogWatcher.take();
} catch (ClosedWatchServiceException x) {
break;
}
boolean reload = false;
for (WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
if (kind == ENTRY_CREATE || kind == ENTRY_DELETE || kind == ENTRY_MODIFY) {
reload = true;
}
}
if (reload) {
Thread.sleep(THREAD_SLEEP_TIME); // experimental wait if file is being written right now
RuntimeEnvironment.getInstance().getAuthorizationFramework().reload();
}
if (!key.reset()) {
break;
}
}
} catch (InterruptedException | IOException ex) {
LOGGER.log(Level.FINEST, "Watchdog finishing (exiting)", ex);
Thread.currentThread().interrupt();
}
LOGGER.log(Level.FINER, "Watchdog finishing (exiting)");
}, "watchDogService");
watchDogThread.start();
| 398
| 581
| 979
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/AbstractCache.java
|
AbstractCache
|
clearFile
|
class AbstractCache implements Cache {
public boolean hasCacheForFile(File file) throws CacheException {
try {
return getCachedFile(file).exists();
} catch (CacheException ex) {
throw new CacheException(ex);
}
}
/**
* Get a <code>File</code> object describing the cache file.
*
* @param file the file to find the cache for
* @return file that might contain cached object for <code>file</code>
* @throws CacheException on error
*/
File getCachedFile(File file) throws CacheException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
StringBuilder sb = new StringBuilder();
sb.append(env.getDataRootPath());
sb.append(File.separatorChar);
sb.append(getCacheDirName());
try {
String add = env.getPathRelativeToSourceRoot(file);
if (add.length() == 0) {
add = File.separator;
}
sb.append(add);
} catch (ForbiddenSymlinkException | IOException e) {
throw new CacheException(String.format("Failed to get path relative to source root for '%s'", file), e);
}
String suffix = getCacheFileSuffix();
if (suffix != null && !suffix.isEmpty()) {
return new File(TandemPath.join(sb.toString(), suffix));
}
return new File(sb.toString());
}
public List<String> clearCache(Collection<RepositoryInfo> repositories) {
List<String> clearedRepos = new ArrayList<>();
for (RepositoryInfo repo : repositories) {
try {
this.clear(repo);
clearedRepos.add(repo.getDirectoryNameRelative());
LOGGER.log(Level.INFO, "{1} cache for ''{0}'' cleared.",
new Object[]{repo.getDirectoryName(), this.getInfo()});
} catch (CacheException e) {
LOGGER.log(Level.WARNING,
"Clearing cache for repository ''{0}'' failed: {1}",
new Object[]{repo.getDirectoryName(), e.getLocalizedMessage()});
}
}
return clearedRepos;
}
/**
* Attempt to delete file with its parent.
* @param file file to delete
*/
static void clearWithParent(File file) {
File parent = file.getParentFile();
if (!file.delete() && file.exists()) {
LOGGER.log(Level.WARNING, "Failed to remove obsolete cache-file: ''{0}''", file.getAbsolutePath());
}
if (parent.delete()) {
LOGGER.log(Level.FINE, "Removed empty cache dir: ''{0}''", parent.getAbsolutePath());
}
}
public void clearFile(String path) {<FILL_FUNCTION_BODY>}
public String getCacheFileSuffix() {
return "";
}
}
|
File historyFile;
try {
historyFile = getCachedFile(new File(RuntimeEnvironment.getInstance().getSourceRootPath() + path));
} catch (CacheException ex) {
LOGGER.log(Level.WARNING, String.format("cannot get cached file for file '%s'"
+ " - the cache entry will not be cleared", path), ex);
return;
}
clearWithParent(historyFile);
| 769
| 107
| 876
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/AccuRevAnnotationParser.java
|
AccuRevAnnotationParser
|
processStream
|
class AccuRevAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(AccuRevAnnotationParser.class);
private static final Pattern ANNOTATION_PATTERN
= Pattern.compile("^\\s+(\\d+.\\d+)\\s+(\\w+)"); // version, user
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
private final String fileName;
/**
* @param fileName the name of the file being annotated
*/
public AccuRevAnnotationParser(String fileName) {
annotation = new Annotation(fileName);
this.fileName = fileName;
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try (BufferedReader reader
= new BufferedReader(new InputStreamReader(input))) {
String line;
int lineno = 0;
try {
while ((line = reader.readLine()) != null) {
++lineno;
Matcher matcher = ANNOTATION_PATTERN.matcher(line);
if (matcher.find()) {
// On Windows machines version shows up as
// <number>\<number>. To get search annotation
// to work properly, need to flip '\' to '/'.
// This is a noop on Unix boxes.
String version = matcher.group(1).replace('\\', '/');
String author = matcher.group(2);
annotation.addLine(version, author, true);
} else {
LOGGER.log(Level.WARNING,
"Did not find annotation in line {0} for ''{1}'': [{2}]",
new Object[]{lineno, this.fileName, line});
}
}
} catch (IOException e) {
LOGGER.log(Level.WARNING,
String.format("Could not read annotations for '%s'", this.fileName), e);
}
}
| 262
| 303
| 565
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/AccuRevHistoryParser.java
|
AccuRevHistoryParser
|
parse
|
class AccuRevHistoryParser implements Executor.StreamHandler {
private AccuRevRepository repository;
private History history;
/**
* Parse the history for the specified file.
*
* @param file the file to parse history for
* @param repos Pointer to the {@code AccuRevRepository}
* @return object representing the file's history
* @throws HistoryException if a problem occurs while executing p4 command
*/
History parse(File file, Repository repos) throws HistoryException {<FILL_FUNCTION_BODY>}
@Override
public void processStream(InputStream input) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(input));
List<HistoryEntry> entries = new ArrayList<>();
String line;
String user;
Date date;
HistoryEntry entry = null;
history = new History();
/*
* Accurev history of an element (directory or file) looks like:
*
* NOSONAR element: /./path/to/element eid: 238865 transaction 1486194; purge;
* 2012/02/28 12:46:55 ; user: tluksha version 2541/1 (2539/1)
*
* transaction 1476285; purge; 2012/02/03 12:16:25 ; user: shaehn
* version 4241/1 (4241/1)
*
* transaction 1317224; promote; 2011/05/03 11:37:56 ; user: mtrinh #
* changes to ngb to compile on windows version 13/93 (1000/2)
*
* ...
*
* What is of interest then is: user (author), version (revision), date,
* comment (message)
*
* Any lines not recognized are ignored.
*/
while ((line = in.readLine()) != null) {
if (line.startsWith("e")) {
continue;
} // ignore element, eid
if (line.startsWith("t")) { // found transaction
String[] data = line.split("; ");
entry = new HistoryEntry();
user = data[3].replaceFirst("user: ", "");
entry.setMessage("");
entry.setAuthor(user);
try {
date = repository.parse(data[2]);
entry.setDate(date);
} catch (ParseException pe) {
//
// Overriding processStream() thus need to comply with the
// set of exceptions it can throw.
//
throw new IOException("Could not parse date: " + line, pe);
}
} else if (line.startsWith(" #") && (entry != null)) { // found comment
entry.appendMessage(line.substring(3));
} else if (line.startsWith(" v") && (entry != null)) { // found version
String[] data = line.split("\\s+");
entry.setRevision(data[2]);
entry.setActive(true);
entries.add(entry);
}
}
history.setHistoryEntries(entries);
}
}
|
repository = (AccuRevRepository) repos;
history = null;
String relPath = repository.getDepotRelativePath(file);
/*
* When the path given is really just the root to the source
* workarea, no history is available, create fake.
*/
String rootRelativePath = File.separator + "." + File.separator;
if (relPath.equals(rootRelativePath)) {
List<HistoryEntry> entries = new ArrayList<>();
entries.add(new HistoryEntry(
"", new Date(), "OpenGrok", "Workspace Root", true));
history = new History(entries);
} else {
/*
* Errors will be logged, so not bothering to add to the output.
*/
Executor executor = repository.getHistoryLogExecutor(file);
executor.exec(true, this);
}
return history;
| 862
| 239
| 1,101
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/Annotation.java
|
Annotation
|
generateColors
|
class Annotation {
private static final Logger LOGGER = LoggerFactory.getLogger(Annotation.class);
AnnotationData annotationData;
private final Map<String, String> desc = new HashMap<>(); // maps revision to description
private final Map<String, Integer> fileVersions = new HashMap<>(); // maps revision to file version
private final LazilyInstantiate<Map<String, String>> colors = LazilyInstantiate.using(this::generateColors);
public Annotation(String filename) {
annotationData = new AnnotationData(filename);
}
public Annotation(AnnotationData annotationData) {
this.annotationData = annotationData;
}
void addLine(String revision, String author, boolean enabled) {
annotationData.addLine(revision, author, enabled, null);
}
void addLine(String revision, String author, boolean enabled, String displayRevision) {
annotationData.addLine(revision, author, enabled, displayRevision);
}
public String getFilename() {
return annotationData.getFilename();
}
public void setRevision(String revision) {
annotationData.setRevision(revision);
}
/**
* @return revision this annotation was generated for
*/
public String getRevision() {
return annotationData.getRevision();
}
/**
* Returns the size of the file (number of lines).
*
* @return number of lines
*/
public int size() {
return annotationData.size();
}
/**
* Gets the revision for the last change to the specified line.
*
* @param line line number (counting from 1)
* @return revision string, or an empty string if there is no information
* about the specified line
*/
public String getRevision(int line) {
return annotationData.getRevision(line);
}
/**
* Gets the revision for the last change to the specified line in a format that may be specifically for display purposes.
*
* @param line line number (counting from 1)
* @return revision string, or an empty string if there is no information
* about the specified line
*/
public String getRevisionForDisplay(int line) {
return annotationData.getRevisionForDisplay(line);
}
/**
* Gets all revisions that are in use, first is the lowest one (sorted using natural order).
*
* @return list of all revisions the file has
*/
public Set<String> getRevisions() {
return annotationData.getRevisions();
}
@TestOnly
Set<String> getAuthors() {
return annotationData.getAuthors();
}
/**
* Gets the author who last modified the specified line.
*
* @param line line number (counting from 1)
* @return author, or an empty string if there is no information about the
* specified line
*/
public String getAuthor(int line) {
return annotationData.getAuthor(line);
}
public int getWidestRevision() {
return annotationData.getWidestRevision();
}
public int getWidestAuthor() {
return annotationData.getWidestAuthor();
}
/**
* Gets the enabled state for the last change to the specified line.
*
* @param line line number (counting from 1)
* @return true if the xref for this revision is enabled, false otherwise
*/
public boolean isEnabled(int line) {
return annotationData.isEnabled(line);
}
void addDesc(String revision, String description) {
desc.put(revision, description);
}
public String getDesc(String revision) {
return desc.get(revision);
}
void addFileVersion(String revision, int fileVersion) {
fileVersions.put(revision, fileVersion);
}
/**
* Translates repository revision number into file version.
* @param revision revision number
* @return file version number. 0 if unknown. 1 first version of file, etc.
*/
public int getFileVersion(String revision) {
return fileVersions.getOrDefault(revision, 0);
}
/**
* @return Count of revisions on this file.
*/
public int getFileVersionsCount() {
return fileVersions.size();
}
/**
* Return the color palette for the annotated file.
*
* @return map of (revision, css color string) for each revision in {@code getRevisions()}
* @see #generateColors()
*/
public Map<String, String> getColors() {
return colors.get();
}
/**
* Generate the color palette for the annotated revisions.
* <p>
* First, take into account revisions which are tracked in history fields
* and compute their color. Secondly, use all other revisions in order
* which is undefined and generate the rest of the colors for them.
*
* @return map of (revision, css color string) for each revision in {@code getRevisions()}
* @see #getRevisions()
*/
private Map<String, String> generateColors() {<FILL_FUNCTION_BODY>}
//TODO below might be useless, need to test with more SCMs and different commit messages
// to see if it will not be useful, if title attribute of <a> loses it's breath
public void writeTooltipMap(Writer out) throws IOException {
out.append("<script type=\"text/javascript\">\nvar desc = new Object();\n");
for (Entry<String, String> entry : desc.entrySet()) {
out.append("desc['");
out.append(entry.getKey());
out.append("'] = \"");
out.append(entry.getValue());
out.append("\";\n");
}
out.append("</script>\n");
}
@Override
public String toString() {
StringWriter sw = new StringWriter();
for (AnnotationLine annotationLine : annotationData.getLines()) {
sw.append(annotationLine.getRevision());
sw.append("|");
sw.append(annotationLine.getAuthor());
sw.append(": \n");
}
try {
writeTooltipMap(sw);
} catch (IOException e) {
LOGGER.finest(e.getMessage());
}
return sw.toString();
}
}
|
List<Color> orderedColors = RainbowColorGenerator.getOrderedColors();
Map<String, String> colorMap = new HashMap<>();
final List<String> revisions =
getRevisions()
.stream()
/*
* Greater file version means more recent revision.
* 0 file version means unknown revision (untracked by history entries).
*
* The result of this sort is:
* 1) known revisions sorted from most recent to least recent
* 2) all other revisions in non-determined order
*/
.sorted(Comparator.comparingInt(this::getFileVersion).reversed())
.collect(Collectors.toList());
final int nColors = orderedColors.size();
final double colorsPerBucket = (double) nColors / getRevisions().size();
revisions.forEach(revision -> {
final int lineVersion = getRevisions().size() - getFileVersion(revision);
final double bucketTotal = colorsPerBucket * lineVersion;
final int bucketIndex = (int) Math.max(
Math.min(Math.floor(bucketTotal), nColors - 1.0), 0);
Color color = orderedColors.get(bucketIndex);
colorMap.put(revision, String.format("rgb(%d, %d, %d)", color.red, color.green, color.blue));
});
return colorMap;
| 1,672
| 367
| 2,039
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/AnnotationData.java
|
AnnotationData
|
equals
|
class AnnotationData implements Serializable {
private static final long serialVersionUID = -1;
// for serialization
public AnnotationData() {
}
public AnnotationData(String filename) {
this.filename = filename;
}
private List<AnnotationLine> annotationLines = new ArrayList<>();
private int widestRevision;
private int widestAuthor;
private String filename;
/**
* The revision it was generated for is used for staleness check in {@link FileAnnotationCache#get(File, String)}.
* Storing it in the filename would not work well ({@link org.opengrok.indexer.util.TandemPath}
* shortening with very long filenames), on the other hand it is necessary to deserialize the object
* to tell whether it is stale.
*/
String revision;
public List<AnnotationLine> getLines() {
return annotationLines;
}
public void setLines(List<AnnotationLine> annotationLines) {
this.annotationLines = annotationLines;
}
// For serialization.
public void setWidestRevision(int widestRevision) {
this.widestRevision = widestRevision;
}
// For serialization.
public void setWidestAuthor(int widestAuthor) {
this.widestAuthor = widestAuthor;
}
/**
* Gets the author who last modified the specified line.
*
* @param line line number (counting from 1)
* @return author, or an empty string if there is no information about the
* specified line
*/
public String getAuthor(int line) {
try {
return annotationLines.get(line - 1).getAuthor();
} catch (IndexOutOfBoundsException e) {
return "";
}
}
/**
* Gets the revision for the last change to the specified line.
*
* @param line line number (counting from 1)
* @return revision string, or an empty string if there is no information
* about the specified line
*/
public String getRevision(int line) {
try {
return annotationLines.get(line - 1).getRevision();
} catch (IndexOutOfBoundsException e) {
return "";
}
}
/**
* Gets the representation of the revision to be used for display purposes, which may be abbreviated, for the last change to the specified line.
*
* @param line line number (counting from 1)
* @return revision string, or an empty string if there is no information
* about the specified line
*/
public String getRevisionForDisplay(int line) {
try {
return annotationLines.get(line - 1).getDisplayRevision();
} catch (IndexOutOfBoundsException e) {
return "";
}
}
/**
* Gets the enabled state for the last change to the specified line.
*
* @param line line number (counting from 1)
* @return true if the xref for this revision is enabled, false otherwise
*/
public boolean isEnabled(int line) {
try {
return annotationLines.get(line - 1).isEnabled();
} catch (IndexOutOfBoundsException e) {
return false;
}
}
public void setRevision(String revision) {
this.revision = revision;
}
/**
* @return revision this annotation was generated for
*/
public String getRevision() {
return revision;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getFilename() {
return filename;
}
/**
* Returns the size of the file (number of lines).
*
* @return number of lines
*/
public int size() {
return annotationLines.size();
}
/**
* Returns the widest revision string in the file (used for pretty
* printing).
*
* @return number of characters in the widest revision string
*/
public int getWidestRevision() {
return widestRevision;
}
/**
* Returns the widest author name in the file (used for pretty printing).
*
* @return number of characters in the widest author string
*/
public int getWidestAuthor() {
return widestAuthor;
}
/**
* Adds a line to the file.
* @param annotationLine {@link AnnotationLine} instance
*/
void addLine(final AnnotationLine annotationLine) {
annotationLines.add(annotationLine);
widestRevision = Math.max(widestRevision, annotationLine.getDisplayRevision().length());
widestAuthor = Math.max(widestAuthor, annotationLine.getAuthor().length());
}
/**
* @param revision revision number
* @param author author name
* @param enabled whether the line is enabled
* @param displayRevision a specialised revision number of display purposes. Can be null in which case the revision number will be used.
* @see #addLine(AnnotationLine)
*/
void addLine(String revision, String author, boolean enabled, String displayRevision) {
final AnnotationLine annotationLine = new AnnotationLine(revision, author, enabled, displayRevision);
addLine(annotationLine);
}
/**
* Gets all revisions that are in use, first is the lowest one (sorted using natural order).
*
* @return set of all revisions for given file
*/
public Set<String> getRevisions() {
Set<String> ret = new HashSet<>();
for (AnnotationLine ln : annotationLines) {
ret.add(ln.getRevision());
}
return ret;
}
@TestOnly
Set<String> getAuthors() {
return annotationLines.stream().map(AnnotationLine::getAuthor).collect(Collectors.toSet());
}
@Override
public int hashCode() {
return Objects.hash(annotationLines, filename);
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
return Optional.ofNullable(obj)
.filter(other -> getClass() == other.getClass())
.map(AnnotationData.class::cast)
.filter(other -> Objects.deepEquals(getLines(), other.getLines()))
.filter(other -> Objects.equals(getFilename(), other.getFilename()))
.filter(other -> Objects.equals(getWidestAuthor(), other.getWidestAuthor()))
.filter(other -> Objects.equals(getWidestRevision(), other.getWidestRevision()))
.filter(other -> Objects.equals(getRevision(), other.getRevision()))
.isPresent();
| 1,585
| 174
| 1,759
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/AnnotationDataClassLoader.java
|
AnnotationDataClassLoader
|
loadClass
|
class AnnotationDataClassLoader extends ClassLoader {
private static final Set<String> allowedClasses = Set.of(
ArrayList.class,
Collections.class,
AnnotationData.class,
AnnotationLine.class,
String.class,
XMLDecoder.class
).stream().map(java.lang.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 AnnotationData object");
}
return getClass().getClassLoader().loadClass(name);
| 131
| 57
| 188
|
<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/opengrok-indexer/src/main/java/org/opengrok/indexer/history/AnnotationLine.java
|
AnnotationLine
|
equals
|
class AnnotationLine implements Serializable {
private static final long serialVersionUID = 3402729223485872826L;
private String revision;
private String author;
private boolean enabled;
private String displayRevision;
public AnnotationLine() {
// for serialization
}
/**
* An annotation line where the revision is not overridden for display purposes.
* @param revision revision string
* @param author author string
* @param enabled whether it is enabled
*/
AnnotationLine(String revision, String author, boolean enabled) {
this(revision, author, enabled, null);
}
AnnotationLine(String revision, String author, boolean enabled, String displayRevision) {
this.revision = revision == null ? "" : revision;
this.author = author == null ? "" : author;
this.enabled = enabled;
this.setDisplayRevision(displayRevision);
}
public String getRevision() {
return revision;
}
public String getAuthor() {
return author;
}
public boolean isEnabled() {
return enabled;
}
public void setRevision(String revision) {
this.revision = revision;
}
public void setAuthor(String author) {
this.author = author;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* A specialised revision for display purposes.
*
* @return the display revision if not null, otherwise the revision.
*/
public String getDisplayRevision() {
return displayRevision == null ? revision : displayRevision;
}
public void setDisplayRevision(String displayRevision) {
this.displayRevision = displayRevision;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(isEnabled(), getAuthor(), getRevision());
}
}
|
return Optional.ofNullable(obj)
.filter(other -> getClass() == other.getClass())
.map(AnnotationLine.class::cast)
.filter(other -> Objects.equals(isEnabled(), other.isEnabled()))
.filter(other -> Objects.equals(getAuthor(), other.getAuthor()))
.filter(other -> Objects.equals(getRevision(), other.getRevision()))
.filter(other -> Objects.equals(getDisplayRevision(), other.getDisplayRevision()))
.isPresent();
| 527
| 138
| 665
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BazaarAnnotationParser.java
|
BazaarAnnotationParser
|
processStream
|
class BazaarAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BazaarAnnotationParser.class);
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
/**
* Pattern used to extract author/revision.
*/
private static final Pattern BLAME_PATTERN = Pattern.compile("^\\W*(\\S+)\\W+(\\S+).*$");
private final String fileName;
/**
* @param fileName the name of the file being annotated
*/
public BazaarAnnotationParser(String fileName) {
annotation = new Annotation(fileName);
this.fileName = fileName;
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
String line = "";
int lineno = 0;
Matcher matcher = BLAME_PATTERN.matcher(line);
while ((line = in.readLine()) != null) {
++lineno;
matcher.reset(line);
if (matcher.find()) {
String rev = matcher.group(1);
String author = matcher.group(2).trim();
annotation.addLine(rev, author, true);
} else {
LOGGER.log(Level.WARNING,
"Error: did not find annotation in line {0} for ''{1}'': [{2}]",
new Object[]{String.valueOf(lineno), this.fileName, line});
}
}
}
| 271
| 208
| 479
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BazaarHistoryParser.java
|
BazaarHistoryParser
|
populateCommitFilesInHistoryEntry
|
class BazaarHistoryParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BazaarHistoryParser.class);
private String myDir;
private final List<HistoryEntry> entries = new ArrayList<>();
private final BazaarRepository repository;
BazaarHistoryParser(BazaarRepository repository) {
this.repository = repository;
myDir = repository.getDirectoryName() + File.separator;
}
History parse(File file, String sinceRevision) throws HistoryException {
try {
Executor executor = repository.getHistoryLogExecutor(file, sinceRevision);
int status = executor.exec(true, this);
if (status != 0) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\" Exit code: " + status);
}
} catch (IOException e) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\"", e);
}
// If a changeset to start from is specified, remove that changeset
// from the list, since only the ones following it should be returned.
// Also check that the specified changeset was found, otherwise throw
// an exception.
if (sinceRevision != null) {
repository.removeAndVerifyOldestChangeset(entries, sinceRevision);
}
return new History(entries);
}
/**
* Process the output from the log command and insert the HistoryEntries
* into the history field.
*
* @param input The output from the process
* @throws java.io.IOException If an error occurs while reading the stream
*/
@Override
public void processStream(InputStream input) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(input));
String s;
var entry = createHistoryEntry();
int state = 0;
while ((s = in.readLine()) != null) {
if ("------------------------------------------------------------".equals(s)) {
if (state > 2) {
entries.add(entry);
}
entry = createHistoryEntry();
state = 0;
continue;
}
switch (state) {
case 0:
// First, go on until revno is found.
state = state + populateRevisionInHistoryEntry(s, entry);
break;
case 1:
// Then, look for committer.
state = state + populateCommitterInHistoryEntry(s, entry);
break;
case 2:
// And then, look for timestamp.
state = state + populateDateInHistoryEntry(s, entry);
break;
case 3:
// Expect the commit message to follow immediately after the timestamp
state = state + populateCommitMessageInHistoryEntry(s, entry);
break;
case 4:
// Finally, store the list of modified, added and removed
// files. (Except the labels.)
populateCommitFilesInHistoryEntry(s, entry);
break;
default:
LOGGER.log(Level.WARNING, "Unknown parser state: {0}", state);
break;
}
}
if (state > 2) {
entries.add(entry);
}
}
private HistoryEntry createHistoryEntry() {
var entry = new HistoryEntry();
entry.setActive(true);
return entry;
}
/**
*
* @param currentLine currentLine of string from stream
* @param historyEntry current history entry to populate committer
*/
private void populateCommitFilesInHistoryEntry(@NotNull String currentLine,
@NotNull HistoryEntry historyEntry) throws IOException {<FILL_FUNCTION_BODY>}
/**
*
* @param currentLine currentLine of string from stream
* @param historyEntry current history entry to populate committer
* @return 1 if committer is populated else 0
*/
private int populateCommitMessageInHistoryEntry(@NotNull String currentLine, @NotNull HistoryEntry historyEntry) {
// everything up to the list of
// modified, added and removed files is part of the commit
// message.
int state = 0;
if (currentLine.startsWith("modified:") || currentLine.startsWith("added:") || currentLine.startsWith("removed:")) {
++state;
} else if (currentLine.startsWith(" ")) {
// Commit messages returned by bzr log -v are prefixed
// with two blanks.
historyEntry.appendMessage(currentLine.substring(2));
}
return state;
}
/**
*
* @param currentLine currentLine of string from stream
* @param historyEntry current history entry to populate committer
* @return 1 if committer is populated else 0
*/
private int populateCommitterInHistoryEntry(@NotNull String currentLine, @NotNull HistoryEntry historyEntry) {
int state = 0;
if (currentLine.startsWith("committer:")) {
historyEntry.setAuthor(currentLine.substring("committer:".length()).trim());
++state;
}
return state;
}
/**
*
* @param currentLine currentLine of string from stream
* @param historyEntry current history entry to populate Date
* @return 1 if Date is populated else 0
* @throws IOException on failure to parse timestamp
*/
private int populateDateInHistoryEntry(@NotNull String currentLine, @NotNull HistoryEntry historyEntry) throws IOException {
int state = 0;
if (currentLine.startsWith("timestamp:")) {
try {
Date date = repository.parse(currentLine.substring("timestamp:".length()).trim());
historyEntry.setDate(date);
} catch (ParseException e) {
//
// Overriding processStream() thus need to comply with the
// set of exceptions it can throw.
//
throw new IOException("Failed to parse history timestamp:" + currentLine, e);
}
++state;
}
return state;
}
/**
*
* @param currentLine currentLine of string from stream
* @param historyEntry current history entry to populate Revision
* @return 1 if revision is populated else 0
*/
private int populateRevisionInHistoryEntry(@NotNull String currentLine, @NotNull HistoryEntry historyEntry) {
int state = 0;
if (currentLine.startsWith("revno:")) {
String[] rev = currentLine.substring("revno:".length()).trim().split(" ");
historyEntry.setRevision(rev[0]);
++state;
}
return state;
}
/**
* Parse the given string.
*
* @param buffer The string to be parsed
* @return The parsed history
* @throws IOException if we fail to parse the buffer
*/
History parse(String buffer) throws IOException {
myDir = File.separator;
processStream(new ByteArrayInputStream(buffer.getBytes(StandardCharsets.UTF_8)));
return new History(entries);
}
}
|
if (!(currentLine.startsWith("modified:") || currentLine.startsWith("added:")
|| currentLine.startsWith("removed:"))) {
// The list of files is prefixed with blanks.
currentLine = currentLine.trim();
int idx = currentLine.indexOf(" => ");
if (idx != -1) {
currentLine = currentLine.substring(idx + 4);
}
File f = new File(myDir, currentLine);
try {
String name = RuntimeEnvironment.getInstance().getPathRelativeToSourceRoot(f);
historyEntry.addFile(name.intern());
} catch (ForbiddenSymlinkException e) {
LOGGER.log(Level.FINER, e.getMessage());
// ignored
} catch (InvalidPathException e) {
LOGGER.log(Level.WARNING, e.getMessage());
}
}
| 1,813
| 230
| 2,043
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BazaarTagEntry.java
|
BazaarTagEntry
|
compareTo
|
class BazaarTagEntry extends TagEntry {
public BazaarTagEntry(int revision, String tag) {
super(revision, tag);
}
@Override
public int compareTo(HistoryEntry that) {<FILL_FUNCTION_BODY>}
}
|
assert this.revision != NOREV : "BazaarTagEntry created without tag specified.specified";
return Integer.compare(this.revision, Integer.parseInt(that.getRevision()));
| 71
| 53
| 124
|
<methods>public int compareTo(org.opengrok.indexer.history.TagEntry) ,public abstract int compareTo(org.opengrok.indexer.history.HistoryEntry) ,public boolean equals(java.lang.Object) ,public java.util.Date getDate() ,public java.lang.String getTags() ,public int hashCode() ,public void setTags(java.lang.String) <variables>private static final java.lang.String DATE_NULL_ASSERT,protected static final int NOREV,protected final non-sealed java.util.Date date,protected final non-sealed int revision,protected java.lang.String tags
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BazaarTagParser.java
|
BazaarTagParser
|
processStream
|
class BazaarTagParser implements Executor.StreamHandler {
/**
* Store tag entries created by processStream.
*/
private final NavigableSet<TagEntry> entries = new TreeSet<>();
/**
* Returns the set of entries that has been created.
*
* @return entries a set of tag entries
*/
public NavigableSet<TagEntry> getEntries() {
return entries;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
String line;
while ((line = in.readLine()) != null) {
String[] parts = line.split(" *");
if (parts.length < 2) {
throw new IOException("Tag line contains more than 2 columns: " + line);
}
// Grrr, how to parse tags with spaces inside?
// This solution will loose multiple spaces;-/
var tag = String.join(" ", parts);
TagEntry tagEntry = new BazaarTagEntry(Integer.parseInt(parts[parts.length - 1]), tag);
// Bazaar lists multiple tags on more lines. We need to merge those into single TagEntry
TagEntry higher = entries.ceiling(tagEntry);
if (higher != null && higher.equals(tagEntry)) {
// Found in the tree, merge tags
entries.remove(higher);
tagEntry.setTags(higher.getTags() + TAGS_SEPARATOR + tag);
}
entries.add(tagEntry);
}
}
| 141
| 277
| 418
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BitKeeperAnnotationParser.java
|
BitKeeperAnnotationParser
|
processStream
|
class BitKeeperAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BitKeeperAnnotationParser.class);
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
/**
* @param fileName the name of the file being annotated
*/
public BitKeeperAnnotationParser(String fileName) {
annotation = new Annotation(fileName);
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
/**
* Process the output of a {@code bk annotate} command.
*
* Each input line should be in the following format:
* USER\tREVISION\tTEXT
*
* @param input the executor input stream
* @throws IOException if the stream reader throws an IOException
*/
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
final BufferedReader in = new BufferedReader(new InputStreamReader(input));
for (String line = in.readLine(); line != null; line = in.readLine()) {
final String[] fields = line.split("\t");
if (fields.length >= 2) {
final String author = fields[0];
final String rev = fields[1];
annotation.addLine(rev, author, true);
} else {
LOGGER.log(Level.SEVERE, "Error: malformed BitKeeper annotate output {0}", line);
}
}
| 278
| 147
| 425
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BitKeeperHistoryParser.java
|
BitKeeperHistoryParser
|
processStream
|
class BitKeeperHistoryParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BitKeeperHistoryParser.class);
/**
* Parses dates.
*/
private final SimpleDateFormat dateFormat;
/**
* Store entries processed from executor output.
*/
private final List<HistoryEntry> entries = new ArrayList<>();
/**
* Store renamed files processed from executor output.
*/
private final Set<String> renamedFiles = new TreeSet<>();
/**
* Constructor to construct the thing to be constructed.
*
* @param datePattern a simple date format string
*/
BitKeeperHistoryParser(String datePattern) {
dateFormat = new SimpleDateFormat(datePattern);
}
/**
* Returns the history that has been created.
*
* @return history a history object
*/
History getHistory() {
return new History(entries, new ArrayList<>(renamedFiles));
}
/**
* Process the output of a `bk log` command.
*
* Each input line should be in the following format:
* either
* D FILE\tREVISION\tDATE\tUSER(\tRENAMED_FROM)?
* or
* C COMMIT_MESSAGE_LINE
*
* BitKeeper always outputs the file name relative to its root directory, which is nice for us since that's what
* History expects.
*
* @param input the executor input stream
* @throws IOException if the stream reader throws an IOException
*/
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
HistoryEntry entry = null;
final BufferedReader in = new BufferedReader(new InputStreamReader(input));
for (String line = in.readLine(); line != null; line = in.readLine()) {
if (line.startsWith("D ")) {
entry = null;
try {
final String[] fields = line.substring(2).split("\t");
final HistoryEntry newEntry = new HistoryEntry();
if (fields[0].equals("ChangeSet")) {
continue;
}
newEntry.addFile(fields[0].intern());
newEntry.setRevision(fields[1]);
newEntry.setDate(dateFormat.parse(fields[2]));
newEntry.setAuthor(fields[3]);
newEntry.setActive(true);
entry = newEntry;
entries.add(entry);
if (fields.length == 5) {
renamedFiles.add(fields[4]);
}
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Error: malformed BitKeeper log output {0}", line);
}
} else if (line.startsWith("C ") && (entry != null)) {
final String messageLine = line.substring(2);
entry.appendMessage(messageLine);
}
}
| 439
| 336
| 775
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BitKeeperTagEntry.java
|
BitKeeperTagEntry
|
compareTo
|
class BitKeeperTagEntry extends TagEntry {
protected String changeset;
public BitKeeperTagEntry(String changeset, Date date, String tag) {
super(date, tag);
this.changeset = changeset;
}
@Override
public int compareTo(HistoryEntry that) {<FILL_FUNCTION_BODY>}
}
|
assert this.date != null : "BitKeeper TagEntry created without date specified";
return this.date.compareTo(that.getDate());
| 94
| 40
| 134
|
<methods>public int compareTo(org.opengrok.indexer.history.TagEntry) ,public abstract int compareTo(org.opengrok.indexer.history.HistoryEntry) ,public boolean equals(java.lang.Object) ,public java.util.Date getDate() ,public java.lang.String getTags() ,public int hashCode() ,public void setTags(java.lang.String) <variables>private static final java.lang.String DATE_NULL_ASSERT,protected static final int NOREV,protected final non-sealed java.util.Date date,protected final non-sealed int revision,protected java.lang.String tags
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BitKeeperTagParser.java
|
BitKeeperTagParser
|
processStream
|
class BitKeeperTagParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BitKeeperTagParser.class);
/**
* Parses dates.
*/
private final SimpleDateFormat dateFormat;
/**
* Store tag entries created by {@link #processStream(InputStream)}.
*/
private final NavigableSet<TagEntry> entries = new TreeSet<>();
/**
* Constructor to construct the thing to be constructed.
*
* @param datePattern a simple date format string
*/
public BitKeeperTagParser(String datePattern) {
dateFormat = new SimpleDateFormat(datePattern);
}
/**
* Returns the set of entries that has been created.
*
* @return entries a set of tag entries
*/
public NavigableSet<TagEntry> getEntries() {
return entries;
}
/**
* Process the output of the {@code bk tags} command.
*
* Each input line should be in the following format:
* either
* {@code D REVISION\tDATE}
* or
* {@code T TAG}
*
* @param input the executor input stream
* @throws IOException if the stream reader throws an IOException
*/
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
String revision = null;
Date date = null;
String tag;
final BufferedReader in = new BufferedReader(new InputStreamReader(input));
for (String line = in.readLine(); line != null; line = in.readLine()) {
if (line.startsWith("D ")) {
final String[] fields = line.substring(2).split("\t");
try {
revision = fields[0];
date = dateFormat.parse(fields[1]);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Error: malformed BitKeeper tags output {0}", line);
}
} else if (line.startsWith("T ") && (date != null)) {
tag = line.substring(2);
entries.add(new BitKeeperTagEntry(revision, date, tag));
}
}
| 363
| 228
| 591
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/BoundaryChangesets.java
|
IdWithProgress
|
getBoundaryChangesetIDs
|
class IdWithProgress {
private final Progress progress;
private final String id;
IdWithProgress(String id, Progress progress) {
this.id = id;
this.progress = progress;
}
public String getId() {
return id;
}
public Progress getProgress() {
return progress;
}
}
/**
* @param sinceRevision start revision ID
* @return immutable list of revision IDs denoting the intervals
* @throws HistoryException if there is problem traversing the changesets in the repository
*/
public synchronized List<String> getBoundaryChangesetIDs(String sinceRevision) throws HistoryException {<FILL_FUNCTION_BODY>
|
reset();
Level logLevel = Level.FINE;
LOGGER.log(logLevel, "getting boundary changesets for {0}", repository);
Statistics stat = new Statistics();
try (Progress progress = new Progress(LOGGER, String.format("changesets visited of %s", this.repository),
logLevel)) {
repository.accept(sinceRevision, this::visit, progress);
}
// The changesets need to go from oldest to newest.
Collections.reverse(result);
stat.report(LOGGER, logLevel,
String.format("Done getting boundary changesets for %s (%d entries)",
repository, result.size()));
return List.copyOf(result);
| 182
| 184
| 366
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/CVSAnnotationParser.java
|
CVSAnnotationParser
|
processStream
|
class CVSAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(CVSAnnotationParser.class);
/**
* Pattern used to extract author/revision from {@code cvs annotate}.
*/
private static final Pattern ANNOTATE_PATTERN = Pattern.compile("([\\.\\d]+)\\W+\\((\\w+)");
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
private final String fileName;
/**
* @param fileName the name of the file being annotated
*/
public CVSAnnotationParser(String fileName) {
annotation = new Annotation(fileName);
this.fileName = fileName;
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
BufferedReader in = new BufferedReader(new InputStreamReader(input));
String line = "";
int lineno = 0;
boolean hasStarted = false;
Matcher matcher = ANNOTATE_PATTERN.matcher(line);
while ((line = in.readLine()) != null) {
// Skip header
if (!hasStarted && (line.length() == 0 || !Character.isDigit(line.charAt(0)))) {
continue;
}
hasStarted = true;
// Start parsing
++lineno;
matcher.reset(line);
if (matcher.find()) {
String rev = matcher.group(1);
String author = matcher.group(2).trim();
annotation.addLine(rev, author, true);
} else {
LOGGER.log(Level.WARNING,
"Error: did not find annotation in line {0} for ''{1}'': [{2}]",
new Object[]{String.valueOf(lineno), this.fileName, line});
}
}
| 274
| 273
| 547
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/CVSHistoryParser.java
|
CVSHistoryParser
|
parseTag
|
class CVSHistoryParser implements Executor.StreamHandler {
private enum ParseState {
NAMES, TAG, REVISION, METADATA, COMMENT
}
private History history;
private CVSRepository cvsRepository = new CVSRepository();
/**
* Process the output from the log command and insert the {@link HistoryEntry} objects created therein
* into the {@link #history} field.
*
* @param input The output from the process
* @throws java.io.IOException If an error occurs while reading the stream
*/
@Override
public void processStream(InputStream input) throws IOException {
ArrayList<HistoryEntry> entries = new ArrayList<>();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
history = new History();
HistoryEntry entry = null;
HashMap<String, String> tags = null;
ParseState state = ParseState.NAMES;
String s = in.readLine();
while (s != null) {
if (state == ParseState.NAMES && s.startsWith("symbolic names:")) {
tags = new HashMap<>();
state = ParseState.TAG;
s = in.readLine();
}
if (state == ParseState.TAG) {
if (s.startsWith("\t")) {
parseTag(tags, s);
} else {
state = ParseState.REVISION;
s = in.readLine();
}
}
if (state == ParseState.REVISION && s.startsWith("revision ")) {
if (entry != null) {
entries.add(entry);
}
entry = new HistoryEntry();
entry.setActive(true);
String commit = s.substring("revision".length()).trim();
entry.setRevision(commit);
if (tags.containsKey(commit)) {
history.addTags(entry, tags.get(commit));
}
state = ParseState.METADATA;
s = in.readLine();
}
if (state == ParseState.METADATA && s.startsWith("date: ")) {
parseDateAuthor(entry, s);
state = ParseState.COMMENT;
s = in.readLine();
}
if (state == ParseState.COMMENT) {
if (s.equals("----------------------------")) {
state = ParseState.REVISION;
} else if (s.equals("=============================================================================")) {
state = ParseState.NAMES;
} else {
if (entry != null) {
entry.appendMessage(s);
}
}
}
s = in.readLine();
}
if (entry != null) {
entries.add(entry);
}
history.setHistoryEntries(entries);
}
private void parseDateAuthor(HistoryEntry entry, String s) throws IOException {
for (String pair : s.split(";")) {
String[] keyVal = pair.split(":", 2);
String key = keyVal[0].trim();
String val = keyVal[1].trim();
if ("date".equals(key)) {
try {
val = val.replace('/', '-');
entry.setDate(cvsRepository.parse(val));
} catch (ParseException pe) {
//
// Overriding processStream() thus need to comply with the
// set of exceptions it can throw.
//
throw new IOException("Failed to parse date: '" + val + "'", pe);
}
} else if ("author".equals(key)) {
entry.setAuthor(val);
}
}
}
private void parseTag(HashMap<String, String> tags, String s) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Sort history entries in the object according to semantic ordering of the revision string.
* @param history {@link History} object
*/
@VisibleForTesting
static void sortHistoryEntries(History history) {
List<HistoryEntry> entries = history.getHistoryEntries();
entries.sort((h1, h2) -> new Version(h2.getRevision()).compareTo(new Version(h1.getRevision())));
history.setHistoryEntries(entries);
}
/**
* Parse the history for the specified file.
*
* @param file the file to parse history for
* @param repository Pointer to the SubversionRepository
* @return object representing the file's history
*/
History parse(File file, Repository repository) throws HistoryException {
cvsRepository = (CVSRepository) repository;
try {
Executor executor = cvsRepository.getHistoryLogExecutor(file);
int status = executor.exec(true, this);
if (status != 0) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\" Exit code: " + status);
}
} catch (IOException e) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\"", e);
}
// In case there is a branch, the log entries can be returned in
// unsorted order (as a result of using '-r1.1:branch' for 'cvs log')
// so they need to be sorted according to revision.
if (cvsRepository.getBranch() != null && !cvsRepository.getBranch().isEmpty()) {
sortHistoryEntries(history);
}
return history;
}
/**
* Parse the given string. Used for testing.
*
* @param buffer The string to be parsed
* @return The parsed history
* @throws IOException if we fail to parse the buffer
*/
@VisibleForTesting
History parse(String buffer) throws IOException {
processStream(new ByteArrayInputStream(buffer.getBytes(StandardCharsets.UTF_8)));
return history;
}
}
|
String[] pair = s.trim().split(": ");
if (pair.length != 2) {
//
// Overriding processStream() thus need to comply with the
// set of exceptions it can throw.
//
throw new IOException("Failed to parse tag: '" + s + "'");
} else {
if (tags.containsKey(pair[1])) {
// Join multiple tags for one revision
String oldTag = tags.get(pair[1]);
tags.remove(pair[1]);
tags.put(pair[1], oldTag + " " + pair[0]);
} else {
tags.put(pair[1], pair[0]);
}
}
| 1,530
| 174
| 1,704
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/CacheUtil.java
|
CacheUtil
|
clearCacheDir
|
class CacheUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheUtil.class);
private CacheUtil() {
// private to enforce static
}
/**
*
* @param repository {@link RepositoryInfo} instance
* @param cache {@link Cache} instance
* @return absolute directory path for top level cache directory of given repository.
* Will return {@code null} on error.
*/
@VisibleForTesting
@Nullable
public static String getRepositoryCacheDataDirname(RepositoryInfo repository, Cache cache) {
String repoDirBasename;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
try {
repoDirBasename = env.getPathRelativeToSourceRoot(new File(repository.getDirectoryName()));
} catch (IOException ex) {
LOGGER.log(Level.WARNING,
String.format("Could not resolve repository '%s' relative to source root", repository), ex);
return null;
} catch (ForbiddenSymlinkException ex) {
LOGGER.log(Level.FINER, ex.getMessage());
return null;
}
return env.getDataRootPath() + File.separatorChar
+ cache.getCacheDirName()
+ repoDirBasename;
}
public static void clearCacheDir(RepositoryInfo repository, Cache cache) {<FILL_FUNCTION_BODY>}
}
|
String histDir = CacheUtil.getRepositoryCacheDataDirname(repository, cache);
if (histDir != null) {
// Remove all files which constitute the history cache.
try {
IOUtils.removeRecursive(Paths.get(histDir));
} catch (NoSuchFileException ex) {
LOGGER.log(Level.WARNING, String.format("directory '%s' does not exist", histDir));
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "tried removeRecursive()", ex);
}
}
| 347
| 145
| 492
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/ClearCaseAnnotationParser.java
|
ClearCaseAnnotationParser
|
processStream
|
class ClearCaseAnnotationParser implements Executor.StreamHandler {
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
/**
* @param fileName the name of the file being annotated
*/
public ClearCaseAnnotationParser(String fileName) {
annotation = new Annotation(fileName);
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
String line;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(input))) {
while ((line = in.readLine()) != null) {
String[] parts = line.split("\\|");
String aAuthor = parts[0];
String aRevision = parts[1];
aRevision = aRevision.replace('\\', '/');
annotation.addLine(aRevision, aAuthor, true);
}
}
| 166
| 121
| 287
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/ClearCaseHistoryParser.java
|
ClearCaseHistoryParser
|
processStream
|
class ClearCaseHistoryParser implements Executor.StreamHandler {
private History history;
private ClearCaseRepository repository = new ClearCaseRepository();
History parse(File file, Repository repos) throws HistoryException {
repository = (ClearCaseRepository) repos;
try {
Executor executor = repository.getHistoryLogExecutor(file);
int status = executor.exec(true, this);
if (status != 0) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\" Exit code: " + status);
}
return history;
} catch (IOException e) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\"", e);
}
}
/**
* Process the output from the log command and insert the HistoryEntries
* into the history field.
*
* @param input The output from the process
* @throws java.io.IOException If an error occurs while reading the stream
*/
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Parse the given string.
*
* @param buffer The string to be parsed
* @return The parsed history
* @throws IOException if we fail to parse the buffer
*/
History parse(String buffer) throws IOException {
processStream(new ByteArrayInputStream(buffer.getBytes(StandardCharsets.UTF_8)));
return history;
}
}
|
BufferedReader in = new BufferedReader(new InputStreamReader(input));
List<HistoryEntry> entries = new ArrayList<>();
String s;
HistoryEntry entry = null;
while ((s = in.readLine()) != null) {
if (!"create version".equals(s) && !"create directory version".equals(s)) {
// skip this history entry
while ((s = in.readLine()) != null) {
if (".".equals(s)) {
break;
}
}
continue;
}
entry = new HistoryEntry();
if ((s = in.readLine()) != null) {
try {
entry.setDate(repository.parse(s));
} catch (ParseException pe) {
//
// Overriding processStream() thus need to comply with the
// set of exceptions it can throw.
//
throw new IOException("Could not parse date: " + s, pe);
}
}
if ((s = in.readLine()) != null) {
entry.setAuthor(s);
}
if ((s = in.readLine()) != null) {
s = s.replace('\\', '/');
entry.setRevision(s);
}
StringBuilder message = new StringBuilder();
String glue = "";
while ((s = in.readLine()) != null && !".".equals(s)) {
if (s.isEmpty()) {
// avoid empty lines in comments
continue;
}
message.append(glue);
message.append(s.trim());
glue = "\n";
}
entry.setMessage(message.toString());
entry.setActive(true);
entries.add(entry);
}
history = new History();
history.setHistoryEntries(entries);
| 387
| 458
| 845
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/DirectoryHistoryReader.java
|
DirectoryHistoryReader
|
readFromHistory
|
class DirectoryHistoryReader {
private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryHistoryReader.class);
// This is a giant hash constructed in this class.
// It maps date -> author -> (comment, revision, displayRevision) -> [ list of files ]
private final Map<Date, Map<String, Map<List<String>, SortedSet<String>>>> hash
= new LinkedHashMap<>(); // set in put()
Iterator<Date> diter;
Date idate;
Iterator<String> aiter;
String iauthor;
Iterator<List<String>> citer;
List<String> icomment;
HistoryEntry currentEntry; // set in next()
History history; // set in the constructor
private static final int MAX_RESULTS = 40;
/**
* The main task of this method is to produce list of history entries for
* the specified directory and store them in @code history. This is done by
* searching the index to get recently changed files under in the directory
* tree under @code path and storing their histories in giant @code hash.
*
* @param path directory to generate history for
* @throws IOException when index cannot be accessed
*/
public DirectoryHistoryReader(String path) throws IOException {
SuperIndexSearcher searcher = null;
try {
// Prepare for index search.
String srcRoot = RuntimeEnvironment.getInstance().getSourceRootPath();
// The search results will be sorted by date.
searcher = RuntimeEnvironment.getInstance().getSuperIndexSearcher(new File(srcRoot, path));
SortField sfield = new SortField(QueryBuilder.DATE, SortField.Type.STRING, true);
Sort sort = new Sort(sfield);
QueryParser qparser = new QueryParser(QueryBuilder.PATH, new CompatibleAnalyser());
Query query;
ScoreDoc[] hits = null;
try {
// Get files under given directory by searching the index.
query = qparser.parse(path);
TopFieldDocs fdocs = searcher.search(query, MAX_RESULTS, sort);
hits = fdocs.scoreDocs;
} catch (ParseException e) {
LOGGER.log(Level.WARNING,
"An error occurred while parsing search query", e);
}
if (hits != null) {
// Get maximum MAX_RESULTS (why ? XXX) files which were changed recently.
StoredFields storedFields = searcher.storedFields();
for (int i = 0; i < MAX_RESULTS && i < hits.length; i++) {
int docId = hits[i].doc;
Document doc = storedFields.document(docId);
String rpath = doc.get(QueryBuilder.PATH);
if (!rpath.startsWith(path)) {
continue;
}
Date cdate;
try {
cdate = DateTools.stringToDate(doc.get(QueryBuilder.DATE));
} catch (java.text.ParseException ex) {
LOGGER.log(Level.WARNING, String.format("Could not get date for '%s'", path), ex);
cdate = new Date();
}
int ls = rpath.lastIndexOf('/');
if (ls != -1) {
String rparent = rpath.substring(0, ls);
String rbase = rpath.substring(ls + 1);
History hist = null;
File f = new File(srcRoot + rparent, rbase);
try {
hist = HistoryGuru.getInstance().getHistory(f);
} catch (HistoryException e) {
LOGGER.log(Level.WARNING,
String.format("An error occurred while getting history reader for '%s'", f), e);
}
if (hist == null) {
put(cdate, "", null, "-", "", rpath);
} else {
// Put all history entries for this file into the giant hash.
readFromHistory(hist, rpath);
}
}
}
}
// Now go through the giant hash and produce history entries from it.
ArrayList<HistoryEntry> entries = new ArrayList<>();
while (next()) {
entries.add(currentEntry);
}
// This is why we are here. Store all the constructed history entries
// into history object.
history = new History(entries);
} finally {
if (searcher != null) {
try {
searcher.release();
} catch (Exception ex) {
LOGGER.log(Level.WARNING,
String.format("An error occurred while closing index reader for '%s'", path), ex);
}
}
}
}
public History getHistory() {
return history;
}
// Fill the giant hash with some data from one history entry.
private void put(Date date, String revision, String displayRevision, String author, String comment, String path) {
long time = date.getTime();
date.setTime(time - time % 3600000L);
Map<String, Map<List<String>, SortedSet<String>>> ac = hash.computeIfAbsent(date, k -> new HashMap<>());
Map<List<String>, SortedSet<String>> cf = ac.computeIfAbsent(author, k -> new HashMap<>());
// We are not going to modify the list so this is safe to do.
List<String> cr = new ArrayList<>();
cr.add(comment);
cr.add(revision);
cr.add(displayRevision);
SortedSet<String> fls = cf.computeIfAbsent(cr, k -> new TreeSet<>());
fls.add(path);
}
/**
* Do one traversal step of the giant hash and produce history entry object
* and store it into @code currentEntry.
*
* @return true if history entry was successfully generated otherwise false
*/
private boolean next() {
if (diter == null) {
diter = hash.keySet().iterator();
}
if (citer == null || !citer.hasNext()) {
if (aiter == null || !aiter.hasNext()) {
if (diter.hasNext()) {
idate = diter.next();
aiter = hash.get(idate).keySet().iterator();
} else {
return false;
}
}
iauthor = aiter.next();
citer = hash.get(idate).get(iauthor).keySet().iterator();
}
icomment = citer.next();
currentEntry = new HistoryEntry(icomment.get(1), icomment.get(2), idate, iauthor, icomment.get(0), true,
hash.get(idate).get(iauthor).get(icomment));
return true;
}
/**
* Go through all history entries in @code hist for file @code path and
* store them in the giant hash.
*
* @param hist history to store
* @param rpath path of the file corresponding to the history
*/
private void readFromHistory(History hist, String rpath) {<FILL_FUNCTION_BODY>}
}
|
for (HistoryEntry entry : hist.getHistoryEntries()) {
if (entry.isActive()) {
String comment = entry.getMessage();
String cauthor = entry.getAuthor();
Date cdate = entry.getDate();
String revision = entry.getRevision();
String displayRevision = entry.getDisplayRevision();
put(cdate, revision, displayRevision, cauthor, comment, rpath);
break;
}
}
| 1,822
| 116
| 1,938
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/FileAnnotationCache.java
|
FileAnnotationCache
|
readAnnotation
|
class FileAnnotationCache extends AbstractCache implements AnnotationCache {
private static final Logger LOGGER = LoggerFactory.getLogger(FileAnnotationCache.class);
private Counter fileAnnotationCacheHits;
private Counter fileAnnotationCacheMisses;
private static final String ANNOTATION_CACHE_DIR_NAME = "annotationcache";
public void initialize() {
MeterRegistry meterRegistry = Metrics.getRegistry();
if (meterRegistry != null) {
fileAnnotationCacheHits = Counter.builder("cache.annotation.file.get").
description("file annotation cache hits").
tag("what", "hits").
register(meterRegistry);
fileAnnotationCacheMisses = Counter.builder("cache.annotation.file.get").
description("file annotation cache misses").
tag("what", "miss").
register(meterRegistry);
}
}
/**
* Read serialized {@link AnnotationData} from a file and create {@link Annotation} instance out of it.
*/
static Annotation readCache(File file) throws IOException {
ObjectMapper mapper = new SmileMapper();
return new Annotation(mapper.readValue(file, AnnotationData.class));
}
/**
* Retrieve revision from the cache for given file. This is done in a fashion that keeps I/O low.
* Assumes that {@link AnnotationData#revision} is serialized in the cache file as the first member.
* @param file source root file
* @return revision from the cache file or {@code null}
* @throws CacheException on error
*/
@Nullable
String getRevision(File file) throws CacheException {
File cacheFile;
try {
cacheFile = getCachedFile(file);
} catch (CacheException e) {
throw new CacheException("failed to get annotation cache file", e);
}
SmileFactory factory = new SmileFactory();
try (SmileParser parser = factory.createParser(cacheFile)) {
parser.nextToken();
while (parser.getCurrentToken() != null) {
if (parser.getCurrentToken().equals(JsonToken.FIELD_NAME)) {
break;
}
parser.nextToken();
}
if (parser.getCurrentName().equals("revision")) {
parser.nextToken();
if (!parser.getCurrentToken().equals(JsonToken.VALUE_STRING)) {
LOGGER.log(Level.WARNING, "the value of the ''revision'' field in ''{0}'' is not string",
cacheFile);
return null;
}
return parser.getValueAsString();
} else {
LOGGER.log(Level.WARNING, "the first serialized field is not ''revision'' in ''{0}''", cacheFile);
return null;
}
} catch (IOException e) {
throw new CacheException(e);
}
}
@Override
public String getCacheFileSuffix() {
return "";
}
@VisibleForTesting
Annotation readAnnotation(File file) throws CacheException {<FILL_FUNCTION_BODY>}
/**
* This is potentially expensive operation as the cache entry has to be retrieved from disk
* in order to tell whether it is stale or not.
* @param file source file
* @return indication whether the cache entry is fresh
*/
public boolean isUpToDate(File file) {
try {
return get(file, null) != null;
} catch (CacheException e) {
return false;
}
}
public Annotation get(File file, @Nullable String rev) throws CacheException {
Annotation annotation = null;
String latestRevision = LatestRevisionUtil.getLatestRevision(file);
if (rev == null || (latestRevision != null && latestRevision.equals(rev))) {
/*
* Double check that the cached annotation is not stale by comparing the stored revision
* with revision to be fetched.
* This should be more robust than the file time stamp based check performed by history cache,
* at the expense of having to read some content from the annotation cache.
*/
final String storedRevision = getRevision(file);
/*
* Even though store() does not allow to store annotation with null revision, the check
* should be present to catch weird cases of someone not using the store() or general badness.
*/
if (storedRevision == null) {
LOGGER.finer(() -> String.format("no stored revision in annotation cache for '%s'",
launderLog(file.toString())));
} else if (!storedRevision.equals(latestRevision)) {
LOGGER.finer(() -> String.format("stored revision %s for '%s' does not match latest revision %s",
storedRevision, launderLog(file.toString()), rev));
} else {
// read from the cache
annotation = readAnnotation(file);
}
}
if (annotation != null) {
if (fileAnnotationCacheHits != null) {
fileAnnotationCacheHits.increment();
}
} else {
if (fileAnnotationCacheMisses != null) {
fileAnnotationCacheMisses.increment();
}
LOGGER.finest(() -> String.format("annotation cache miss for '%s' in revision %s",
launderLog(file.toString()), rev));
return null;
}
return annotation;
}
private void writeCache(AnnotationData annotationData, File outfile) throws IOException {
ObjectMapper mapper = new SmileMapper();
mapper.writeValue(outfile, annotationData);
}
@SuppressWarnings("java:S1764")
public void store(File file, Annotation annotation) throws CacheException {
if (annotation.getRevision() == null || annotation.getRevision().isEmpty()) {
throw new CacheException(String.format("annotation for ''%s'' does not contain revision", file));
}
File cacheFile;
try {
cacheFile = getCachedFile(file);
} catch (CacheException e) {
LOGGER.log(Level.FINER, e.getMessage());
return;
}
File dir = cacheFile.getParentFile();
// calling isDirectory() twice to prevent a race condition
if (!dir.isDirectory() && !dir.mkdirs() && !dir.isDirectory()) {
throw new CacheException("Unable to create cache directory '" + dir + "'.");
}
Statistics statistics = new Statistics();
try {
writeCache(annotation.annotationData, cacheFile);
statistics.report(LOGGER, Level.FINEST, String.format("wrote annotation for '%s'", file),
"cache.annotation.file.store.latency");
} catch (IOException e) {
LOGGER.log(Level.WARNING, "failed to write annotation to cache", e);
}
}
public void clear(RepositoryInfo repository) {
CacheUtil.clearCacheDir(repository, this);
}
@Override
public void optimize() {
// nothing to do
}
@Override
public boolean supportsRepository(Repository repository) {
// all repositories are supported
return true;
}
@Override
public String getCacheDirName() {
return ANNOTATION_CACHE_DIR_NAME;
}
@Override
public String getInfo() {
return getClass().getSimpleName();
}
}
|
File cacheFile;
try {
cacheFile = getCachedFile(file);
} catch (CacheException e) {
LOGGER.log(Level.WARNING, "failed to get annotation cache file", e);
return null;
}
try {
Statistics statistics = new Statistics();
Annotation annotation = readCache(cacheFile);
statistics.report(LOGGER, Level.FINEST, String.format("deserialized annotation from cache for '%s'", file));
return annotation;
} catch (IOException e) {
throw new CacheException(String.format("failed to read annotation cache for '%s'", file), e);
}
| 1,876
| 165
| 2,041
|
<methods>public non-sealed void <init>() ,public List<java.lang.String> clearCache(Collection<org.opengrok.indexer.history.RepositoryInfo>) ,public void clearFile(java.lang.String) ,public java.lang.String getCacheFileSuffix() ,public boolean hasCacheForFile(java.io.File) throws org.opengrok.indexer.history.CacheException<variables>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/FileCollector.java
|
FileCollector
|
accept
|
class FileCollector extends ChangesetVisitor {
private final Set<String> files;
public FileCollector(boolean consumeMergeChangesets) {
super(consumeMergeChangesets);
files = new HashSet<>();
}
public void accept(RepositoryWithHistoryTraversal.ChangesetInfo changesetInfo) {<FILL_FUNCTION_BODY>}
/**
* @return set of file paths relative to source root. There are no guarantees w.r.t. ordering.
*/
public Set<String> getFiles() {
return files;
}
void addFiles(Collection<String> files) {
this.files.addAll(files);
}
@VisibleForTesting
public void reset() {
files.clear();
}
}
|
if (changesetInfo.renamedFiles != null) {
files.addAll(changesetInfo.renamedFiles);
}
if (changesetInfo.files != null) {
files.addAll(changesetInfo.files);
}
if (changesetInfo.deletedFiles != null) {
files.addAll(changesetInfo.deletedFiles);
}
| 204
| 101
| 305
|
<methods><variables>boolean consumeMergeChangesets
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/GitTagEntry.java
|
GitTagEntry
|
compareTo
|
class GitTagEntry extends TagEntry {
private final String hash;
GitTagEntry(String hash, Date date, String tags) {
super(date, tags);
this.hash = hash;
}
/**
* Gets the immutable, initialized Git hash value.
*/
String getHash() {
return hash;
}
@Override
public int compareTo(HistoryEntry that) {<FILL_FUNCTION_BODY>}
}
|
assert this.date != null : "Git TagEntry created without date specified";
return this.date.compareTo(that.getDate());
| 119
| 38
| 157
|
<methods>public int compareTo(org.opengrok.indexer.history.TagEntry) ,public abstract int compareTo(org.opengrok.indexer.history.HistoryEntry) ,public boolean equals(java.lang.Object) ,public java.util.Date getDate() ,public java.lang.String getTags() ,public int hashCode() ,public void setTags(java.lang.String) <variables>private static final java.lang.String DATE_NULL_ASSERT,protected static final int NOREV,protected final non-sealed java.util.Date date,protected final non-sealed int revision,protected java.lang.String tags
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/History.java
|
History
|
getHistoryEntries
|
class History implements Serializable {
private static final long serialVersionUID = -1;
static final String TAGS_SEPARATOR = ", ";
/** Entries in the log. The first entry is the most recent one. */
private List<HistoryEntry> entries;
/**
* Track renamed files, so they can be treated in special way (for some SCMs) during cache creation.
* These are relative to repository root.
*/
private final Set<String> renamedFiles;
/**
* Revision of the newest change. Used in history cache.
*/
private String latestRev;
// revision to tag list. Individual tags are joined via TAGS_SEPARATOR.
private Map<String, String> tags = new HashMap<>();
public History() {
this(new ArrayList<>());
}
public History(List<HistoryEntry> entries) {
this(entries, Collections.emptyList());
}
History(List<HistoryEntry> entries, List<String> renamed) {
this.entries = entries;
this.renamedFiles = new HashSet<>(renamed);
}
History(List<HistoryEntry> entries, Set<String> renamed) {
this.entries = entries;
this.renamedFiles = renamed;
}
History(List<HistoryEntry> entries, Set<String> renamed, String latestRev) {
this(entries, renamed);
this.latestRev = latestRev;
}
public String getLatestRev() {
return latestRev;
}
// Needed for serialization.
public Map<String, String> getTags() {
return tags;
}
// Needed for serialization.
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public void setEntries(List<HistoryEntry> entries) {
this.entries = entries;
}
/**
* Set the list of log entries for the file. The first entry is the most
* recent one.
*
* @param entries The entries to add to the list
*/
public void setHistoryEntries(List<HistoryEntry> entries) {
this.setEntries(entries);
}
/**
* Get the list of log entries, most recent first.
*
* @return The list of entries in this history
*/
public List<HistoryEntry> getHistoryEntries() {
return entries;
}
/**
* Get the list of log entries, most recent first.
* With parameters
* @param limit max number of entries
* @param offset starting position
*
* @return The list of entries in this history
*/
public List<HistoryEntry> getHistoryEntries(int limit, int offset) {<FILL_FUNCTION_BODY>}
/**
* Check if at least one history entry has a file list.
*
* @return {@code true} if at least one of the entries has a non-empty
* file list, {@code false} otherwise
*/
public boolean hasFileList() {
return entries.stream()
.map(HistoryEntry::getFiles)
.anyMatch(files -> !files.isEmpty());
}
/**
* Check if at least one history entry has a tag list.
*
* @return {@code true} if at least one of the entries has a non-empty
* tag list, {@code false} otherwise
*/
public boolean hasTags() {
return !tags.isEmpty();
}
public void addTags(HistoryEntry entry, String newTags) {
tags.merge(entry.getRevision(), newTags, (a, b) -> a + TAGS_SEPARATOR + b);
}
/**
* Gets a value indicating if {@code file} is in the list of renamed files.
* @param file file path
* @return is file renamed
*/
public boolean isRenamed(String file) {
return renamedFiles.contains(file);
}
public Set<String> getRenamedFiles() {
return renamedFiles;
}
/**
* @return list of revisions
*/
public List<String> getRevisionList() {
return getHistoryEntries().stream().
map(HistoryEntry::getRevision).collect(Collectors.toList());
}
/**
* Strip files and tags.
* @see HistoryEntry#strip()
*/
public void strip() {
for (HistoryEntry ent : this.getHistoryEntries()) {
ent.strip();
}
tags.clear();
}
/**
* @return last (newest) history entry or null
*/
public @Nullable HistoryEntry getLastHistoryEntry() {
List<HistoryEntry> historyEntries = getHistoryEntries();
if (historyEntries == null || historyEntries.isEmpty()) {
return null;
}
return historyEntries.get(0);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
History that = (History) o;
return Objects.equals(this.getHistoryEntries(), that.getHistoryEntries()) &&
Objects.equals(this.getTags(), that.getTags()) &&
Objects.equals(this.getRenamedFiles(), that.getRenamedFiles());
}
@Override
public int hashCode() {
return Objects.hash(getHistoryEntries(), getTags(), getRenamedFiles());
}
@Override
public String toString() {
return this.getHistoryEntries().toString() + ", renamed files: " + this.getRenamedFiles().toString() +
" , tags: " + getTags();
}
}
|
offset = Math.max(offset, 0);
limit = offset + limit > entries.size() ? entries.size() - offset : limit;
return entries.subList(offset, offset + limit);
| 1,502
| 52
| 1,554
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/HistoryClassLoader.java
|
HistoryClassLoader
|
loadClass
|
class HistoryClassLoader extends ClassLoader {
private static final Set<String> allowedClasses = Set.of(
ArrayList.class,
Collections.class,
Date.class,
HashMap.class,
History.class,
HistoryEntry.class,
RepositoryInfo.class,
String.class,
TreeSet.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 History object");
}
return getClass().getClassLoader().loadClass(name);
| 150
| 55
| 205
|
<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/opengrok-indexer/src/main/java/org/opengrok/indexer/history/HistoryCollector.java
|
HistoryCollector
|
accept
|
class HistoryCollector extends ChangesetVisitor {
List<HistoryEntry> entries;
Set<String> renamedFiles;
String latestRev;
HistoryCollector(boolean consumeMergeChangesets) {
super(consumeMergeChangesets);
entries = new ArrayList<>();
renamedFiles = new HashSet<>();
}
@Override
public void accept(RepositoryWithHistoryTraversal.ChangesetInfo changesetInfo) {<FILL_FUNCTION_BODY>}
}
|
RepositoryWithHistoryTraversal.CommitInfo commit = changesetInfo.commit;
// Make sure to record the revision even though this is a merge changeset
// and the collector does not want to consume these.
// The changesets are visited from newest to oldest, so record just the first one.
if (latestRev == null) {
latestRev = commit.revision;
}
if (changesetInfo.isMerge != null && changesetInfo.isMerge && !consumeMergeChangesets) {
return;
}
// TODO: add a test for this
String author;
if (commit.authorEmail != null) {
author = commit.authorName + " <" + commit.authorEmail + ">";
} else {
author = commit.authorName;
}
HistoryEntry historyEntry = new HistoryEntry(
commit.revision, commit.displayRevision,
commit.date, author,
commit.message, true, changesetInfo.files);
if (changesetInfo.renamedFiles != null) {
renamedFiles.addAll(changesetInfo.renamedFiles);
// TODO: hack
historyEntry.getFiles().addAll(changesetInfo.renamedFiles);
}
entries.add(historyEntry);
| 129
| 325
| 454
|
<methods><variables>boolean consumeMergeChangesets
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/HistoryEntry.java
|
HistoryEntry
|
dump
|
class HistoryEntry implements Serializable {
private static final long serialVersionUID = 1277313126047397131L;
private static final Logger LOGGER = LoggerFactory.getLogger(HistoryEntry.class);
private String revision;
private String displayRevision;
private Date date;
private String author;
@SuppressWarnings("PMD.AvoidStringBufferField")
private final StringBuffer message;
private boolean active;
@JsonIgnore
private SortedSet<String> files;
/** Creates a new instance of HistoryEntry. */
public HistoryEntry() {
message = new StringBuffer();
files = new TreeSet<>();
}
/**
* Copy constructor.
* @param that HistoryEntry object
*/
public HistoryEntry(HistoryEntry that) {
this(that.revision, that.displayRevision, that.date, that.author, that.message.toString(), that.active, that.files);
}
public HistoryEntry(String revision, String displayRevision, Date date, String author, String message, boolean active, Collection<String> files) {
this.revision = revision;
this.displayRevision = displayRevision;
setDate(date);
this.author = author;
this.message = new StringBuffer(message);
this.active = active;
this.files = new TreeSet<>();
if (files != null) {
this.files.addAll(files);
}
}
public HistoryEntry(String revision, Date date, String author, String message, boolean active) {
this(revision, null, date, author, message, active, null);
}
@VisibleForTesting
HistoryEntry(String revision) {
this();
this.revision = revision;
}
@JsonIgnore
public String getLine() {
return String.join(" ",
getRevision(), getDate().toString(), getAuthor(), message, "\n");
}
public void dump() {<FILL_FUNCTION_BODY>}
/**
* @return description of selected fields; used in the web app.
*/
@JsonIgnore
public String getDescription() {
return "changeset: " + getRevision()
+ "\nsummary: " + getMessage() + "\nuser: "
+ getAuthor() + "\ndate: " + getDate();
}
public String getAuthor() {
return author;
}
public Date getDate() {
return date == null ? null : (Date) date.clone();
}
public String getMessage() {
return message.toString().trim();
}
public String getRevision() {
return revision;
}
public String getDisplayRevision() {
return displayRevision == null ? revision : displayRevision;
}
public void setAuthor(String author) {
this.author = author;
}
public final void setDate(Date date) {
if (date == null) {
this.date = null;
} else {
this.date = (Date) date.clone();
}
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public void setMessage(String message) {
this.message.setLength(0);
this.message.append(message);
}
public void setRevision(String revision) {
this.revision = revision;
}
public void setDisplayRevision(String displayRevision) {
this.displayRevision = displayRevision;
}
public void appendMessage(String message) {
this.message.append(message);
this.message.append("\n");
}
public void addFile(String file) {
files.add(file);
}
public SortedSet<String> getFiles() {
return files;
}
public void setFiles(SortedSet<String> files) {
this.files = files;
}
/**
* @deprecated The method is kept only for backward compatibility to avoid warnings when deserializing objects
* from the previous format.
* The tags were moved to the {@link History} class.
* Will be removed sometime after the OpenGrok 1.8.0 version.
*/
@Deprecated(since = "1.7.11", forRemoval = true)
public void setTags(String tags) {
// Tags moved to the History object.
}
@Override
public String toString() {
return String.join(" ",
getRevision(), getDisplayRevision(), getDate().toString(), getAuthor(), getMessage(), getFiles().toString());
}
/**
* Remove list of files and tags.
*/
public void strip() {
stripFiles();
}
/**
* Remove list of files.
*/
public void stripFiles() {
files.clear();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HistoryEntry that = (HistoryEntry) o;
return Objects.equals(this.getAuthor(), that.getAuthor()) &&
Objects.equals(this.getRevision(), that.getRevision()) &&
Objects.equals(this.getDisplayRevision(), that.getDisplayRevision()) &&
Objects.equals(this.getDate(), that.getDate()) &&
Objects.equals(this.getMessage(), that.getMessage()) &&
Objects.equals(this.getFiles(), that.getFiles());
}
@Override
public int hashCode() {
return Objects.hash(getAuthor(), getRevision(), getDisplayRevision(), getDate(), getMessage(), getFiles());
}
}
|
LOGGER.log(Level.FINE, "HistoryEntry : revision = {0}", revision);
LOGGER.log(Level.FINE, "HistoryEntry : displayRevision = {0}", displayRevision);
LOGGER.log(Level.FINE, "HistoryEntry : date = {0}", date);
LOGGER.log(Level.FINE, "HistoryEntry : author = {0}", author);
LOGGER.log(Level.FINE, "HistoryEntry : active = {0}", active ?
"True" : "False");
String[] lines = message.toString().split("\n");
String separator = "=";
for (String line : lines) {
LOGGER.log(Level.FINE, "HistoryEntry : message {0} {1}",
new Object[]{separator, line});
separator = ">";
}
separator = "=";
for (String file : files) {
LOGGER.log(Level.FINE, "HistoryEntry : files {0} {1}",
new Object[]{separator, file});
separator = ">";
}
| 1,509
| 284
| 1,793
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/HistoryReader.java
|
HistoryReader
|
createInternalReader
|
class HistoryReader extends Reader {
private final List<HistoryEntry> entries;
private Reader input;
public HistoryReader(History history) {
entries = history.getHistoryEntries();
}
@Override
public int read(char @NotNull [] cbuf, int off, int len) throws IOException {
if (input == null) {
input = createInternalReader();
}
return input.read(Objects.requireNonNull(cbuf, "cbuf"), off, len);
}
@Override
public void close() throws IOException {
IOUtils.close(input);
}
private Reader createInternalReader() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder str = new StringBuilder();
for (HistoryEntry entry : entries) {
str.append(entry.getLine());
}
return new StringReader(str.toString());
| 174
| 49
| 223
|
<methods>public abstract void close() throws java.io.IOException,public void mark(int) throws java.io.IOException,public boolean markSupported() ,public static java.io.Reader nullReader() ,public int read() throws java.io.IOException,public int read(java.nio.CharBuffer) throws java.io.IOException,public int read(char[]) throws java.io.IOException,public abstract int read(char[], int, int) throws java.io.IOException,public boolean ready() throws java.io.IOException,public void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public long transferTo(java.io.Writer) throws java.io.IOException<variables>private static final int TRANSFER_BUFFER_SIZE,protected java.lang.Object lock,private static final int maxSkipBufferSize,private char[] skipBuffer
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/MercurialAnnotationParser.java
|
MercurialAnnotationParser
|
processStream
|
class MercurialAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MercurialAnnotationParser.class);
private Annotation annotation = null;
private final HashMap<String, HistoryEntry> revs;
private final File file;
/**
* Pattern used to extract author/revision from the {@code hg annotate} command.
*/
private static final Pattern ANNOTATION_PATTERN = Pattern.compile("^\\s*(\\d+):");
MercurialAnnotationParser(File file, HashMap<String, HistoryEntry> revs) {
this.file = file;
this.revs = revs;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
Annotation getAnnotation() {
return this.annotation;
}
}
|
annotation = new Annotation(file.getName());
String line;
int lineno = 0;
Matcher matcher = ANNOTATION_PATTERN.matcher("");
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
while ((line = in.readLine()) != null) {
++lineno;
matcher.reset(line);
if (matcher.find()) {
String rev = matcher.group(1);
String author = "N/A";
// Use the history index hash map to get the author.
if (revs.get(rev) != null) {
author = revs.get(rev).getAuthor();
}
annotation.addLine(rev, Util.getEmail(author.trim()), true);
} else {
LOGGER.log(Level.WARNING,
"Error: did not find annotation in line {0} for ''{1}'': [{2}]",
new Object[]{lineno, this.file, line});
}
}
}
| 228
| 265
| 493
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/MercurialHistoryParserRevisionsOnly.java
|
MercurialHistoryParserRevisionsOnly
|
parse
|
class MercurialHistoryParserRevisionsOnly implements Executor.StreamHandler {
private final MercurialRepository repository;
private final Consumer<BoundaryChangesets.IdWithProgress> visitor;
private final Progress progress;
MercurialHistoryParserRevisionsOnly(MercurialRepository repository,
Consumer<BoundaryChangesets.IdWithProgress> visitor, Progress progress) {
this.repository = repository;
this.visitor = visitor;
this.progress = progress;
}
void parse(File file, String sinceRevision) throws HistoryException {<FILL_FUNCTION_BODY>}
@Override
public void processStream(InputStream input) throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
String s;
while ((s = in.readLine()) != null) {
visitor.accept(new BoundaryChangesets.IdWithProgress(s, progress));
}
}
}
}
|
try {
Executor executor = repository.getHistoryLogExecutor(file, sinceRevision, null, true);
int status = executor.exec(true, this);
if (status != 0) {
throw new HistoryException(
String.format("Failed to get revisions for: \"%s\" since revision %s Exit code: %d",
file.getAbsolutePath(), sinceRevision, status));
}
} catch (IOException e) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\"", e);
}
| 245
| 152
| 397
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/MercurialTagEntry.java
|
MercurialTagEntry
|
compareTo
|
class MercurialTagEntry extends TagEntry {
public MercurialTagEntry(int revision, String tag) {
super(revision, tag);
}
@Override
public int compareTo(HistoryEntry that) {<FILL_FUNCTION_BODY>}
}
|
assert this.revision != NOREV : "Mercurial TagEntry created without revision specified";
String[] revs = that.getRevision().split(":");
assert revs.length == 2 : "Unable to parse revision format";
return Integer.compare(this.revision, Integer.parseInt(revs[0]));
| 71
| 85
| 156
|
<methods>public int compareTo(org.opengrok.indexer.history.TagEntry) ,public abstract int compareTo(org.opengrok.indexer.history.HistoryEntry) ,public boolean equals(java.lang.Object) ,public java.util.Date getDate() ,public java.lang.String getTags() ,public int hashCode() ,public void setTags(java.lang.String) <variables>private static final java.lang.String DATE_NULL_ASSERT,protected static final int NOREV,protected final non-sealed java.util.Date date,protected final non-sealed int revision,protected java.lang.String tags
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/MercurialTagParser.java
|
MercurialTagParser
|
processStream
|
class MercurialTagParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MercurialTagParser.class);
/**
* Store tag entries created by processStream.
*/
private TreeSet<TagEntry> entries = new TreeSet<>();
/**
* Returns the set of entries that has been created.
*
* @return entries a set of tag entries
*/
public TreeSet<TagEntry> getEntries() {
return entries;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try {
try (BufferedReader in = new BufferedReader(
new InputStreamReader(input))) {
String line;
while ((line = in.readLine()) != null) {
String[] parts = line.split(" *");
if (parts.length < 2) {
LOGGER.log(Level.WARNING,
"Failed to parse tag list: {0}",
"Tag line contains more than 2 columns: " + line);
entries = null;
break;
}
// Grrr, how to parse tags with spaces inside?
// This solution will lose multiple spaces ;-/
String tag = parts[0];
for (int i = 1; i < parts.length - 1; ++i) {
tag = tag.concat(" ");
tag = tag.concat(parts[i]);
}
// The implicit 'tip' tag only causes confusion so ignore it.
if (tag.contentEquals("tip")) {
continue;
}
String[] revParts = parts[parts.length - 1].split(":");
if (revParts.length != 2) {
LOGGER.log(Level.WARNING,
"Failed to parse tag list: {0}",
"Mercurial revision parsing error: "
+ parts[parts.length - 1]);
entries = null;
break;
}
TagEntry tagEntry
= new MercurialTagEntry(Integer.parseInt(revParts[0]),
tag);
// Reverse the order of the list
entries.add(tagEntry);
}
}
} catch (IOException e) {
LOGGER.log(Level.WARNING,
"Failed to read tag list: {0}", e.getMessage());
entries = null;
}
| 161
| 446
| 607
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/MonotoneAnnotationParser.java
|
MonotoneAnnotationParser
|
processStream
|
class MonotoneAnnotationParser implements Executor.StreamHandler {
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
/**
* Pattern used to extract author/revision from the {@code mnt annotate} command.
*/
private static final Pattern ANNOTATION_PATTERN
= Pattern.compile("^(\\w+)\\p{Punct}\\p{Punct} by (\\S+)");
/**
* @param file the file being annotated
*/
public MonotoneAnnotationParser(File file) {
annotation = new Annotation(file.getName());
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
String line;
String author = null;
String rev = null;
while ((line = in.readLine()) != null) {
Matcher matcher = ANNOTATION_PATTERN.matcher(line);
if (matcher.find()) {
rev = matcher.group(1);
author = matcher.group(2);
annotation.addLine(rev, author, true);
} else {
annotation.addLine(rev, author, true);
}
}
}
| 239
| 153
| 392
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/MonotoneHistoryParser.java
|
MonotoneHistoryParser
|
parse
|
class MonotoneHistoryParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MonotoneHistoryParser.class);
private final List<HistoryEntry> entries = new ArrayList<>(); //NOPMD
private final MonotoneRepository repository;
private final String mydir;
MonotoneHistoryParser(MonotoneRepository repository) {
this.repository = repository;
mydir = repository.getDirectoryName() + File.separator;
}
/**
* Parse the history for the specified file or directory. If a changeset is
* specified, only return the history from the changeset right after the
* specified one.
*
* @param file the file or directory to get history for
* @param changeset the changeset right before the first one to fetch, or
* {@code null} if all changesets should be fetched
* @return history for the specified file or directory
* @throws HistoryException if an error happens when parsing the history
*/
History parse(File file, String changeset) throws HistoryException {<FILL_FUNCTION_BODY>}
/**
* Process the output from the hg log command and insert the HistoryEntries
* into the history field.
*
* @param input The output from the process
* @throws java.io.IOException If an error occurs while reading the stream
*/
@Override
public void processStream(InputStream input) throws IOException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
String s;
HistoryEntry entry = null;
int state = 0;
while ((s = in.readLine()) != null) {
s = s.trim();
// Later versions of monotone (such as 1.0) output even more dashes so lets require
// the minimum amount for maximum compatibility between monotone versions.
if (s.startsWith("-----------------------------------------------------------------")) {
if (entry != null && state > 2) {
entries.add(entry);
}
entry = new HistoryEntry();
entry.setActive(true);
state = 0;
continue;
}
switch (state) {
case 0:
if (s.startsWith("Revision:")) {
String rev = s.substring("Revision:".length()).trim();
entry.setRevision(rev);
++state;
}
break;
case 1:
if (s.startsWith("Author:")) {
entry.setAuthor(s.substring("Author:".length()).trim());
++state;
}
break;
case 2:
if (s.startsWith("Date:")) {
Date date = new Date();
try {
date = repository.parse(s.substring("date:".length()).trim());
} catch (ParseException pe) {
//
// Overriding processStream() thus need to comply with the
// set of exceptions it can throw.
//
throw new IOException("Could not parse date: " + s, pe);
}
entry.setDate(date);
++state;
}
break;
case 3:
if (s.startsWith("Modified ") || s.startsWith("Added ") || s.startsWith("Deleted ")) {
++state;
} else if (s.equalsIgnoreCase("ChangeLog:")) {
state = 5;
}
break;
case 4:
if (s.startsWith("Modified ") || s.startsWith("Added ") || s.startsWith("Deleted ")) {
continue;
} else if (s.equalsIgnoreCase("ChangeLog:")) {
state = 5;
} else {
String[] files = s.split(" ");
for (String f : files) {
File file = new File(mydir, f);
try {
String path = env.getPathRelativeToSourceRoot(
file);
entry.addFile(path.intern());
} catch (ForbiddenSymlinkException e) {
LOGGER.log(Level.FINER, e.getMessage());
// ignore
} catch (FileNotFoundException e) { // NOPMD
// If the file is not located under the source root, ignore it
} catch (InvalidPathException e) {
LOGGER.log(Level.WARNING, e.getMessage());
}
}
}
break;
case 5:
entry.appendMessage(s);
break;
default:
LOGGER.warning("Unknown parser state: " + state);
break;
}
}
if (entry != null && state > 2) {
entries.add(entry);
}
}
}
|
try {
Executor executor = repository.getHistoryLogExecutor(file, changeset);
int status = executor.exec(true, this);
if (status != 0) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\" Exit code: " + status);
}
} catch (IOException e) {
throw new HistoryException("Failed to get history for: \"" +
file.getAbsolutePath() + "\"", e);
}
return new History(entries);
| 1,195
| 144
| 1,339
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/MonotoneRepository.java
|
MonotoneRepository
|
getHistoryGet
|
class MonotoneRepository extends Repository {
private static final Logger LOGGER = LoggerFactory.getLogger(MonotoneRepository.class);
private static final long serialVersionUID = 1L;
/**
* The property name used to obtain the client command for this repository.
*/
public static final String CMD_PROPERTY_KEY = "org.opengrok.indexer.history.Monotone";
/**
* The command to use to access the repository if none was given explicitly.
*/
public static final String CMD_FALLBACK = "mnt";
public MonotoneRepository() {
type = "Monotone";
datePatterns = new String[]{
"yyyy-MM-dd'T'hh:mm:ss"
};
}
@Override
boolean getHistoryGet(OutputStream out, String parent, String basename, String rev) {<FILL_FUNCTION_BODY>}
/**
* Get an executor to be used for retrieving the history log for the named
* file or directory.
*
* @param file The file or directory to retrieve history for
* @param sinceRevision the oldest changeset to return from the executor, or
* {@code null} if all changesets should be returned
* @return An Executor ready to be started
*/
Executor getHistoryLogExecutor(File file, String sinceRevision)
throws IOException {
String filename = getRepoRelativePath(file);
List<String> cmd = new ArrayList<>();
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
cmd.add(RepoCommand);
cmd.add("log");
if (sinceRevision != null) {
cmd.add("--to");
cmd.add(sinceRevision);
}
cmd.add("--no-graph");
cmd.add("--no-merges");
cmd.add("--no-format-dates");
cmd.add(filename);
return new Executor(cmd, new File(getDirectoryName()), sinceRevision != null);
}
/**
* Annotate the specified file/revision using the {@code mnt annotate} command.
*
* @param file file to annotate
* @param revision revision to annotate
* @return file annotation
* @throws java.io.IOException if I/O exception occurred or the command failed
*/
@Override
public Annotation annotate(File file, String revision) throws IOException {
ArrayList<String> cmd = new ArrayList<>();
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
cmd.add(RepoCommand);
cmd.add("annotate");
cmd.add(getQuietOption());
if (revision != null) {
cmd.add("-r");
cmd.add(revision);
}
cmd.add(file.getName());
File directory = new File(getDirectoryName());
Executor executor = new Executor(cmd, directory,
RuntimeEnvironment.getInstance().getInteractiveCommandTimeout());
MonotoneAnnotationParser parser = new MonotoneAnnotationParser(file);
int status = executor.exec(true, parser);
if (status != 0) {
LOGGER.log(Level.WARNING,
"Failed to get annotations for: \"{0}\" Exit code: {1}",
new Object[]{file.getAbsolutePath(), String.valueOf(status)});
throw new IOException(executor.getErrorString());
} else {
return parser.getAnnotation();
}
}
@Override
public boolean fileHasAnnotation(File file) {
return true;
}
@Override
public boolean fileHasHistory(File file) {
return true;
}
@Override
boolean isRepositoryFor(File file, CommandTimeoutType cmdType) {
File f = new File(file, "_MTN");
return f.exists() && f.isDirectory();
}
@Override
public boolean isWorking() {
if (working == null) {
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
working = checkCmd(RepoCommand, "--help");
}
return working;
}
@Override
boolean hasHistoryForDirectories() {
return true;
}
@Override
History getHistory(File file) throws HistoryException {
return getHistory(file, null);
}
@Override
History getHistory(File file, String sinceRevision)
throws HistoryException {
return new MonotoneHistoryParser(this).parse(file, sinceRevision);
}
private String getQuietOption() {
if (useDeprecated()) {
return "--reallyquiet";
} else {
return "--quiet --quiet";
}
}
public static final String DEPRECATED_KEY
= "org.opengrok.indexer.history.monotone.deprecated";
private boolean useDeprecated() {
return Boolean.parseBoolean(System.getProperty(DEPRECATED_KEY, "false"));
}
@Override
String determineParent(CommandTimeoutType cmdType) throws IOException {
String parent = null;
File directory = new File(getDirectoryName());
List<String> cmd = new ArrayList<>();
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
cmd.add(RepoCommand);
cmd.add("ls");
cmd.add("vars");
cmd.add("database");
Executor executor = new Executor(cmd, directory,
RuntimeEnvironment.getInstance().getCommandTimeout(cmdType));
executor.exec();
try (BufferedReader in = new BufferedReader(executor.getOutputReader())) {
String line;
while ((line = in.readLine()) != null) {
if (line.startsWith("database") && line.contains("default-server")) {
String[] parts = line.split("\\s+");
if (parts.length != 3) {
LOGGER.log(Level.WARNING,
"Failed to get parent for {0}", getDirectoryName());
}
parent = parts[2];
break;
}
}
}
return parent;
}
@Override
String determineBranch(CommandTimeoutType cmdType) {
return null;
}
@Override
String determineCurrentVersion(CommandTimeoutType cmdType) throws IOException {
return null;
}
}
|
File directory = new File(getDirectoryName());
try {
String filename = (new File(parent, basename)).getCanonicalPath()
.substring(getDirectoryName().length() + 1);
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
String[] argv = {RepoCommand, "cat", "-r", rev, filename};
Executor executor = new Executor(Arrays.asList(argv), directory,
RuntimeEnvironment.getInstance().getInteractiveCommandTimeout());
copyBytes(out::write, executor.getOutputStream());
return true;
} catch (Exception exp) {
LOGGER.log(Level.SEVERE,
"Failed to get history: {0}", exp.getClass().toString());
}
return false;
| 1,647
| 202
| 1,849
|
<methods>public final java.lang.String determineBranch() throws java.io.IOException,public final java.lang.String determineCurrentVersion() throws java.io.IOException,public final java.lang.String determineParent() throws java.io.IOException,public static java.lang.String format(java.util.Date) ,public boolean getHistoryGet(java.io.File, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public java.io.InputStream getHistoryGet(java.lang.String, java.lang.String, java.lang.String) ,public List<java.lang.String> getIgnoredDirs() ,public List<java.lang.String> getIgnoredFiles() ,public org.opengrok.indexer.history.HistoryEntry getLastHistoryEntry(java.io.File, boolean) throws org.opengrok.indexer.history.HistoryException,public java.lang.String getRepoCommand() ,public final boolean isRepositoryFor(java.io.File) ,public java.util.Date parse(java.lang.String) throws java.text.ParseException<variables>private static final java.util.logging.Logger LOGGER,protected static final java.text.SimpleDateFormat OUTPUT_DATE_FORMAT,protected java.lang.String RepoCommand,protected final non-sealed List<java.lang.String> ignoredDirs,protected final non-sealed List<java.lang.String> ignoredFiles,private static final long serialVersionUID,protected NavigableSet<org.opengrok.indexer.history.TagEntry> tagList
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/PerforceAnnotationParser.java
|
PerforceAnnotationParser
|
processStream
|
class PerforceAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(PerforceAnnotationParser.class);
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
private final PerforceRepository repo;
private final File file;
private static final Pattern ANNOTATION_PATTERN = Pattern.compile("^(\\d+): .*");
/**
* @param repo defined instance
* @param file the file being annotated
*/
public PerforceAnnotationParser(PerforceRepository repo, File file) {
annotation = new Annotation(file.getName());
this.repo = repo;
this.file = file;
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// Pass null for revision to get all history for the file.
PerforceHistoryParser parser = new PerforceHistoryParser(repo);
List<HistoryEntry> revisions = parser.getRevisions(file, null).getHistoryEntries();
HashMap<String, String> revAuthor = new HashMap<>();
for (HistoryEntry entry : revisions) {
revAuthor.put(entry.getRevision(), entry.getAuthor());
}
String line;
int lineno = 0;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
while ((line = reader.readLine()) != null) {
++lineno;
if (line.equals("(... files differ ...)")) {
// Perforce knows as a binary file?
continue;
}
Matcher matcher = ANNOTATION_PATTERN.matcher(line);
if (matcher.find()) {
String revision = matcher.group(1);
String author = revAuthor.get(revision);
annotation.addLine(revision, author, true);
} else {
LOGGER.log(Level.WARNING,
"Error: did not find annotation in line {0} for ''{1}'': [{2}]",
new Object[]{lineno, this.file, line});
}
}
} catch (IOException e) {
LOGGER.log(Level.WARNING,
String.format("Error: Could not read annotations for '%s'", this.file), e);
}
| 265
| 380
| 645
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RCSAnnotationParser.java
|
RCSAnnotationParser
|
processStream
|
class RCSAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RCSAnnotationParser.class);
private Annotation annotation = null;
private final File file;
/**
* Pattern used to extract author/revision from {@code blame}.
*/
private static final Pattern ANNOTATION_PATTERN
= Pattern.compile("^([\\d\\.]+)\\s*\\((\\S+)\\s*\\S+\\): ");
RCSAnnotationParser(File file) {
this.file = file;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
Annotation getAnnotation() {
return this.annotation;
}
}
|
annotation = new Annotation(file.getName());
String line;
int lineno = 0;
Matcher matcher = ANNOTATION_PATTERN.matcher("");
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
while ((line = in.readLine()) != null) {
++lineno;
matcher.reset(line);
if (matcher.find()) {
String rev = matcher.group(1);
String author = matcher.group(2);
annotation.addLine(rev, author, true);
} else {
LOGGER.log(Level.WARNING,
"Error: did not find annotation in line {0} for ''{1}'': [{2}]",
new Object[]{lineno, this.file, line});
}
}
}
| 200
| 213
| 413
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RCSHistoryParser.java
|
RCSHistoryParser
|
parseFile
|
class RCSHistoryParser {
private static final Logger LOGGER = LoggerFactory.getLogger(RCSHistoryParser.class);
private static File readCVSRoot(File root, File cvsDir, String name) throws IOException {
String cvsroot = readFirstLine(root);
if (cvsroot == null) {
return null;
}
if (cvsroot.charAt(0) != '/') {
return null;
}
File repository = new File(cvsDir, "Repository");
String repo = readFirstLine(repository);
String dir = cvsroot + File.separatorChar + repo;
String filename = name + ",v";
File rcsFile = new File(dir, filename);
if (!rcsFile.exists()) {
File atticFile = new File(dir + File.separatorChar + "Attic", filename);
if (atticFile.exists()) {
rcsFile = atticFile;
}
}
return rcsFile;
}
History parse(File file, Repository repos) throws HistoryException {
try {
return parseFile(file);
} catch (IOException ioe) {
throw new HistoryException(ioe);
}
}
private History parseFile(File file) throws IOException {<FILL_FUNCTION_BODY>}
private void traverse(Node n, List<HistoryEntry> history) {
if (n == null) {
return;
}
traverse(n.getChild(), history);
TreeMap<?, ?> brt = n.getBranches();
if (brt != null) {
for (Object o : brt.values()) {
Node b = (Node) o;
traverse(b, history);
}
}
if (!n.isGhost()) {
HistoryEntry entry = new HistoryEntry();
entry.setRevision(n.getVersion().toString());
entry.setDate(n.getDate());
entry.setAuthor(n.getAuthor());
entry.setMessage(n.getLog());
entry.setActive(true);
history.add(entry);
}
}
protected static File getRCSFile(File file) {
return getRCSFile(file.getParent(), file.getName());
}
protected static File getRCSFile(String parent, String name) {
File rcsDir = new File(parent, "RCS");
File rcsFile = new File(rcsDir, name + ",v");
if (rcsFile.exists()) {
return rcsFile;
}
// not RCS, try CVS instead
return getCVSFile(parent, name);
}
protected static File getCVSFile(String parent, String name) {
try {
File CVSdir = new File(parent, "CVS");
if (CVSdir.isDirectory() && CVSdir.canRead()) {
File root = new File(CVSdir, "Root");
if (root.canRead()) {
return readCVSRoot(root, CVSdir, name);
}
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, e, () ->
"Failed to retrieve CVS file of parent: " + parent + ", name: " + name);
}
return null;
}
/**
* Read the first line of a file.
* @param file the file from which to read
* @return the first line of the file, or {@code null} if the file is empty
* @throws IOException if an I/O error occurs while reading the file
*/
private static String readFirstLine(File file) throws IOException {
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
return in.readLine();
}
}
}
|
File rcsfile = getRCSFile(file);
if (rcsfile == null) {
return null;
}
try {
Archive archive = new Archive(rcsfile.getPath());
Version ver = archive.getRevisionVersion();
Node n = archive.findNode(ver);
n = n.root();
ArrayList<HistoryEntry> entries = new ArrayList<>();
traverse(n, entries);
History history = new History();
history.setHistoryEntries(entries);
return history;
} catch (ParseException pe) {
throw RCSRepository.wrapInIOException(
"Could not parse file " + file.getPath(), pe);
}
| 967
| 179
| 1,146
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RCSRepository.java
|
RCSRepository
|
getHistoryGet
|
class RCSRepository extends Repository {
private static final Logger LOGGER = LoggerFactory.getLogger(RCSRepository.class);
private static final long serialVersionUID = 1L;
/**
* This property name is used to obtain the command to get annotation for this repository.
*/
private static final String CMD_BLAME_PROPERTY_KEY = "org.opengrok.indexer.history.RCS.blame";
/**
* The command to use to get annotation if none was given explicitly.
*/
private static final String CMD_BLAME_FALLBACK = "blame";
/**
* This is a static replacement for 'working' field. Effectively, check if hg is working once in a JVM
* instead of calling it for every MercurialRepository instance.
*/
private static final Supplier<Boolean> BLAME_IS_WORKING = LazilyInstantiate.using(RCSRepository::isBlameWorking);
public RCSRepository() {
type = "RCS";
ignoredDirs.add("RCS");
}
private static boolean isBlameWorking() {
String repoCommand = getCommand(MercurialRepository.class, CMD_BLAME_PROPERTY_KEY, CMD_BLAME_FALLBACK);
return checkCmd(repoCommand);
}
@Override
public boolean isWorking() {
if (working == null) {
working = BLAME_IS_WORKING.get();
ensureCommand(CMD_BLAME_PROPERTY_KEY, CMD_BLAME_FALLBACK);
}
return working;
}
@Override
boolean fileHasHistory(File file) {
return getRCSFile(file) != null;
}
@Override
boolean getHistoryGet(OutputStream out, String parent, String basename, String rev) {<FILL_FUNCTION_BODY>}
@Override
boolean fileHasAnnotation(File file) {
return fileHasHistory(file);
}
@Override
Annotation annotate(File file, String revision) throws IOException {
List<String> argv = new ArrayList<>();
ensureCommand(CMD_BLAME_PROPERTY_KEY, CMD_BLAME_FALLBACK);
argv.add(RepoCommand);
if (revision != null) {
argv.add("-r");
argv.add(revision);
}
argv.add(file.getName());
Executor executor = new Executor(argv, file.getParentFile(),
RuntimeEnvironment.getInstance().getInteractiveCommandTimeout());
RCSAnnotationParser annotator = new RCSAnnotationParser(file);
executor.exec(true, annotator);
return annotator.getAnnotation();
}
/**
* Wrap a {@code Throwable} in an {@code IOException} and return it.
*/
static IOException wrapInIOException(String message, Throwable t) {
return new IOException(message + ": " + t.getMessage(), t);
}
@Override
boolean isRepositoryFor(File file, CommandTimeoutType cmdType) {
File rcsDir = new File(file, "RCS");
if (!rcsDir.isDirectory()) {
return false;
}
// If there is at least one entry with the ',v' suffix,
// consider this a RCS repository.
String[] list = rcsDir.list((dir, name) ->
// Technically we should check whether the entry is a file
// however this would incur additional I/O. The pattern
// should be enough.
name.matches(".*,v")
);
return (list.length > 0);
}
/**
* Get a {@code File} object that points to the file that contains
* RCS history for the specified file.
*
* @param file the file whose corresponding RCS file should be found
* @return the file which contains the RCS history, or {@code null} if it
* cannot be found
*/
File getRCSFile(File file) {
File dir = new File(file.getParentFile(), "RCS");
String baseName = file.getName();
File rcsFile = new File(dir, baseName + ",v");
return rcsFile.exists() ? rcsFile : null;
}
@Override
boolean hasHistoryForDirectories() {
return false;
}
@Override
History getHistory(File file) throws HistoryException {
return new RCSHistoryParser().parse(file, this);
}
@Override
String determineParent(CommandTimeoutType cmdType) throws IOException {
return null;
}
@Override
String determineBranch(CommandTimeoutType cmdType) throws IOException {
return null;
}
@Override
String determineCurrentVersion(CommandTimeoutType cmdType) throws IOException {
return null;
}
}
|
try {
File file = new File(parent, basename);
File rcsFile = getRCSFile(file);
try (InputStream in = new RCSget(rcsFile.getPath(), rev)) {
copyBytes(out::write, in);
}
return true;
} catch (IOException ioe) {
LOGGER.log(Level.SEVERE, ioe, () ->
"Failed to retrieve revision " + rev + " of " + basename);
return false;
}
| 1,244
| 130
| 1,374
|
<methods>public final java.lang.String determineBranch() throws java.io.IOException,public final java.lang.String determineCurrentVersion() throws java.io.IOException,public final java.lang.String determineParent() throws java.io.IOException,public static java.lang.String format(java.util.Date) ,public boolean getHistoryGet(java.io.File, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public java.io.InputStream getHistoryGet(java.lang.String, java.lang.String, java.lang.String) ,public List<java.lang.String> getIgnoredDirs() ,public List<java.lang.String> getIgnoredFiles() ,public org.opengrok.indexer.history.HistoryEntry getLastHistoryEntry(java.io.File, boolean) throws org.opengrok.indexer.history.HistoryException,public java.lang.String getRepoCommand() ,public final boolean isRepositoryFor(java.io.File) ,public java.util.Date parse(java.lang.String) throws java.text.ParseException<variables>private static final java.util.logging.Logger LOGGER,protected static final java.text.SimpleDateFormat OUTPUT_DATE_FORMAT,protected java.lang.String RepoCommand,protected final non-sealed List<java.lang.String> ignoredDirs,protected final non-sealed List<java.lang.String> ignoredFiles,private static final long serialVersionUID,protected NavigableSet<org.opengrok.indexer.history.TagEntry> tagList
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RCSget.java
|
RCSget
|
read
|
class RCSget extends InputStream {
private final InputStream stream;
/**
* Pass null in version to get current revision.
* @param file file contents to get
* @param version specified revision or @{code null}
* @throws java.io.IOException if I/O exception occurred
* @throws java.io.FileNotFoundException if the file cannot be found
*/
public RCSget(String file, String version) throws IOException, FileNotFoundException {
try {
Archive archive = new Archive(file);
Object[] lines;
if (version == null) {
lines = archive.getRevision(false);
} else {
lines = archive.getRevision(version, false);
}
StringBuilder sb = new StringBuilder();
for (Object line : lines) {
sb.append((String) line);
sb.append("\n");
}
stream = new ByteArrayInputStream(sb.toString().getBytes());
} catch (ParseException e) {
throw RCSRepository.wrapInIOException("Parse error", e);
} catch (InvalidFileFormatException e) {
throw RCSRepository.wrapInIOException("Invalid RCS file format", e);
} catch (PatchFailedException e) {
throw RCSRepository.wrapInIOException("Patch failed", e);
} catch (NodeNotFoundException e) {
throw RCSRepository.wrapInIOException(
"Revision " + version + " not found", e);
}
}
@Override
public synchronized void reset() throws IOException {
stream.reset();
}
@Override
public void close() throws IOException {
IOUtils.close(stream);
}
@Override
public synchronized void mark(int readlimit) {
stream.mark(readlimit);
}
@Override
public int read(byte[] buffer, int pos, int len) throws IOException {
return stream.read(buffer, pos, len);
}
@Override
public int read() throws IOException {<FILL_FUNCTION_BODY>}
}
|
throw new IOException("use a BufferedInputStream. just read() is not supported!");
| 516
| 23
| 539
|
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RazorHistoryParser.java
|
RazorHistoryParser
|
parseContents
|
class RazorHistoryParser {
private static final Logger LOGGER = LoggerFactory.getLogger(RazorHistoryParser.class);
private RazorRepository repository = new RazorRepository();
private static final Pattern ACTION_TYPE_PATTERN =
Pattern.compile("^(INTRODUCE|CHECK-OUT|CHECK-IN|UN-CHECK-OUT|RENAME|EDIT_PROPS|ALTERED|CHECK-POINT|" +
"REVERT|INTRODUCE_AND_EDIT|BRANCH|BUMP|MERGE-CHECK-IN|PROMOTE)\\s+(\\S*)\\s+([\\.0-9]+)?\\s+(\\S*)\\s+(\\S*)\\s*$");
private static final Pattern ADDITIONAL_INFO_PATTERN =
Pattern.compile("^##(TITLE|NOTES|AUDIT|ISSUE):\\s+(.*)\\s*$");
private static final boolean DUMP_HISTORY_ENTRY_ADDITIONS = false;
History parse(File file, Repository repos) throws HistoryException {
try {
return parseFile(file, repos);
} catch (IOException ioe) {
throw new HistoryException(ioe);
}
}
private History parseFile(File file, Repository repos)
throws IOException {
repository = (RazorRepository) repos;
File mappedFile = repository.getRazorHistoryFileFor(file);
parseDebug("Mapping " + file.getPath() + " to '" + mappedFile.getPath() + "'");
if (!mappedFile.exists()) {
parseProblem("History File Mapping is NON-EXISTENT (" + mappedFile.getAbsolutePath() + ")");
return null;
}
if (mappedFile.isDirectory()) {
parseProblem("History File Mapping is a DIRECTORY (" + mappedFile.getAbsolutePath() + ")");
return null;
}
try (FileReader contents = new FileReader(mappedFile.getAbsoluteFile())) {
return parseContents(new BufferedReader(contents));
}
}
protected History parseContents(BufferedReader contents) throws IOException {<FILL_FUNCTION_BODY>}
private void dumpEntry(HistoryEntry entry) {
if (DUMP_HISTORY_ENTRY_ADDITIONS) {
entry.dump();
}
}
private void parseDebug(String message) {
LOGGER.log(Level.FINE, () -> "RazorHistoryParser: " + message );
}
private void parseProblem(String message) {
LOGGER.log(Level.SEVERE, () -> "PROBLEM: RazorHistoryParser - " + message);
}
}
|
String line;
ArrayList<HistoryEntry> entries = new ArrayList<>();
HistoryEntry entry = null;
boolean ignoreEntry = false;
boolean seenActionType = false;
boolean lastWasTitle = true;
Matcher actionMatcher = ACTION_TYPE_PATTERN.matcher("");
Matcher infoMatcher = ADDITIONAL_INFO_PATTERN.matcher("");
while ((line = contents.readLine()) != null) {
parseDebug("Processing '" + line + "'");
if (line.isBlank()) {
if (entry != null && entry.getDate() != null) {
entries.add(entry);
dumpEntry(entry);
}
entry = new HistoryEntry();
ignoreEntry = false;
seenActionType = false;
} else if (!ignoreEntry) {
if (seenActionType) {
infoMatcher.reset(line);
if (infoMatcher.find()) {
String infoType = infoMatcher.group(1);
String details = infoMatcher.group(2);
if ("TITLE".equals(infoType)) {
parseDebug("Setting Message : '" + details + "'");
entry.setMessage(details);
lastWasTitle = true;
} else {
parseDebug("Ignoring Info Type Line '" + line + "'");
}
} else {
if (!line.startsWith("##") && line.charAt(0) == '#') {
parseDebug("Seen Comment : '" + line + "'");
if (lastWasTitle) {
entry.appendMessage("");
lastWasTitle = false;
}
entry.appendMessage(line.substring(1));
} else {
parseProblem("Expecting addlInfo and got '" + line + "'");
}
}
} else {
actionMatcher.reset(line);
if (actionMatcher.find()) {
seenActionType = true;
if (entry != null && entry.getDate() != null) {
entries.add(entry);
dumpEntry(entry);
}
entry = new HistoryEntry();
String actionType = actionMatcher.group(1);
String userName = actionMatcher.group(2);
String revision = actionMatcher.group(3);
String state = actionMatcher.group(4);
String dateTime = actionMatcher.group(5);
parseDebug("New History Event Seen : actionType = " + actionType + ", userName = " + userName +
", revision = " + revision + ", state = " + state + ", dateTime = " + dateTime);
if (actionType.startsWith("INTRODUCE") ||
actionType.contains("CHECK-IN") ||
"CHECK-POINT".equals(actionType) ||
"REVERT".equals(actionType)) {
entry.setAuthor(userName);
entry.setRevision(revision);
entry.setActive("Active".equals(state));
Date date = null;
try {
date = repository.parse(dateTime);
} catch (ParseException pe) {
//
// Overriding processStream() thus need to comply with the
// set of exceptions it can throw.
//
throw new IOException("Could not parse date: " + dateTime, pe);
}
entry.setDate(date);
ignoreEntry = false;
} else {
ignoreEntry = true;
}
} else {
parseProblem("Expecting actionType and got '" + line + "'");
}
}
}
}
if (entry != null && entry.getDate() != null) {
entries.add(entry);
dumpEntry(entry);
}
History history = new History();
history.setHistoryEntries(entries);
return history;
| 703
| 969
| 1,672
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RepoRepository.java
|
RepoRepository
|
isRepositoryFor
|
class RepoRepository extends Repository {
// TODO: cache all of the GitRepositories within the class
private static final long serialVersionUID = 1L;
/**
* The property name used to obtain the client command for this repository.
*/
public static final String CMD_PROPERTY_KEY = "org.opengrok.indexer.history.repo";
/**
* The command to use to access the repository if none was given explicitly.
*/
public static final String CMD_FALLBACK = "repo";
public RepoRepository() {
type = "repo";
setWorking(Boolean.TRUE);
ignoredDirs.add(".repo");
}
@Override
public boolean isWorking() {
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
return true;
}
@Override
boolean isRepositoryFor(File file, CommandTimeoutType cmdType) {<FILL_FUNCTION_BODY>}
@Override
boolean supportsSubRepositories() {
return true;
}
@Override
boolean fileHasHistory(File file) {
return false;
}
@Override
boolean hasHistoryForDirectories() {
return false;
}
@Override
History getHistory(File file) {
throw new UnsupportedOperationException("Should never be called!");
}
@Override
boolean getHistoryGet(OutputStream out, String parent, String basename, String rev) {
throw new UnsupportedOperationException("Should never be called!");
}
@Override
boolean fileHasAnnotation(File file) {
return false;
}
@Override
Annotation annotate(File file, String revision) {
throw new UnsupportedOperationException("Should never be called!");
}
@Override
String determineParent(CommandTimeoutType cmdType) throws IOException {
return null;
}
@Override
String determineBranch(CommandTimeoutType cmdType) {
return null;
}
@Override
String determineCurrentVersion(CommandTimeoutType cmdType) throws IOException {
return null;
}
}
|
if (file.isDirectory()) {
File f = new File(file, ".repo");
return f.exists() && f.isDirectory();
}
return false;
| 543
| 47
| 590
|
<methods>public final java.lang.String determineBranch() throws java.io.IOException,public final java.lang.String determineCurrentVersion() throws java.io.IOException,public final java.lang.String determineParent() throws java.io.IOException,public static java.lang.String format(java.util.Date) ,public boolean getHistoryGet(java.io.File, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public java.io.InputStream getHistoryGet(java.lang.String, java.lang.String, java.lang.String) ,public List<java.lang.String> getIgnoredDirs() ,public List<java.lang.String> getIgnoredFiles() ,public org.opengrok.indexer.history.HistoryEntry getLastHistoryEntry(java.io.File, boolean) throws org.opengrok.indexer.history.HistoryException,public java.lang.String getRepoCommand() ,public final boolean isRepositoryFor(java.io.File) ,public java.util.Date parse(java.lang.String) throws java.text.ParseException<variables>private static final java.util.logging.Logger LOGGER,protected static final java.text.SimpleDateFormat OUTPUT_DATE_FORMAT,protected java.lang.String RepoCommand,protected final non-sealed List<java.lang.String> ignoredDirs,protected final non-sealed List<java.lang.String> ignoredFiles,private static final long serialVersionUID,protected NavigableSet<org.opengrok.indexer.history.TagEntry> tagList
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RepositoriesHelp.java
|
RepositoriesHelp
|
getText
|
class RepositoriesHelp {
public static String getText() {<FILL_FUNCTION_BODY>}
private static void appendClassesHelp(
StringBuilder builder, List<Class<? extends Repository>> clazzes) {
clazzes.sort((o1, o2) -> o1.getSimpleName().compareToIgnoreCase(o2.getSimpleName()));
for (Class<?> clazz : clazzes) {
String simpleName = clazz.getSimpleName();
if (toAka(builder, simpleName)) {
builder.append(" (");
builder.append(simpleName);
builder.append(")");
}
builder.append(System.lineSeparator());
}
}
private static boolean toAka(StringBuilder builder, String repoSimpleName) {
final String REPOSITORY = "Repository";
if (!repoSimpleName.endsWith(REPOSITORY)) {
builder.append(repoSimpleName);
return false;
} else {
String aka = repoSimpleName.substring(0,
repoSimpleName.length() - REPOSITORY.length());
builder.append(aka.toLowerCase(Locale.ROOT));
return true;
}
}
/* private to enforce static */
private RepositoriesHelp() {
}
}
|
StringBuilder builder = new StringBuilder();
builder.append("Enabled repositories:");
builder.append(System.lineSeparator());
builder.append(System.lineSeparator());
List<Class<? extends Repository>> clazzes = RepositoryFactory.getRepositoryClasses();
appendClassesHelp(builder, clazzes);
List<Class<? extends Repository>> disabledClazzes =
RepositoryFactory.getDisabledRepositoryClasses();
if (!disabledClazzes.isEmpty()) {
if (!clazzes.isEmpty()) {
builder.append(System.lineSeparator());
}
builder.append("Disabled repositories:");
builder.append(System.lineSeparator());
builder.append(System.lineSeparator());
appendClassesHelp(builder, disabledClazzes);
}
return builder.toString();
| 338
| 210
| 548
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RepositoryLookupUncached.java
|
RepositoryLookupUncached
|
getRepository
|
class RepositoryLookupUncached implements RepositoryLookup {
private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryLookupUncached.class);
@Override
public Repository getRepository(final Path filePath, Set<String> repoParentDirs,
Map<String, Repository> repositories, PathCanonicalizer canonicalizer) {<FILL_FUNCTION_BODY>}
@Override
public void clear() {
// Do nothing
}
@Override
public void repositoriesRemoved(Collection<Repository> removedRepos) {
// Do nothings
}
}
|
Path path = filePath;
while (path != null) {
String nextPath = path.toString();
for (String rootKey : repoParentDirs) {
String rel;
try {
rel = canonicalizer.resolve(path, path.getFileSystem().getPath(rootKey));
} catch (IOException e) {
LOGGER.log(Level.WARNING, e, () ->
"Failed to get relative to canonical for " + nextPath);
return null;
}
Repository repo;
if (rel.equals(nextPath)) {
repo = repositories.get(nextPath);
} else {
String inRootPath = Paths.get(rootKey, rel).toString();
repo = repositories.get(inRootPath);
}
if (repo != null) {
return repo;
}
}
path = path.getParent();
}
return null;
| 153
| 236
| 389
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RepositoryWithHistoryTraversal.java
|
ChangesetInfo
|
doCreateCache
|
class ChangesetInfo {
CommitInfo commit;
public SortedSet<String> files;
public Set<String> renamedFiles;
public Set<String> deletedFiles;
public Boolean isMerge;
ChangesetInfo(CommitInfo commit) {
this.commit = commit;
this.files = new TreeSet<>();
this.renamedFiles = new HashSet<>();
this.deletedFiles = new HashSet<>();
}
ChangesetInfo(CommitInfo commit, SortedSet<String> files, Set<String> renamedFiles, Set<String> deletedFiles,
Boolean isMerge) {
this.commit = commit;
this.files = files;
this.renamedFiles = renamedFiles;
this.deletedFiles = deletedFiles;
this.isMerge = isMerge;
}
}
/**
* Traverse history of given file/directory.
* @param file File object
* @param sinceRevision start revision (non-inclusive)
* @param tillRevision end revision (inclusive)
* @param numCommits maximum number of commits to traverse (use {@code null} as unlimited)
* @param visitors list of {@link ChangesetVisitor} objects
* @throws HistoryException on error
*/
public abstract void traverseHistory(File file, String sinceRevision, @Nullable String tillRevision,
Integer numCommits, List<ChangesetVisitor> visitors) throws HistoryException;
public History getHistory(File file, String sinceRevision, String tillRevision,
Integer numCommits) throws HistoryException {
if (numCommits != null && numCommits <= 0) {
return null;
}
HistoryCollector historyCollector = new HistoryCollector(isMergeCommitsEnabled());
traverseHistory(file, sinceRevision, tillRevision, numCommits, List.of(historyCollector));
History history = new History(historyCollector.entries, historyCollector.renamedFiles,
historyCollector.latestRev);
// Assign tags to changesets they represent.
if (RuntimeEnvironment.getInstance().isTagsEnabled() && hasFileBasedTags()) {
assignTagsInHistory(history);
}
return history;
}
@Override
protected void doCreateCache(HistoryCache cache, String sinceRevision, File directory) throws HistoryException, CacheException {<FILL_FUNCTION_BODY>
|
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
FileCollector fileCollector = null;
Project project = Project.getProject(directory);
if (project != null && isHistoryBasedReindex() && isHistoryEnabled()) {
// The fileCollector has to go through merge changesets no matter what the configuration says
// in order to detect the files that need to be indexed.
fileCollector = new FileCollector(true);
}
if (!env.isHistoryCachePerPartesEnabled()) {
LOGGER.log(Level.INFO, "repository {0} supports per partes history cache creation however " +
"it is disabled in the configuration. Generating history cache as whole.", this);
HistoryCollector historyCollector = new HistoryCollector(isMergeCommitsEnabled());
List<ChangesetVisitor> visitors = new ArrayList<>();
visitors.add(historyCollector);
if (fileCollector != null) {
visitors.add(fileCollector);
}
try (Progress progress = new Progress(LOGGER, String.format("changesets traversed of %s", this),
Level.FINER)) {
ProgressVisitor progressVisitor = new ProgressVisitor(progress);
visitors.add(progressVisitor);
traverseHistory(directory, sinceRevision, null, null, visitors);
}
History history = new History(historyCollector.entries, historyCollector.renamedFiles,
historyCollector.latestRev);
// Assign tags to changesets they represent.
if (env.isTagsEnabled() && hasFileBasedTags()) {
assignTagsInHistory(history);
}
finishCreateCache(cache, history, null);
updateFileCollector(fileCollector, project);
return;
}
// For repositories that supports this, avoid storing complete History in memory
// (which can be sizeable, at least for the initial indexing, esp. if merge changeset support is enabled),
// by splitting the work into multiple chunks.
BoundaryChangesets boundaryChangesets = new BoundaryChangesets(this);
List<String> boundaryChangesetList = new ArrayList<>(boundaryChangesets.getBoundaryChangesetIDs(sinceRevision));
boundaryChangesetList.add(null); // to finish the last step in the cycle below
LOGGER.log(Level.FINE, "boundary changesets: {0}", boundaryChangesetList);
int cnt = 0;
for (String tillRevision: boundaryChangesetList) {
Statistics stat = new Statistics();
LOGGER.log(Level.FINEST, "storing history cache for revision range ({0}, {1})",
new Object[]{sinceRevision, tillRevision});
HistoryCollector historyCollector = new HistoryCollector(isMergeCommitsEnabled());
List<ChangesetVisitor> visitors = new ArrayList<>();
visitors.add(historyCollector);
if (fileCollector != null) {
visitors.add(fileCollector);
}
try (Progress progress = new Progress(LOGGER,
String.format("changesets traversed of %s (range %s %s)", this, sinceRevision, tillRevision),
Level.FINER)) {
ProgressVisitor progressVisitor = new ProgressVisitor(progress);
visitors.add(progressVisitor);
traverseHistory(directory, sinceRevision, tillRevision, null, visitors);
}
History history = new History(historyCollector.entries, historyCollector.renamedFiles,
historyCollector.latestRev);
// Assign tags to changesets they represent.
if (env.isTagsEnabled() && hasFileBasedTags()) {
assignTagsInHistory(history);
}
finishCreateCache(cache, history, tillRevision);
sinceRevision = tillRevision;
stat.report(LOGGER, Level.FINE, String.format("Finished chunk %d/%d of history cache for repository '%s'",
++cnt, boundaryChangesetList.size(), this.getDirectoryName()));
}
updateFileCollector(fileCollector, project);
| 607
| 1,027
| 1,634
|
<methods>public non-sealed void <init>() ,public abstract void accept(java.lang.String, Consumer<org.opengrok.indexer.history.BoundaryChangesets.IdWithProgress>, org.opengrok.indexer.util.Progress) throws org.opengrok.indexer.history.HistoryException,public int getPerPartesCount() <variables>private static final java.util.logging.Logger LOGGER,public static final int MAX_CHANGESETS,private static final long serialVersionUID
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/RepositoryWithPerPartesHistory.java
|
RepositoryWithPerPartesHistory
|
doCreateCache
|
class RepositoryWithPerPartesHistory extends Repository {
private static final long serialVersionUID = -3433255821312805064L;
public static final int MAX_CHANGESETS = 128;
private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryWithPerPartesHistory.class);
/**
* Just like for {@link Repository#getHistory(File)} it is expected that the lists of (renamed) files
* individual files (i.e. not directory) are empty.
* @param file file to retrieve history for
* @param sinceRevision start revision (non-inclusive)
* @param tillRevision end revision (inclusive)
* @return history object
* @throws HistoryException if history retrieval fails
*/
abstract History getHistory(File file, String sinceRevision, String tillRevision) throws HistoryException;
/**
* @return maximum number of entries to retrieve
*/
public int getPerPartesCount() {
return MAX_CHANGESETS;
}
/**
* Traverse the changesets using the visitor pattern.
* @param sinceRevision start revision
* @param visitor consumer of revisions
* @param progress {@link Progress} instance
* @throws HistoryException on error during history retrieval
*/
public abstract void accept(String sinceRevision, Consumer<BoundaryChangesets.IdWithProgress> visitor,
Progress progress)
throws HistoryException;
@Override
protected void doCreateCache(HistoryCache cache, String sinceRevision, File directory)
throws HistoryException, CacheException {<FILL_FUNCTION_BODY>}
}
|
if (!RuntimeEnvironment.getInstance().isHistoryCachePerPartesEnabled()) {
LOGGER.log(Level.INFO, "repository {0} supports per partes history cache creation however " +
"it is disabled in the configuration. Generating history cache as whole.", this);
History history = getHistory(directory, sinceRevision);
finishCreateCache(cache, history, null);
return;
}
// For repositories that supports this, avoid storing complete History in memory
// (which can be sizeable, at least for the initial indexing, esp. if merge changeset support is enabled),
// by splitting the work into multiple chunks.
BoundaryChangesets boundaryChangesets = new BoundaryChangesets(this);
List<String> boundaryChangesetList = new ArrayList<>(boundaryChangesets.getBoundaryChangesetIDs(sinceRevision));
boundaryChangesetList.add(null); // to finish the last step in the cycle below
LOGGER.log(Level.FINE, "boundary changesets: {0}", boundaryChangesetList);
int cnt = 0;
for (String tillRevision: boundaryChangesetList) {
Statistics stat = new Statistics();
LOGGER.log(Level.FINEST, "storing history cache for revision range ({0}, {1})",
new Object[]{sinceRevision, tillRevision});
History history = getHistory(directory, sinceRevision, tillRevision);
finishCreateCache(cache, history, tillRevision);
sinceRevision = tillRevision;
stat.report(LOGGER, Level.FINE, String.format("finished chunk %d/%d of history cache for repository ''%s''",
++cnt, boundaryChangesetList.size(), this.getDirectoryName()));
}
| 416
| 442
| 858
|
<methods>public final java.lang.String determineBranch() throws java.io.IOException,public final java.lang.String determineCurrentVersion() throws java.io.IOException,public final java.lang.String determineParent() throws java.io.IOException,public static java.lang.String format(java.util.Date) ,public boolean getHistoryGet(java.io.File, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public java.io.InputStream getHistoryGet(java.lang.String, java.lang.String, java.lang.String) ,public List<java.lang.String> getIgnoredDirs() ,public List<java.lang.String> getIgnoredFiles() ,public org.opengrok.indexer.history.HistoryEntry getLastHistoryEntry(java.io.File, boolean) throws org.opengrok.indexer.history.HistoryException,public java.lang.String getRepoCommand() ,public final boolean isRepositoryFor(java.io.File) ,public java.util.Date parse(java.lang.String) throws java.text.ParseException<variables>private static final java.util.logging.Logger LOGGER,protected static final java.text.SimpleDateFormat OUTPUT_DATE_FORMAT,protected java.lang.String RepoCommand,protected final non-sealed List<java.lang.String> ignoredDirs,protected final non-sealed List<java.lang.String> ignoredFiles,private static final long serialVersionUID,protected NavigableSet<org.opengrok.indexer.history.TagEntry> tagList
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SCCSHistoryParser.java
|
SCCSHistoryParser
|
read
|
class SCCSHistoryParser {
static final String SCCS_DIR_NAME = "SCCS";
boolean pass;
boolean passRecord;
boolean active;
int field;
boolean sep;
StringBuilder sccsRecord = new StringBuilder(128);
Reader in;
// Record fields
private String revision;
private Date rdate;
private String author;
private String comment;
private final SCCSRepository repository;
SCCSHistoryParser(SCCSRepository repository) {
this.repository = repository;
}
History parse(File file) throws HistoryException {
try {
return parseFile(file);
} catch (IOException e) {
throw new HistoryException(String.format("Failed to get history for '%s'", file.getAbsolutePath()), e);
} catch (ParseException e) {
throw new HistoryException(String.format("Failed to parse history for '%s'", file.getAbsolutePath()), e);
}
}
@Nullable
private History parseFile(File file) throws IOException, ParseException {
File f = getSCCSFile(file);
if (f == null) {
return null;
}
in = new BufferedReader(new FileReader(f));
pass = sep = false;
passRecord = true;
active = true;
field = 0;
ArrayList<HistoryEntry> entries = new ArrayList<>();
while (next()) {
HistoryEntry entry = new HistoryEntry();
entry.setRevision(getRevision());
entry.setDate(getDate());
entry.setAuthor(getAuthor());
entry.setMessage(getComment());
entry.setActive(isActive());
entries.add(entry);
}
IOUtils.close(in);
History history = new History();
history.setHistoryEntries(entries);
return history;
}
/**
* Read a single line of delta record into the {@link #sccsRecord} member.
*
* @return boolean indicating whether there is another record.
* @throws IOException on I/O error
*/
private boolean next() throws IOException {
sep = true;
sccsRecord.setLength(0);
int c;
while ((c = read()) > 1) {
sccsRecord.append((char) c);
}
// to flag that revision needs to be re populated if you really need it
revision = null;
return (sccsRecord.length() > 2);
}
/**
* Split record into fields.
*
* @throws ParseException if the date in the record cannot be parsed
*/
private void initFields() throws ParseException {
if (revision == null) {
String[] f = sccsRecord.toString().split(" ", 6);
if (f.length > 5) {
revision = f[1];
try {
rdate = repository.parse(f[2] + " " + f[3]);
} catch (ParseException e) {
rdate = null;
//
// Throw new exception up so that it can be paired with filename
// on which the problem occurred.
//
throw e;
}
author = f[4];
comment = f[5];
} else {
rdate = null;
author = null;
comment = null;
}
}
}
/**
* @return get the revision string of current log record
*/
private String getRevision() throws ParseException {
initFields();
return revision;
}
/**
* @return get the date associated with current log record
*/
private Date getDate() throws ParseException {
initFields();
return rdate;
}
/**
* @return get the author of current log record
*/
private String getAuthor() throws ParseException {
initFields();
return author;
}
/**
* @return get the comments of current log record
*/
private String getComment() throws ParseException {
initFields();
return comment;
}
private boolean isActive() {
return active;
}
private int read() throws IOException {<FILL_FUNCTION_BODY>}
private static File getSCCSFile(File file) {
return getSCCSFile(file.getParent(), file.getName());
}
@Nullable
static File getSCCSFile(String parent, String name) {
File f = Paths.get(parent, SCCS_DIR_NAME, "s." + name).toFile();
if (!f.exists()) {
return null;
}
return f;
}
}
|
int c, d, dt;
while ((c = in.read()) != -1) {
switch (c) { //NOPMD
case 1:
d = in.read();
switch (d) {
case 'c':
case 't':
case 'u':
d = in.read();
if (d != ' ') {
return (d);
}
pass = true;
break;
case 'd':
d = in.read();
if (d == ' ') {
dt = in.read();
active = dt != 'R';
passRecord = true;
field = 1;
} else {
return (d);
}
break;
case -1:
case 'I': //the file contents start
case 'D':
case 'E':
case 'T':
return -1;
case 'e':
pass = false;
if (sep && passRecord) {
return 1;
}
passRecord = true;
break;
default:
pass = false;
}
break;
case ' ':
if (passRecord) {
if (field > 0) {
field++;
pass = true;
}
if (field > 5) {
field = 0;
pass = false;
return c;
}
}
default:
if (pass && passRecord) {
return c;
}
}
}
return -1;
| 1,200
| 392
| 1,592
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SCCSRepository.java
|
SCCSRepository
|
annotate
|
class SCCSRepository extends Repository {
private static final Logger LOGGER = LoggerFactory.getLogger(SCCSRepository.class);
private static final long serialVersionUID = 1L;
/**
* The property name used to obtain the client command for this repository.
*/
public static final String CMD_PROPERTY_KEY = "org.opengrok.indexer.history.SCCS";
/**
* The command to use to access the repository if none was given explicitly.
*/
public static final String CMD_FALLBACK = "sccs";
@VisibleForTesting
static final String CODEMGR_WSDATA = "Codemgr_wsdata";
public SCCSRepository() {
type = "SCCS";
/*
* Originally there was only the "yy/MM/dd" pattern however the newer SCCS implementations seem
* to use the time as well. Some historical SCCS versions might still use that, so it is left there
* for potential compatibility.
*/
datePatterns = new String[]{
"yy/MM/dd HH:mm:ss",
"yy/MM/dd"
};
ignoredDirs.add("SCCS");
}
@Override
boolean getHistoryGet(OutputStream out, String parent, String basename, String rev) {
try {
File history = SCCSHistoryParser.getSCCSFile(parent, basename);
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
try (InputStream in = SCCSget.getRevision(RepoCommand, history, rev)) {
copyBytes(out::write, in);
}
return true;
} catch (FileNotFoundException ex) {
// continue below
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "An error occurred while getting revision", ex);
}
return false;
}
private Map<String, String> getAuthors(File file) throws IOException {
ArrayList<String> argv = new ArrayList<>();
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
argv.add(RepoCommand);
argv.add("prs");
argv.add("-e");
argv.add("-d:I: :P:");
argv.add(file.getCanonicalPath());
Executor executor = new Executor(argv, file.getCanonicalFile().getParentFile(),
RuntimeEnvironment.getInstance().getInteractiveCommandTimeout());
SCCSRepositoryAuthorParser parser = new SCCSRepositoryAuthorParser();
executor.exec(true, parser);
return parser.getAuthors();
}
/**
* Annotate the specified file/revision.
*
* @param file file to annotate
* @param revision revision to annotate
* @return file annotation
* @throws java.io.IOException if I/O exception occurs
*/
@Override
public Annotation annotate(File file, String revision) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public boolean fileHasAnnotation(File file) {
return true;
}
@Override
public boolean fileHasHistory(File file) {
String parentFile = file.getParent();
String name = file.getName();
File f = SCCSHistoryParser.getSCCSFile(parentFile, name);
if (f == null) {
return false;
}
return f.exists();
}
@Override
boolean isRepositoryFor(File file, CommandTimeoutType cmdType) {
if (file.isDirectory()) {
File f = new File(file, CODEMGR_WSDATA.toLowerCase()); // OK no ROOT
if (f.isDirectory()) {
return true;
}
f = new File(file, CODEMGR_WSDATA);
if (f.isDirectory()) {
return true;
}
return new File(file, SCCSHistoryParser.SCCS_DIR_NAME).isDirectory();
}
return false;
}
@Override
public boolean isWorking() {
if (working == null) {
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
working = checkCmd(RepoCommand, "help", "help");
if (!working) {
working = checkCmd(RepoCommand, "--version");
}
}
return working;
}
@Override
boolean hasHistoryForDirectories() {
return false;
}
@Override
History getHistory(File file) throws HistoryException {
return new SCCSHistoryParser(this).parse(file);
}
@Override
String determineParent(CommandTimeoutType cmdType) throws IOException {
File parentFile = Paths.get(getDirectoryName(), CODEMGR_WSDATA, "parent").toFile();
String parent = null;
if (parentFile.isFile()) {
String line;
try (BufferedReader in = new BufferedReader(new FileReader(parentFile))) {
if ((line = in.readLine()) == null) {
LOGGER.log(Level.WARNING,
"Failed to get parent for {0} (cannot read first line of {1})",
new Object[]{getDirectoryName(), parentFile.getName()});
return null;
}
if (!line.startsWith("VERSION")) {
LOGGER.log(Level.WARNING,
"Failed to get parent for {0} (first line does not start with VERSION)",
getDirectoryName());
}
if ((parent = in.readLine()) == null) {
LOGGER.log(Level.WARNING,
"Failed to get parent for {0} (cannot read second line of {1})",
new Object[]{getDirectoryName(), parentFile.getName()});
}
}
}
return parent;
}
@Override
String determineBranch(CommandTimeoutType cmdType) {
return null;
}
@Override
String determineCurrentVersion(CommandTimeoutType cmdType) throws IOException {
return null;
}
}
|
Map<String, String> authors = getAuthors(file);
ArrayList<String> argv = new ArrayList<>();
ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
argv.add(RepoCommand);
argv.add("get");
argv.add("-m");
argv.add("-p");
if (revision != null) {
argv.add("-r" + revision);
}
argv.add(file.getCanonicalPath());
Executor executor = new Executor(argv, file.getCanonicalFile().getParentFile(),
RuntimeEnvironment.getInstance().getInteractiveCommandTimeout());
SCCSRepositoryAnnotationParser parser = new SCCSRepositoryAnnotationParser(file, authors);
executor.exec(true, parser);
return parser.getAnnotation();
| 1,556
| 214
| 1,770
|
<methods>public final java.lang.String determineBranch() throws java.io.IOException,public final java.lang.String determineCurrentVersion() throws java.io.IOException,public final java.lang.String determineParent() throws java.io.IOException,public static java.lang.String format(java.util.Date) ,public boolean getHistoryGet(java.io.File, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public java.io.InputStream getHistoryGet(java.lang.String, java.lang.String, java.lang.String) ,public List<java.lang.String> getIgnoredDirs() ,public List<java.lang.String> getIgnoredFiles() ,public org.opengrok.indexer.history.HistoryEntry getLastHistoryEntry(java.io.File, boolean) throws org.opengrok.indexer.history.HistoryException,public java.lang.String getRepoCommand() ,public final boolean isRepositoryFor(java.io.File) ,public java.util.Date parse(java.lang.String) throws java.text.ParseException<variables>private static final java.util.logging.Logger LOGGER,protected static final java.text.SimpleDateFormat OUTPUT_DATE_FORMAT,protected java.lang.String RepoCommand,protected final non-sealed List<java.lang.String> ignoredDirs,protected final non-sealed List<java.lang.String> ignoredFiles,private static final long serialVersionUID,protected NavigableSet<org.opengrok.indexer.history.TagEntry> tagList
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SCCSRepositoryAnnotationParser.java
|
SCCSRepositoryAnnotationParser
|
processStream
|
class SCCSRepositoryAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SCCSRepositoryAnnotationParser.class);
/**
* Store annotation created by {@link #processStream(InputStream)}.
*/
private final Annotation annotation;
private final Map<String, String> authors;
private final File file;
/**
* Pattern used to extract revision from the {@code sccs get} command.
*/
private static final Pattern ANNOTATION_PATTERN = Pattern.compile("^([\\d.]+)\\s+");
SCCSRepositoryAnnotationParser(File file, Map<String, String> authors) {
this.file = file;
this.annotation = new Annotation(file.getName());
this.authors = authors;
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
}
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(input))) {
String line;
int lineno = 0;
while ((line = in.readLine()) != null) {
++lineno;
Matcher matcher = ANNOTATION_PATTERN.matcher(line);
if (matcher.find()) {
String rev = matcher.group(1);
String author = authors.get(rev);
if (author == null) {
author = "unknown";
}
annotation.addLine(rev, author, true);
} else {
LOGGER.log(Level.SEVERE,
"Error: did not find annotations in line {0} for ''{2}'': [{1}]",
new Object[]{lineno, line, file});
}
}
}
| 285
| 212
| 497
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SCCSRepositoryAuthorParser.java
|
SCCSRepositoryAuthorParser
|
processStream
|
class SCCSRepositoryAuthorParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SCCSRepositoryAuthorParser.class);
private final Map<String, String> authors = new HashMap<>();
/**
* Pattern used to extract revision from the {@code sccs get} command.
*/
private static final Pattern AUTHOR_PATTERN = Pattern.compile("^([\\d.]+)\\s+(\\S+)");
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
/**
* @return map of revision to author
*/
public Map<String, String> getAuthors() {
return authors;
}
}
|
try (BufferedReader in = new BufferedReader(
new InputStreamReader(input))) {
String line;
int lineno = 0;
while ((line = in.readLine()) != null) {
++lineno;
Matcher matcher = AUTHOR_PATTERN.matcher(line);
if (matcher.find()) {
String rev = matcher.group(1);
String auth = matcher.group(2);
authors.put(rev, auth);
} else {
LOGGER.log(Level.WARNING,
"Error: did not find authors in line {0}: [{1}]",
new Object[]{lineno, line});
}
}
}
| 192
| 180
| 372
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SCCSget.java
|
SCCSget
|
getRevision
|
class SCCSget {
public static InputStream getRevision(String command, File file, String revision) throws IOException {<FILL_FUNCTION_BODY>}
private SCCSget() {
}
}
|
InputStream ret = null;
ArrayList<String> argv = new ArrayList<>();
argv.add(command);
argv.add("get");
argv.add("-p");
if (revision != null) {
argv.add("-r" + revision);
}
argv.add(file.getCanonicalPath());
Executor executor = new Executor(argv);
if (executor.exec() == 0) {
ret = executor.getOutputStream();
}
return ret;
| 57
| 140
| 197
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SSCMHistoryParser.java
|
SSCMHistoryParser
|
processStream
|
class SSCMHistoryParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SSCMHistoryParser.class);
private final SSCMRepository repository;
SSCMHistoryParser(SSCMRepository repository) {
this.repository = repository;
}
private static final String ACTION_PATTERN = "[a-z][a-z ]+";
private static final String USER_PATTERN = "\\w+";
private static final String VERSION_PATTERN = "\\d+";
private static final String TIME_PATTERN = "\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{2} [AP]M";
private static final String COMMENT_START_PATTERN = "Comments - ";
// ^([a-z][a-z ]+)(?:\[(.*?)\])?\s+(\w+)\s+(\d+)\s+(\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2} [AP]M)$\s*(?:Comments - )?
private static final Pattern HISTORY_PATTERN = Pattern.compile("^(" + ACTION_PATTERN +
")(?:\\[(.*?)\\])?\\s+(" + USER_PATTERN + ")\\s+(" + VERSION_PATTERN + ")\\s+(" + TIME_PATTERN +
")$\\s*(?:" + COMMENT_START_PATTERN + ")?",
Pattern.MULTILINE);
private static final String NEWLINE = System.getProperty("line.separator");
private History history;
/**
* Process the output from the history command and insert the HistoryEntries
* into the history field.
*
* @param input The output from the process
* @throws java.io.IOException If an error occurs while reading the stream
*/
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
History parse(File file, String sinceRevision) throws HistoryException {
try {
Executor executor = repository.getHistoryLogExecutor(file, sinceRevision);
int status = executor.exec(true, this);
if (status != 0) {
throw new HistoryException("Failed to get history for: \""
+ file.getAbsolutePath() + "\" Exit code: " + status);
}
} catch (IOException e) {
throw new HistoryException("Failed to get history for: \""
+ file.getAbsolutePath() + "\"", e);
}
return history;
}
/**
* Parse the given string.
*
* @param buffer The string to be parsed
* @return The parsed history
* @throws IOException if we fail to parse the buffer
*/
History parse(String buffer) throws IOException {
processStream(new ByteArrayInputStream(buffer.getBytes(StandardCharsets.UTF_8)));
return history;
}
}
|
history = new History();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuilder total = new StringBuilder(input.available());
String line;
while ((line = in.readLine()) != null) {
total.append(line).append(NEWLINE);
}
ArrayList<HistoryEntry> entries = new ArrayList<>();
HistoryEntry entry = null;
int prevEntryEnd = 0;
long revisionCounter = 0;
Matcher matcher = HISTORY_PATTERN.matcher(total);
while (matcher.find()) {
if (entry != null) {
if (matcher.start() != prevEntryEnd) {
// Get the comment and reduce all double new lines to single
// add a space as well for better formatting in RSS feeds.
entry.appendMessage(total.substring(prevEntryEnd, matcher.start()).replaceAll("(\\r?\\n){2}", " $1").trim());
}
entries.add(0, entry);
entry = null;
}
String revision = matcher.group(4);
String author = matcher.group(3);
String context = matcher.group(2);
String date = matcher.group(5);
long currentRevision = 0;
try {
currentRevision = Long.parseLong(revision);
} catch (NumberFormatException ex) {
LOGGER.log(Level.WARNING, ex, () -> "Failed to parse revision: '" + revision + "'");
}
// We're only interested in history entries that change file content
if (revisionCounter < currentRevision) {
revisionCounter = currentRevision;
entry = new HistoryEntry();
// Add context of action to message. Helps when branch name is used
// as indicator of why promote was made.
if (context != null) {
entry.appendMessage("[" + context + "] ");
}
entry.setAuthor(author);
entry.setRevision(revision);
try {
entry.setDate(repository.parse(date));
} catch (ParseException ex) {
LOGGER.log(Level.WARNING, ex, () -> "Failed to parse date: '" + date + "'");
}
entry.setActive(true);
}
prevEntryEnd = matcher.end();
}
if (entry != null) {
if (total.length() != prevEntryEnd) {
// Get the comment and reduce all double new lines to single
// add a space as well for better formatting in RSS feeds.
entry.appendMessage(total.substring(prevEntryEnd).replaceAll("(\\r?\\n){2}", " $1").trim());
}
entries.add(0, entry);
}
history.setHistoryEntries(entries);
| 775
| 719
| 1,494
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SubversionAnnotationParser.java
|
SubversionAnnotationParser
|
processStream
|
class SubversionAnnotationParser implements Executor.StreamHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SubversionAnnotationParser.class);
/**
* Store annotation created by processStream.
*/
private final Annotation annotation;
private final String fileName;
/**
* @param fileName the name of the file being annotated
*/
public SubversionAnnotationParser(String fileName) {
annotation = new Annotation(fileName);
this.fileName = fileName;
}
/**
* Returns the annotation that has been created.
*
* @return annotation an annotation object
*/
public Annotation getAnnotation() {
return annotation;
}
@Override
public void processStream(InputStream input) throws IOException {<FILL_FUNCTION_BODY>}
private static class AnnotateHandler extends DefaultHandler2 {
String rev;
String author;
final Annotation annotation;
final StringBuilder sb;
AnnotateHandler(String filename, Annotation annotation) {
this.annotation = annotation;
sb = new StringBuilder();
}
@Override
public void startElement(String uri, String localName, String qname,
Attributes attr) {
sb.setLength(0);
if ("entry".equals(qname)) {
rev = null;
author = null;
} else if ("commit".equals(qname)) {
rev = attr.getValue("revision");
}
}
@Override
public void endElement(String uri, String localName, String qname) {
if ("author".equals(qname)) {
author = sb.toString();
} else if ("entry".equals(qname)) {
annotation.addLine(rev, author, true);
}
}
@Override
public void characters(char[] arg0, int arg1, int arg2) {
sb.append(arg0, arg1, arg2);
}
}
}
|
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser;
try {
saxParser = factory.newSAXParser();
saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant
} catch (ParserConfigurationException | SAXException ex) {
throw new IOException("Failed to create SAX parser", ex);
}
AnnotateHandler handler = new AnnotateHandler(fileName, annotation);
try (BufferedInputStream in
= new BufferedInputStream(input)) {
saxParser.parse(in, handler);
} catch (Exception e) {
LOGGER.log(Level.SEVERE,
"An error occurred while parsing the xml output", e);
}
| 501
| 224
| 725
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/SubversionHistoryParser.java
|
Handler
|
initSaxParser
|
class Handler extends DefaultHandler2 {
private static final String COPYFROM_PATH = "copyfrom-path";
/**
* Example of the longest date format that we should accept - SimpleDateFormat cannot cope with micro/nano seconds.
*/
static final int SVN_MILLIS_DATE_LENGTH = "2020-03-26T15:38:55.999Z".length();
final String prefix;
final String home;
final int length;
final List<HistoryEntry> entries = new ArrayList<>();
final Set<String> renamedFiles = new HashSet<>();
final Map<String, String> renamedToDirectoryRevisions = new HashMap<>();
final SubversionRepository repository;
HistoryEntry entry;
StringBuilder sb;
boolean isRenamedFile;
boolean isRenamedDir;
Handler(String home, String prefix, int length, SubversionRepository repository) {
this.home = home;
this.prefix = prefix;
this.length = length;
this.repository = repository;
sb = new StringBuilder();
}
Set<String> getRenamedFiles() {
return renamedFiles;
}
Map<String, String> getRenamedDirectories() {
return renamedToDirectoryRevisions;
}
@Override
public void startElement(String uri, String localName, String qname, Attributes attr) {
isRenamedFile = false;
isRenamedDir = false;
if ("logentry".equals(qname)) {
entry = new HistoryEntry();
entry.setActive(true);
entry.setRevision(attr.getValue("revision"));
} else if ("path".equals(qname) && attr.getIndex(COPYFROM_PATH) != -1) {
LOGGER.log(Level.FINER, "rename for {0}", attr.getValue(COPYFROM_PATH));
if ("dir".equals(attr.getValue("kind"))) {
isRenamedDir = true;
} else {
isRenamedFile = true;
}
}
sb.setLength(0);
}
@Override
public void endElement(String uri, String localName, String qname) throws SAXException {
String s = sb.toString();
if ("author".equals(qname)) {
entry.setAuthor(s);
} else if ("date".equals(qname)) {
try {
// need to strip microseconds off - assume final character is Z otherwise invalid anyway.
String dateString = s;
if (s.length() > SVN_MILLIS_DATE_LENGTH) {
dateString = dateString.substring(0, SVN_MILLIS_DATE_LENGTH - 1) +
dateString.charAt(dateString.length() - 1);
}
entry.setDate(repository.parse(dateString));
} catch (ParseException ex) {
throw new SAXException("Failed to parse date: " + s, ex);
}
} else if ("path".equals(qname)) {
/*
* We only want valid files in the repository, not the
* top-level directory itself, hence the check for inequality.
*/
if (s.startsWith(prefix) && !s.equals(prefix)) {
File file = new File(home, s.substring(prefix.length()));
String path = file.getAbsolutePath().substring(length);
// The same file names may be repeated in many commits,
// so intern them to reduce the memory footprint.
entry.addFile(path.intern());
if (isRenamedFile) {
renamedFiles.add(path.intern());
}
if (isRenamedDir) {
renamedToDirectoryRevisions.put(path.intern(), entry.getRevision());
}
} else {
LOGGER.log(Level.FINER, "Skipping file ''{0}'' outside repository ''{1}''",
new Object[]{s, this.home});
}
} else if ("msg".equals(qname)) {
entry.setMessage(s);
}
if ("logentry".equals(qname)) {
// Avoid adding incomplete history entries.
if (Objects.isNull(entry.getDate())) {
throw new SAXException(String.format("date is null in history entry for revision %s",
Optional.ofNullable(entry.getRevision()).orElse("<unknown>")));
}
entries.add(entry);
}
sb.setLength(0);
}
@Override
public void characters(char[] arg0, int arg1, int arg2) {
sb.append(arg0, arg1, arg2);
}
}
/**
* Initialize the SAX parser instance.
*/
private void initSaxParser() throws HistoryException {<FILL_FUNCTION_BODY>
|
SAXParserFactory factory = SAXParserFactory.newInstance();
saxParser = null;
try {
saxParser = factory.newSAXParser();
saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant
} catch (Exception ex) {
throw new HistoryException("Failed to create SAX parser", ex);
}
| 1,248
| 127
| 1,375
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/history/TagEntry.java
|
TagEntry
|
compareTo
|
class TagEntry implements Comparable<TagEntry> {
private static final String DATE_NULL_ASSERT = "date == null";
/**
* If repo uses linear revision numbering.
*/
protected final int revision;
/**
* If repo does not use linear numbering.
*/
protected final Date date;
/**
* Tag of the revision.
*/
protected String tags;
/**
* Sentinel value for a repo that does not use linear numbering.
*/
protected static final int NOREV = -1;
/**
* Initializes an instance for a repo where revision number is present.
*
* @param revision revision number
* @param tags string representing tags
*/
protected TagEntry(int revision, String tags) {
this.revision = revision;
this.date = null;
this.tags = tags;
}
/**
* Initializes an instance for a repo where revision number is not present
* and {@code date} is used instead.
*
* @param date revision date
* @param tags string representing tags
* @throws IllegalArgumentException if {@code date} is null
*/
protected TagEntry(Date date, String tags) {
if (date == null) {
throw new IllegalArgumentException("`date' is null");
}
this.revision = NOREV;
this.date = date;
this.tags = tags;
}
public String getTags() {
return this.tags;
}
public void setTags(String tag) {
this.tags = tag;
}
public Date getDate() {
return date;
}
/**
* Necessary Comparable method, used for sorting of TagEntries.
*
* @param that Compare to.
* @return 1 for greater, 0 for equal and -1 for smaller objects.
*/
@Override
public int compareTo(TagEntry that) {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object aThat) {
if (this == aThat) {
return true;
}
if (!(aThat instanceof TagEntry)) {
return false;
}
TagEntry that = (TagEntry) aThat;
if (this.revision != NOREV) {
return this.revision == that.revision;
}
assert this.date != null : DATE_NULL_ASSERT;
return this.date.equals(that.date);
}
@Override
public int hashCode() {
if (this.revision != NOREV) {
return this.revision;
}
assert this.date != null : DATE_NULL_ASSERT;
return this.date.hashCode();
}
/**
* Compares to given HistoryEntry, needed for history parsing. Depends on
* specific repository revision format, therefore abstract.
*
* @param aThat HistoryEntry we compare to.
* @return 1 for greater, 0 for equal and -1 for smaller objects.
*/
public abstract int compareTo(HistoryEntry aThat);
}
|
if (this == that) {
return 0;
}
if (this.revision != NOREV) {
return Integer.compare(this.revision, that.revision);
}
assert this.date != null : DATE_NULL_ASSERT;
return this.date.compareTo(that.date);
| 798
| 89
| 887
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/DefaultIndexChangedListener.java
|
DefaultIndexChangedListener
|
fileAdded
|
class DefaultIndexChangedListener implements IndexChangedListener {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultIndexChangedListener.class);
private final Map<String, Statistics> statMap = new ConcurrentHashMap<>();
@Override
public void fileAdd(String path, String analyzer) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Add: ''{0}'' ({1})", new Object[]{path, analyzer});
}
statMap.put(path, new Statistics());
}
@Override
public void fileRemove(String path) {
LOGGER.log(Level.FINE, "Remove: ''{0}''", path);
}
@Override
public void fileAdded(String path, String analyzer) {<FILL_FUNCTION_BODY>}
@Override
public void fileRemoved(String path) {
LOGGER.log(Level.FINER, "Removed: ''{0}''", path);
}
}
|
Statistics stat = statMap.get(path);
if (stat != null) {
boolean loggingDone = stat.report(LOGGER, Level.FINEST, String.format("Added: '%s' (%s)", path, analyzer),
"indexer.file.add.latency");
statMap.remove(path, stat);
// The report() updated the meter, however might not have emitted the log message.
// In such case allow it to fall through to the below log() statement.
if (loggingDone) {
return;
}
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "Added: ''{0}'' ({1})", new Object[]{path, analyzer});
}
| 269
| 201
| 470
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexAnalysisSettings.java
|
IndexAnalysisSettings
|
readObject
|
class IndexAnalysisSettings implements Serializable {
private static final long serialVersionUID = 1172403004716059609L;
private static final ObjectInputFilter serialFilter = new WhitelistObjectInputFilter(IndexAnalysisSettings.class);
private String projectName;
/**
* Nullable to allow easing this object into existing OpenGrok indexes
* without forcing a re-indexing.
* @serial
*/
private Integer tabSize;
/**
* Nullable to allow easing this object into existing OpenGrok indexes
* without forcing a re-indexing.
* @serial
*/
private Long analyzerGuruVersion;
/**
* Nullable because otherwise custom de-serialization does not work, as a
* {@code final} initialized value may not actually happen because Java
* de-serialization circumvents normal construction.
* @serial
*/
private Map<String, Long> analyzersVersions = new HashMap<>();
/**
* Gets the project name to be used to distinguish different instances of
* {@link IndexAnalysisSettings} that might be returned by a Lucene
* {@code MultiReader} search across projects.
* @return projectName
*/
public String getProjectName() {
return projectName;
}
/**
* Sets the project name to be used to distinguish different instances of
* {@link IndexAnalysisSettings} that might be returned by a Lucene
* {@code MultiReader} search across projects.
* @param value project name
*/
public void setProjectName(String value) {
this.projectName = value;
}
public Integer getTabSize() {
return tabSize;
}
public void setTabSize(Integer value) {
this.tabSize = value;
}
public Long getAnalyzerGuruVersion() {
return analyzerGuruVersion;
}
public void setAnalyzerGuruVersion(Long value) {
this.analyzerGuruVersion = value;
}
/**
* Gets the version number for the specified file type name if it exists.
* @param fileTypeName name of the file type
* @return a defined value or {@code null} if unknown
*/
public Long getAnalyzerVersion(String fileTypeName) {
return analyzersVersions.get(fileTypeName);
}
/**
* Gets an unmodifiable view of the map of file type names to version
* numbers.
* @return a defined instance
*/
public Map<String, Long> getAnalyzersVersions() {
return Collections.unmodifiableMap(analyzersVersions);
}
/**
* Replaces the contents of the instance's map with the {@code values}.
* @param values a defined instance
*/
public void setAnalyzersVersions(Map<String, Long> values) {
analyzersVersions.clear();
analyzersVersions.putAll(values);
}
/**
* Creates a binary representation of this object.
* @return a byte array representing this object
* @throws IOException Any exception thrown by the underlying
* OutputStream.
*/
public byte[] serialize() throws IOException {
try (ByteArrayOutputStream bytes = new ByteArrayOutputStream(); var oos = new ObjectOutputStream(bytes)) {
oos.writeObject(this);
return bytes.toByteArray();
}
}
/**
* De-serializes a binary representation of an {@link IndexAnalysisSettings}
* object.
* @param bytes a byte array containing the serialization
* @return a defined instance
* @throws IOException Any of the usual Input/Output related exceptions.
* @throws ClassNotFoundException Class of a serialized object cannot be
* found.
* @throws ClassCastException if the array contains an object of another
* type than {@code IndexAnalysisSettings}
*/
public static IndexAnalysisSettings deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
in.setObjectInputFilter(serialFilter);
return (IndexAnalysisSettings) in.readObject();
}
}
private void readObject(ObjectInputStream in) throws ClassNotFoundException,
IOException {<FILL_FUNCTION_BODY>}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeBoolean(projectName != null); // hasValue
out.writeUTF(projectName == null ? "" : projectName);
out.writeBoolean(tabSize != null); // hasValue
out.writeInt(tabSize == null ? 0 : tabSize);
out.writeBoolean(analyzerGuruVersion != null); // hasValue
out.writeLong(analyzerGuruVersion == null ? 0 : analyzerGuruVersion);
int analyzerCount = analyzersVersions.size();
out.writeInt(analyzerCount);
for (Map.Entry<String, Long> entry : analyzersVersions.entrySet()) {
out.writeUTF(entry.getKey());
out.writeLong(entry.getValue());
--analyzerCount;
}
if (analyzerCount != 0) {
throw new IllegalStateException("analyzersVersions were modified");
}
}
}
|
boolean hasValue = in.readBoolean();
String vstring = in.readUTF();
projectName = hasValue ? vstring : null;
hasValue = in.readBoolean();
int vint = in.readInt();
tabSize = hasValue ? vint : null;
hasValue = in.readBoolean();
long vlong = in.readLong();
analyzerGuruVersion = hasValue ? vlong : null;
/*
De-serialization circumvents normal construction, so the following
field could be null.
*/
if (analyzersVersions == null) {
analyzersVersions = new HashMap<>();
}
int analyzerCount = in.readInt();
for (int i = 0; i < analyzerCount; ++i) {
vstring = in.readUTF();
vlong = in.readLong();
analyzersVersions.put(vstring, vlong);
}
| 1,330
| 238
| 1,568
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexAnalysisSettingsAccessor.java
|
IndexAnalysisSettingsAccessor
|
read
|
class IndexAnalysisSettingsAccessor {
/**
* The {@link QueryBuilder}-normalized value for UUID 58859C75-F941-42E5-8D1A-FAF71DDEBBA7.
*/
static final String INDEX_ANALYSIS_SETTINGS_OBJUID = "uthuslvotkgltggqqjmurqojpjpjjkutkujktnkk";
private static final int INDEX_ANALYSIS_SETTINGS_OBJVER = 3;
/**
* Searches for a document with a {@link QueryBuilder#OBJUID} value matching
* {@link #INDEX_ANALYSIS_SETTINGS_OBJUID}. The first document found is
* returned, so this should not be called with a MultiReader.
* @param reader a defined instance
* @return a defined instance or {@code null} if none could be found
* @throws IOException if I/O error occurs while searching Lucene
*/
public IndexAnalysisSettings3 read(IndexReader reader) throws IOException {
IndexAnalysisSettings3[] res = read(reader, 1);
return res.length > 0 ? res[0] : null;
}
/**
* Searches for documents with a {@link QueryBuilder#OBJUID} value matching
* {@link #INDEX_ANALYSIS_SETTINGS_OBJUID}.
* @param reader a defined instance
* @param n a limit to the number of documents returned. The method may
* return less.
* @return a defined instance, which is empty if none could be found
* @throws IOException if I/O error occurs while searching Lucene
*/
public IndexAnalysisSettings3[] read(IndexReader reader, int n) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Writes a document to contain the serialized version of {@code settings},
* with a {@link QueryBuilder#OBJUID} value set to
* {@link #INDEX_ANALYSIS_SETTINGS_OBJUID}. An existing version of the
* document is first deleted.
* @param writer a defined, target instance
* @param settings a defined instance
* @throws IOException if I/O error occurs while writing Lucene
*/
public void write(IndexWriter writer, IndexAnalysisSettings3 settings)
throws IOException {
byte[] objser = settings.serialize();
writer.deleteDocuments(new Term(QueryBuilder.OBJUID,
INDEX_ANALYSIS_SETTINGS_OBJUID));
Document doc = new Document();
StringField uidfield = new StringField(QueryBuilder.OBJUID,
INDEX_ANALYSIS_SETTINGS_OBJUID, Field.Store.NO);
doc.add(uidfield);
doc.add(new StoredField(QueryBuilder.OBJSER, objser));
doc.add(new StoredField(QueryBuilder.OBJVER,
INDEX_ANALYSIS_SETTINGS_OBJVER));
writer.addDocument(doc);
}
private int readObjectVersion(Document doc) {
IndexableField objver = doc.getField(QueryBuilder.OBJVER);
return objver == null ? 1 : objver.numericValue().intValue();
}
}
|
IndexSearcher searcher = RuntimeEnvironment.getInstance().getIndexSearcherFactory().newSearcher(reader);
Query q;
try {
q = new QueryParser(QueryBuilder.OBJUID, new CompatibleAnalyser()).
parse(INDEX_ANALYSIS_SETTINGS_OBJUID);
} catch (ParseException ex) {
// This is not expected, so translate to RuntimeException.
throw new RuntimeException(ex);
}
TopDocs top = searcher.search(q, n);
int nres = top.totalHits.value > n ? n : (int) top.totalHits.value;
IndexAnalysisSettings3[] res = new IndexAnalysisSettings3[nres];
IndexAnalysisSettingsUpgrader upgrader = new IndexAnalysisSettingsUpgrader();
StoredFields storedFields = searcher.storedFields();
for (int i = 0; i < nres; ++i) {
Document doc = storedFields.document(top.scoreDocs[i].doc);
IndexableField objser = doc.getField(QueryBuilder.OBJSER);
int objver = readObjectVersion(doc);
try {
res[i] = objser == null ? null : upgrader.upgrade(
objser.binaryValue().bytes, objver);
} catch (ClassNotFoundException ex) {
// This is not expected, so translate to RuntimeException.
throw new RuntimeException(ex);
}
}
return res;
| 813
| 370
| 1,183
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexAnalysisSettingsUpgrader.java
|
IndexAnalysisSettingsUpgrader
|
convertFromV2
|
class IndexAnalysisSettingsUpgrader {
/**
* De-serialize the specified {@code bytes}, and upgrade if necessary from
* an older version to the current object version which is
* {@link IndexAnalysisSettings3}.
* @param bytes a defined instance
* @param objectVersion a value greater than or equal to 1
* @return a defined instance
* @throws ClassNotFoundException if class of a serialized object cannot be
* found
* @throws IOException if any of the usual Input/Output related exceptions
*/
public IndexAnalysisSettings3 upgrade(byte[] bytes, int objectVersion)
throws ClassNotFoundException, IOException {
switch (objectVersion) {
case 1:
throw new IOException("Too old version " + objectVersion);
case 2:
IndexAnalysisSettings old2 = IndexAnalysisSettings.deserialize(bytes);
return convertFromV2(old2);
case 3:
return IndexAnalysisSettings3.deserialize(bytes);
default:
throw new IllegalArgumentException("Unknown version " + objectVersion);
}
}
private IndexAnalysisSettings3 convertFromV2(IndexAnalysisSettings old2) {<FILL_FUNCTION_BODY>}
}
|
IndexAnalysisSettings3 res = new IndexAnalysisSettings3();
res.setAnalyzerGuruVersion(old2.getAnalyzerGuruVersion());
res.setAnalyzersVersions(old2.getAnalyzersVersions());
res.setProjectName(old2.getProjectName());
res.setTabSize(old2.getTabSize());
// Version 2 has no indexedSymlinks, so nothing more to do.
return res;
| 295
| 113
| 408
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexDocumentException.java
|
IndexDocumentException
|
toString
|
class IndexDocumentException extends IndexCheckException {
private static final long serialVersionUID = -277429315137557112L;
private final Map<Path, Integer> duplicatePathMap;
private final Set<Path> missingPaths;
public IndexDocumentException(String s, Path path) {
super(s, path);
this.duplicatePathMap = null;
this.missingPaths = null;
}
public IndexDocumentException(String message, Path indexPath, Map<Path, Integer> duplicateFileMap, Set<Path> missingPaths) {
super(message, indexPath);
this.duplicatePathMap = duplicateFileMap;
this.missingPaths = missingPaths;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(getMessage());
stringBuilder.append(":");
if (!duplicatePathMap.isEmpty()) {
stringBuilder.append(" duplicate paths = ");
stringBuilder.append(duplicatePathMap);
}
if (!missingPaths.isEmpty()) {
stringBuilder.append(" missing paths = ");
stringBuilder.append(missingPaths);
}
return stringBuilder.toString();
| 215
| 116
| 331
|
<methods>public void <init>(java.lang.String, java.nio.file.Path) ,public void <init>(java.lang.String, Set<java.nio.file.Path>) ,public void <init>(java.lang.Exception) ,public Set<java.nio.file.Path> getFailedPaths() <variables>private final Set<java.nio.file.Path> failedPaths,private static final long serialVersionUID
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexVersionException.java
|
IndexVersionException
|
toString
|
class IndexVersionException extends IndexCheckException {
private static final long serialVersionUID = 5693446916108385595L;
private final int luceneIndexVersion;
private final int indexVersion;
public IndexVersionException(String message, Path path, int luceneIndexVersion, int indexVersion) {
super(message, path);
this.indexVersion = indexVersion;
this.luceneIndexVersion = luceneIndexVersion;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getMessage() + ": " + String.format("Lucene version = %d", luceneIndexVersion) + ", " +
String.format("index version = %d", indexVersion);
| 148
| 49
| 197
|
<methods>public void <init>(java.lang.String, java.nio.file.Path) ,public void <init>(java.lang.String, Set<java.nio.file.Path>) ,public void <init>(java.lang.Exception) ,public Set<java.nio.file.Path> getFailedPaths() <variables>private final Set<java.nio.file.Path> failedPaths,private static final long serialVersionUID
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexWriterConfigFactory.java
|
IndexWriterConfigFactory
|
get
|
class IndexWriterConfigFactory {
IndexWriterConfigFactory() {
}
public IndexWriterConfig get() {<FILL_FUNCTION_BODY>}
}
|
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
Analyzer analyzer = AnalyzerGuru.getAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
iwc.setRAMBufferSizeMB(env.getRamBufferSize());
return iwc;
| 43
| 100
| 143
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexedSymlink.java
|
IndexedSymlink
|
hashCode
|
class IndexedSymlink {
private final String absolute;
private final String canonical;
private final boolean isLocal;
private final String canonicalSeparated;
/**
* Initializes an instance with the required arguments.
* @param absolute a defined instance
* @param canonical a defined instance
* @param isLocal a value indicating if the symlink was local to a project.
*/
IndexedSymlink(String absolute, String canonical, boolean isLocal) {
if (absolute == null) {
throw new IllegalArgumentException("absolute is null");
}
if (canonical == null) {
throw new IllegalArgumentException("canonical is null");
}
this.absolute = absolute;
this.canonical = canonical;
this.isLocal = isLocal;
this.canonicalSeparated = canonical + File.separator;
}
public String getAbsolute() {
return absolute;
}
public String getCanonical() {
return canonical;
}
public boolean isLocal() {
return isLocal;
}
/**
* Gets the value of {@link #getCanonical()} with a {@link File#separator}
* appended.
* @return a defined instance
*/
public String getCanonicalSeparated() {
return canonicalSeparated;
}
/**
* Compares {@link #getAbsolute()}, {@link #getCanonical()}, and
* {@link #isLocal()} to determine equality. (Generated by IntelliJ.)
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IndexedSymlink that = (IndexedSymlink) o;
if (isLocal != that.isLocal) {
return false;
}
if (!absolute.equals(that.absolute)) {
return false;
}
return canonical.equals(that.canonical);
}
/**
* Gets a hashcode derived from {@link #getAbsolute()},
* {@link #getCanonical()}, and {@link #isLocal()}. (Generated by IntelliJ.)
*/
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
}
|
int result = absolute.hashCode();
result = 31 * result + canonical.hashCode();
result = 31 * result + (isLocal ? 1 : 0);
return result;
| 594
| 51
| 645
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/IndexerUtil.java
|
IndexerUtil
|
enableProjects
|
class IndexerUtil {
private IndexerUtil() {
}
/**
* @return map of HTTP headers to use when making API requests to the web application
*/
public static MultivaluedMap<String, Object> getWebAppHeaders() {
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
String token;
if ((token = RuntimeEnvironment.getInstance().getIndexerAuthenticationToken()) != null) {
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
}
return headers;
}
/**
* Enable projects in the remote host application.
* <p>
* NOTE: performs a check if the projects are already enabled,
* before making the change request
*
* @param host the url to the remote host
* @throws ResponseProcessingException in case processing of a received HTTP response fails
* @throws ProcessingException in case the request processing or subsequent I/O operation fails
* @throws WebApplicationException in case the response status code of the response returned by the server is not successful
*/
public static void enableProjects(final String host) throws
ResponseProcessingException,
ProcessingException,
WebApplicationException {<FILL_FUNCTION_BODY>}
}
|
try (Client client = ClientBuilder.newBuilder().
connectTimeout(RuntimeEnvironment.getInstance().getConnectTimeout(), TimeUnit.SECONDS).build()) {
final Invocation.Builder request = client.target(host)
.path("api")
.path("v1")
.path("configuration")
.path("projectsEnabled")
.request()
.headers(getWebAppHeaders());
final String enabled = request.get(String.class);
if (!Boolean.parseBoolean(enabled)) {
try (Response r = request.put(Entity.text(Boolean.TRUE.toString()))) {
if (r.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new WebApplicationException(String.format("Unable to enable projects: %s",
r.getStatusInfo().getReasonPhrase()), r.getStatus());
}
}
}
}
| 319
| 230
| 549
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/NumLinesLOCAccessor.java
|
NumLinesLOCAccessor
|
storeBulk
|
class NumLinesLOCAccessor {
private static final int BULK_READ_THRESHOLD = 100;
/**
* Determines whether there is stored number-of-lines and lines-of-code
* in the index associated to the specified {@code reader}.
*/
public boolean hasStored(IndexReader reader) throws IOException {
DSearchResult searchResult = newDSearch(reader, 1);
return searchResult.hits.totalHits.value > 0;
}
/**
* Stores the net deltas to the index through the specified {@code writer}.
*/
public void store(IndexWriter writer, IndexReader reader,
NumLinesLOCAggregator countsAggregator, boolean isAggregatingDeltas)
throws IOException {
List<AccumulatedNumLinesLOC> counts = new ArrayList<>();
countsAggregator.iterator().forEachRemaining(counts::add);
if (counts.size() >= BULK_READ_THRESHOLD) {
storeBulk(writer, reader, counts, isAggregatingDeltas);
} else if (!counts.isEmpty()) {
storeIterative(writer, reader, counts, isAggregatingDeltas);
}
}
/**
* Queries the stored counts from the specified reader to register them to
* the specified aggregator.
* @return a value indicating whether any defined number-of-lines and
* lines-of-code were found
*/
public boolean register(NumLinesLOCAggregator countsAggregator, IndexReader reader) throws IOException {
/*
* Search for existing documents with any value of PATH. Those are
* documents representing source code files, as opposed to source code
* directories or other object data (e.g. IndexAnalysisSettings3), which
* have no stored PATH.
*/
IndexSearcher searcher = RuntimeEnvironment.getInstance().getIndexSearcherFactory().newSearcher(reader);
Query query;
try {
QueryParser parser = new QueryParser(QueryBuilder.PATH, new CompatibleAnalyser());
parser.setAllowLeadingWildcard(true);
query = parser.parse("*");
} catch (ParseException ex) {
// This is not expected, so translate to RuntimeException.
throw new RuntimeException(ex);
}
TopDocs hits = searcher.search(query, Integer.MAX_VALUE);
return processFileCounts(countsAggregator, searcher, hits);
}
private void storeBulk(IndexWriter writer, IndexReader reader,
List<AccumulatedNumLinesLOC> counts, boolean isAggregatingDeltas) throws IOException {<FILL_FUNCTION_BODY>}
private void storeIterative(IndexWriter writer, IndexReader reader,
List<AccumulatedNumLinesLOC> counts, boolean isAggregatingDeltas) throws IOException {
// Search for existing documents with QueryBuilder.D.
IndexSearcher searcher = RuntimeEnvironment.getInstance().getIndexSearcherFactory().newSearcher(reader);
for (AccumulatedNumLinesLOC entry : counts) {
Query query = new TermQuery(new Term(QueryBuilder.D, entry.getPath()));
TopDocs hits = searcher.search(query, 1);
Integer docID = null;
if (hits.totalHits.value > 0) {
docID = hits.scoreDocs[0].doc;
}
updateDocumentData(writer, searcher, entry, docID, isAggregatingDeltas);
}
}
private void updateDocumentData(IndexWriter writer, IndexSearcher searcher,
AccumulatedNumLinesLOC aggregate, Integer docID, boolean isAggregatingDeltas)
throws IOException {
File pathFile = new File(aggregate.getPath());
String parent = pathFile.getParent();
if (parent == null) {
parent = "";
}
String normalizedPath = QueryBuilder.normalizeDirPath(parent);
long extantLOC = 0;
long extantLines = 0;
if (docID != null) {
Document doc = searcher.storedFields().document(docID);
if (isAggregatingDeltas) {
extantLines = NumberUtils.toLong(doc.get(QueryBuilder.NUML));
extantLOC = NumberUtils.toLong(doc.get(QueryBuilder.LOC));
}
writer.deleteDocuments(new Term(QueryBuilder.D, aggregate.getPath()));
}
long newNumLines = extantLines + aggregate.getNumLines();
long newLOC = extantLOC + aggregate.getLOC();
Document doc = new Document();
doc.add(new StringField(QueryBuilder.D, aggregate.getPath(), Field.Store.YES));
doc.add(new StringField(QueryBuilder.DIRPATH, normalizedPath, Field.Store.NO));
doc.add(new StoredField(QueryBuilder.NUML, newNumLines));
doc.add(new StoredField(QueryBuilder.LOC, newLOC));
writer.addDocument(doc);
}
private boolean processFileCounts(NumLinesLOCAggregator countsAggregator,
IndexSearcher searcher, TopDocs hits) throws IOException {
boolean hasDefinedNumLines = false;
StoredFields storedFields = searcher.storedFields();
for (ScoreDoc sd : hits.scoreDocs) {
Document d = storedFields.document(sd.doc);
NullableNumLinesLOC counts = NumLinesLOCUtil.read(d);
if (counts.getNumLines() != null && counts.getLOC() != null) {
NumLinesLOC defCounts = new NumLinesLOC(counts.getPath(),
counts.getNumLines(), counts.getLOC());
countsAggregator.register(defCounts);
hasDefinedNumLines = true;
}
}
return hasDefinedNumLines;
}
private DSearchResult newDSearch(IndexReader reader, int n) throws IOException {
// Search for existing documents with QueryBuilder.D.
IndexSearcher searcher = RuntimeEnvironment.getInstance().getIndexSearcherFactory().newSearcher(reader);
Query query;
try {
QueryParser parser = new QueryParser(QueryBuilder.D, new CompatibleAnalyser());
parser.setAllowLeadingWildcard(true);
query = parser.parse("*");
} catch (ParseException ex) {
// This is not expected, so translate to RuntimeException.
throw new RuntimeException(ex);
}
TopDocs topDocs = searcher.search(query, n);
return new DSearchResult(searcher, topDocs);
}
private static class DSearchResult {
private final IndexSearcher searcher;
private final TopDocs hits;
DSearchResult(IndexSearcher searcher, TopDocs hits) {
this.searcher = searcher;
this.hits = hits;
}
}
}
|
DSearchResult searchResult = newDSearch(reader, Integer.MAX_VALUE);
// Index the existing document IDs by QueryBuilder.D.
HashMap<String, Integer> byDir = new HashMap<>();
int intMaximum = Integer.MAX_VALUE < searchResult.hits.totalHits.value ?
Integer.MAX_VALUE : (int) searchResult.hits.totalHits.value;
StoredFields storedFields = searchResult.searcher.storedFields();
for (int i = 0; i < intMaximum; ++i) {
int docID = searchResult.hits.scoreDocs[i].doc;
Document doc = storedFields.document(docID);
String dirPath = doc.get(QueryBuilder.D);
byDir.put(dirPath, docID);
}
for (AccumulatedNumLinesLOC entry : counts) {
Integer docID = byDir.get(entry.getPath());
updateDocumentData(writer, searchResult.searcher, entry, docID, isAggregatingDeltas);
}
| 1,761
| 268
| 2,029
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/NumLinesLOCAggregator.java
|
NumLinesLOCAggregator
|
register
|
class NumLinesLOCAggregator {
private final Object syncRoot = new Object();
private final HashMap<String, DeltaData> registeredDeltas = new HashMap<>();
/**
* Gets an iterator over all registered data, explicit and derived, and not
* ordered.
* @return a defined instance
*/
public Iterator<AccumulatedNumLinesLOC> iterator() {
return new AccumulationsIterator(registeredDeltas.entrySet().iterator());
}
/**
* Registers the specified counts. Values should be negative when deleting a
* file or when updating a file's analysis to reverse former values before
* re-registering.
* @param counts {@link NumLinesLOC} instance
*/
public void register(NumLinesLOC counts) {<FILL_FUNCTION_BODY>}
private static class DeltaData {
long numLines;
long loc;
}
private static class AccumulationsIterator implements Iterator<AccumulatedNumLinesLOC> {
private final Iterator<Map.Entry<String, DeltaData>> underlying;
AccumulationsIterator(Iterator<Map.Entry<String, DeltaData>> underlying) {
this.underlying = underlying;
}
@Override
public boolean hasNext() {
return underlying.hasNext();
}
@Override
public AccumulatedNumLinesLOC next() {
Map.Entry<String, DeltaData> underlyingNext = underlying.next();
String path = underlyingNext.getKey();
DeltaData values = underlyingNext.getValue();
return new AccumulatedNumLinesLOCImpl(path, values.numLines, values.loc);
}
}
private static class AccumulatedNumLinesLOCImpl implements AccumulatedNumLinesLOC {
private final String path;
private final long numLines;
private final long loc;
AccumulatedNumLinesLOCImpl(String path, long numLines, long loc) {
this.path = path;
this.numLines = numLines;
this.loc = loc;
}
@Override
public String getPath() {
return path;
}
@Override
public long getNumLines() {
return numLines;
}
@Override
public long getLOC() {
return loc;
}
}
}
|
File file = new File(counts.getPath());
File directory = file.getParentFile();
if (directory != null) {
synchronized (syncRoot) {
do {
String dirPath = Util.fixPathIfWindows(directory.getPath());
var extantDelta = registeredDeltas.computeIfAbsent(dirPath,
key -> new DeltaData());
extantDelta.numLines += counts.getNumLines();
extantDelta.loc += counts.getLOC();
} while ((directory = directory.getParentFile()) != null &&
!directory.getPath().isEmpty());
}
}
| 603
| 162
| 765
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/NumLinesLOCUtil.java
|
NumLinesLOCUtil
|
read
|
class NumLinesLOCUtil {
/**
* Reads data, if they exist, from the specified document.
* @param doc {@link Document} instance
* @return a defined instance
*/
public static NullableNumLinesLOC read(Document doc) {<FILL_FUNCTION_BODY>}
/* private to enforce static */
private NumLinesLOCUtil() {
}
}
|
String path = doc.get(QueryBuilder.D);
if (path == null) {
path = doc.get(QueryBuilder.PATH);
}
Long numLines = NumberUtil.tryParseLong(doc.get(QueryBuilder.NUML));
Long loc = NumberUtil.tryParseLong(doc.get(QueryBuilder.LOC));
return new NullableNumLinesLOC(path, numLines, loc);
| 102
| 107
| 209
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/PendingFileDeletion.java
|
PendingFileDeletion
|
equals
|
class PendingFileDeletion {
private final String absolutePath;
public PendingFileDeletion(String absolutePath) {
this.absolutePath = absolutePath;
}
/**
* @return the absolute path
*/
public String getAbsolutePath() {
return absolutePath;
}
/**
* Compares {@code absolutePath} to the other object's value.
* @param o other object for comparison
* @return {@code true} if the two compared objects are identical;
* otherwise false
*/
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return this.absolutePath.hashCode();
}
}
|
if (!(o instanceof PendingFileDeletion)) {
return false;
}
PendingFileDeletion other = (PendingFileDeletion) o;
return this.absolutePath.equals(other.absolutePath);
| 194
| 63
| 257
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/PendingFileRenaming.java
|
PendingFileRenaming
|
equals
|
class PendingFileRenaming {
private final String absolutePath;
private final String transientPath;
public PendingFileRenaming(String absolutePath, String transientPath) {
this.absolutePath = absolutePath;
this.transientPath = transientPath;
}
/**
* @return the final, absolute path
*/
public String getAbsolutePath() {
return absolutePath;
}
/**
* @return the transient, absolute path
*/
public String getTransientPath() {
return transientPath;
}
/**
* Compares {@code absolutePath} to the other object's value.
* @param o other object for comparison
* @return {@code true} if the two compared objects are identical;
* otherwise false
*/
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return this.absolutePath.hashCode();
}
}
|
if (!(o instanceof PendingFileRenaming)) {
return false;
}
PendingFileRenaming other = (PendingFileRenaming) o;
return this.absolutePath.equals(other.absolutePath);
| 255
| 63
| 318
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/index/PendingSymlinkage.java
|
PendingSymlinkage
|
equals
|
class PendingSymlinkage {
private final String sourcePath;
private final String targetRelPath;
public PendingSymlinkage(String sourcePath, String targetRelPath) {
this.sourcePath = sourcePath;
this.targetRelPath = targetRelPath;
}
/**
* @return the source, absolute path
*/
public String getSourcePath() {
return sourcePath;
}
/**
* @return the target, relative path
*/
public String getTargetRelPath() {
return targetRelPath;
}
/**
* Compares {@code sourcePath} to the other object's value.
* @param o other object for comparison
* @return {@code true} if the two compared objects are identical;
* otherwise false
*/
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return this.sourcePath.hashCode();
}
}
|
if (!(o instanceof PendingSymlinkage)) {
return false;
}
PendingSymlinkage other = (PendingSymlinkage) o;
return this.sourcePath.equals(other.sourcePath);
| 254
| 58
| 312
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/logger/formatter/LogFormatter.java
|
LogFormatter
|
format
|
class LogFormatter extends Formatter {
private static final String DEFAULT_FORMAT = "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n";
private final String format;
private final String version;
public LogFormatter() {
this(DEFAULT_FORMAT, "unknown");
}
public LogFormatter(String format, String version) {
this.format = format;
this.version = version;
}
@Override
@SuppressWarnings("deprecation")
public String format(LogRecord logRecord) {<FILL_FUNCTION_BODY>}
private String className(String className) {
return className.substring(className.lastIndexOf('.') + 1);
}
}
|
Date dat = new Date(logRecord.getMillis());
StringBuilder source = new StringBuilder();
if (logRecord.getSourceClassName() != null) {
source.append(logRecord.getSourceClassName());
if (logRecord.getSourceMethodName() != null) {
source.append(' ').append(logRecord.getSourceMethodName());
}
} else {
source.append(logRecord.getLoggerName());
}
StringBuilder throwable = new StringBuilder();
if (logRecord.getThrown() != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println();
logRecord.getThrown().printStackTrace(pw);
pw.close();
throwable.append(sw.toString());
}
return String.format(format,
dat, //%1
source.toString(), //%2
logRecord.getLoggerName(), //%3
logRecord.getLevel().getLocalizedName(), //%4
formatMessage(logRecord), //%5
throwable, //%6 (till here the same as JDK7's SimpleFormatter)
logRecord.getSourceClassName(), //%7
logRecord.getSourceMethodName(), //%8
className(logRecord.getSourceClassName()), //%9
logRecord.getThreadID(), //%10
logRecord.getMessage(), //%11
version
);
| 225
| 383
| 608
|
<methods>public abstract java.lang.String format(java.util.logging.LogRecord) ,public java.lang.String formatMessage(java.util.logging.LogRecord) ,public java.lang.String getHead(java.util.logging.Handler) ,public java.lang.String getTail(java.util.logging.Handler) <variables>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/CustomQueryParser.java
|
CustomQueryParser
|
isCaseSensitive
|
class CustomQueryParser extends QueryParser {
/**
* Create a query parser customized for OpenGrok.
*
* @param field default field for unqualified query terms
*/
public CustomQueryParser(String field) {
super(field, new CompatibleAnalyser());
setDefaultOperator(AND_OPERATOR);
setAllowLeadingWildcard(
RuntimeEnvironment.getInstance().isAllowLeadingWildcard());
// Convert terms to lower case manually to prevent changing the case
// if the field is case sensitive.
// since lucene 7.0.0 below is in place so every class that
// extends Analyser must normalize the text by itself
/*
## AnalyzingQueryParser removed (LUCENE-7355)
The functionality of AnalyzingQueryParser has been folded into the classic
QueryParser, which now passes terms through Analyzer#normalize when generating
queries.
## CommonQueryParserConfiguration.setLowerCaseExpandedTerms removed (LUCENE-7355)
Expanded terms are now normalized through
Analyzer#normalize.
*/
}
/**
* Is this field case sensitive?
*
* @param field name of the field to check
* @return {@code true} if the field is case sensitive, {@code false}
* otherwise
*/
protected static boolean isCaseSensitive(String field) {<FILL_FUNCTION_BODY>}
/**
* Get a canonical form of a search term. This will convert the term to
* lower case if the field is case insensitive.
*
* @param field the field to search on
* @param term the term to search for
* @return the canonical form of the search term, which matches how it is
* stored in the index
*/
// The analyzers use the default locale. They probably should have used
// a fixed locale, but since they don't, we ignore that PMD warning here.
@SuppressWarnings("PMD.UseLocaleWithCaseConversions")
private static String getCanonicalTerm(String field, String term) {
return isCaseSensitive(field) ? term : term.toLowerCase(Locale.ROOT);
}
// Override the get***Query() methods to lower case the search terms if
// the field is case sensitive. We don't need to override getFieldQuery()
// because it uses the analyzer to convert the terms to canonical form.
@Override
protected Query getFuzzyQuery(String field, String term, float min)
throws ParseException {
return super.getFuzzyQuery(field, getCanonicalTerm(field, term), min);
}
@Override
protected Query getPrefixQuery(String field, String term)
throws ParseException {
return super.getPrefixQuery(field, getCanonicalTerm(field, term));
}
@Override
protected Query getRangeQuery(String field, String term1, String term2,
boolean startinclusive, boolean endinclusive)
throws ParseException {
return super.getRangeQuery(
field,
getCanonicalTerm(field, term1),
getCanonicalTerm(field, term2),
startinclusive,
endinclusive);
}
@Override
protected Query getWildcardQuery(String field, String term)
throws ParseException {
return super.getWildcardQuery(field, getCanonicalTerm(field, term));
}
}
|
// Only definition search and reference search are case sensitive
return QueryBuilder.DEFS.equals(field)
|| QueryBuilder.REFS.equals(field);
| 860
| 41
| 901
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/DirectoryExtraReader.java
|
DirectoryExtraReader
|
search
|
class DirectoryExtraReader {
// N.b.: update #search() comment when changing
private static final int DIR_LIMIT_NUM = 2000;
private static final Logger LOGGER = LoggerFactory.getLogger(
DirectoryExtraReader.class);
/**
* Search for supplemental file information in the specified {@code path}.
* @param searcher a defined instance
* @param path a defined path to qualify the search
* @return a list of results, limited to 2000 values
* @throws IOException if an error occurs searching the index
*/
public List<NullableNumLinesLOC> search(IndexSearcher searcher, String path) throws IOException {<FILL_FUNCTION_BODY>}
private List<NullableNumLinesLOC> processHits(IndexSearcher searcher, TopDocs hits)
throws IOException {
List<NullableNumLinesLOC> results = new ArrayList<>();
StoredFields storedFields = searcher.storedFields();
for (ScoreDoc sd : hits.scoreDocs) {
Document d = storedFields.document(sd.doc);
NullableNumLinesLOC extra = NumLinesLOCUtil.read(d);
results.add(extra);
}
return results;
}
}
|
if (searcher == null) {
throw new IllegalArgumentException("`searcher' is null");
}
if (path == null) {
throw new IllegalArgumentException("`path' is null");
}
QueryBuilder qbuild = new QueryBuilder();
qbuild.setDirPath(path);
Query query;
try {
query = qbuild.build();
} catch (ParseException e) {
final String PARSE_ERROR =
"An error occurred while parsing dirpath query";
LOGGER.log(Level.WARNING, PARSE_ERROR, e);
throw new IOException(PARSE_ERROR);
}
Statistics stat = new Statistics();
TopDocs hits = searcher.search(query, DIR_LIMIT_NUM);
stat.report(LOGGER, Level.FINEST, "search via DirectoryExtraReader done",
"search.latency", new String[]{"category", "extra",
"outcome", hits.scoreDocs.length > 0 ? "success" : "empty"});
return processHits(searcher, hits);
| 319
| 271
| 590
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/Hit.java
|
Hit
|
equals
|
class Hit implements Comparable<Hit> {
/**
* Holds value of property filename.
*/
private String filename;
/**
* Holds value of property directory.
*/
private String directory;
/**
* Holds value of property line.
*/
private String line;
/**
* Holds value of property line no.
*/
private String lineno;
/**
* Holds value of property binary.
*/
private boolean binary;
/**
* Holds value of property alt used to highlight alternating files.
*/
private final boolean alt;
/**
* path relative to source root.
*/
private String path;
/**
* Creates a new instance of Hit.
*/
public Hit() {
this(null, null, null, false, false);
}
/**
* Creates a new instance of Hit.
*
* @param filename The name of the file this hit represents
* @param line The line containing the match
* @param lineno The line number in the file the match was found
* @param binary If this is a binary file or not
* @param alt Is this the "alternate" file
*/
public Hit(String filename, String line, String lineno, boolean binary, boolean alt) {
if (filename != null) {
File file = new File(filename);
this.path = filename;
this.filename = file.getName();
this.directory = file.getParent();
if (directory == null) {
directory = "";
}
}
this.line = line;
this.lineno = lineno;
this.binary = binary;
this.alt = alt;
}
/**
* Getter for property filename.
*
* @return Value of property filename.
*/
public String getFilename() {
return this.filename;
}
/**
* Getter for property path.
*
* @return Value of property path.
*/
public String getPath() {
return this.path;
}
/**
* Getter for property directory.
*
* @return Value of property directory
*/
public String getDirectory() {
return this.directory;
}
/**
* Setter for property filename.
*
* @param filename New value of property filename.
*/
public void setFilename(String filename) {
this.filename = filename;
}
/**
* Getter for property line.
*
* @return Value of property line.
*/
public String getLine() {
return this.line;
}
/**
* Setter for property line.
*
* @param line New value of property line.
*/
public void setLine(String line) {
this.line = line;
}
/**
* Getter for property line no.
*
* @return Value of property line no.
*/
public String getLineno() {
return this.lineno;
}
/**
* Setter for property line no.
*
* @param lineno New value of property line no.
*/
public void setLineno(String lineno) {
this.lineno = lineno;
}
/**
* Compare this object to another hit (in order to implement the comparable interface).
*
* @param o The object to compare this object with
*
* @return the result of a toString().compareTo() of the filename
*/
@Override
public int compareTo(Hit o) throws ClassCastException {
return filename.compareTo(o.filename);
}
/**
* Getter for property binary.
*
* @return Value of property binary.
*/
public boolean isBinary() {
return this.binary;
}
/**
* Setter for property binary.
*
* @param binary New value of property binary.
*/
public void setBinary(boolean binary) {
this.binary = binary;
}
/**
* Holds value of property tag.
*/
private String tag;
/**
* Getter for property tag.
* @return Value of property tag.
*/
public String getTag() {
return this.tag;
}
/**
* Setter for property tag.
* @param tag New value of property tag.
*/
public void setTag(String tag) {
this.tag = tag;
}
/**
* Should this be alternate file?
* @return true if this is the "alternate" file
*/
public boolean getAlt() {
return alt;
}
/**
* Check if two objects are equal. Only consider the {@code filename} field
* to match the return value of the {@link #compareTo(Hit)} method.
* @param o the object to compare with
* @return true if the filenames are equal
*/
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return filename.hashCode();
}
}
|
if (o instanceof Hit) {
return compareTo((Hit) o) == 0;
}
return false;
| 1,328
| 33
| 1,361
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/SettingsHelper.java
|
SettingsHelper
|
getTabSize
|
class SettingsHelper {
private final IndexReader reader;
/**
* Key is Project name or empty string for null Project.
*/
private Map<String, IndexAnalysisSettings3> mappedAnalysisSettings;
/**
* Key is Project name or empty string for null Project. Map is ordered by
* canonical length (ASC) and then canonical value (ASC).
*/
private Map<String, Map<String, IndexedSymlink>> mappedIndexedSymlinks;
public SettingsHelper(IndexReader reader) {
if (reader == null) {
throw new IllegalArgumentException("reader is null");
}
this.reader = reader;
}
/**
* Gets any mapped symlinks (after having called {@link #getSettings(String)}).
* @return either a defined map or {@code null}
*/
public Map<String, IndexedSymlink> getSymlinks(String projectName) throws IOException {
getSettings(projectName);
String projectKey = projectName != null ? projectName : "";
Map<String, IndexedSymlink> indexSymlinks = mappedIndexedSymlinks.get(projectKey);
return Optional.ofNullable(indexSymlinks)
.map(Collections::unmodifiableMap)
.orElseGet(Collections::emptyMap);
}
/**
* Gets the persisted tabSize via {@link #getSettings(String)} if
* available or returns the {@code proj} tabSize if available -- or zero.
* @param proj a defined instance or {@code null} if no project is active
* @return tabSize
* @throws IOException if an I/O error occurs querying the initialized
* reader
*/
public int getTabSize(Project proj) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Gets the settings for a specified project.
* @param projectName a defined instance or {@code null} if no project is
* active (or empty string to mean the same thing)
* @return a defined instance or {@code null} if none is found
* @throws IOException if an I/O error occurs querying the initialized reader
*/
public IndexAnalysisSettings3 getSettings(String projectName) throws IOException {
if (mappedAnalysisSettings == null) {
IndexAnalysisSettingsAccessor dao = new IndexAnalysisSettingsAccessor();
IndexAnalysisSettings3[] setts = dao.read(reader, Short.MAX_VALUE);
map(setts);
}
String projectKey = projectName != null ? projectName : "";
return mappedAnalysisSettings.get(projectKey);
}
private void map(IndexAnalysisSettings3[] setts) {
Map<String, IndexAnalysisSettings3> settingsMap = new HashMap<>();
Map<String, Map<String, IndexedSymlink>> symlinksMap = new HashMap<>();
for (IndexAnalysisSettings3 settings : setts) {
String projectName = settings.getProjectName();
String projectKey = projectName != null ? projectName : "";
settingsMap.put(projectKey, settings);
symlinksMap.put(projectKey, mapSymlinks(settings));
}
mappedAnalysisSettings = settingsMap;
mappedIndexedSymlinks = symlinksMap;
}
private Map<String, IndexedSymlink> mapSymlinks(IndexAnalysisSettings3 settings) {
Map<String, IndexedSymlink> res = new TreeMap<>(
Comparator.comparingInt(String::length).thenComparing(o -> o));
for (IndexedSymlink entry : settings.getIndexedSymlinks().values()) {
res.put(entry.getCanonical(), entry);
}
return res;
}
}
|
String projectName = proj != null ? proj.getName() : null;
IndexAnalysisSettings3 settings = getSettings(projectName);
int tabSize;
if (settings != null && settings.getTabSize() != null) {
tabSize = settings.getTabSize();
} else {
tabSize = proj != null ? proj.getTabSize() : 0;
}
return tabSize;
| 907
| 110
| 1,017
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/Summarizer.java
|
Excerpt
|
getSummary
|
class Excerpt {
List<Summary.Fragment> passages = new ArrayList<>();
Set<String> tokenSet = new TreeSet<>();
int numTerms = 0;
public void addToken(String token) {
tokenSet.add(token);
}
/**
* Return how many unique tokens we have.
*/
public int numUniqueTokens() {
return tokenSet.size();
}
/**
* How many fragments we have.
*/
public int numFragments() {
return passages.size();
}
public void setNumTerms(int numTerms) {
this.numTerms = numTerms;
}
public int getNumTerms() {
return numTerms;
}
/**
* Add a frag to the list.
*/
public void add(Summary.Fragment fragment) {
passages.add(fragment);
}
/**
* Return an Enum for all the fragments.
*/
public List<Summary.Fragment> elements() {
return passages;
}
}
/**
* Returns a summary for the given pre-tokenized text.
*
* @param text input text
* @return summary of hits
* @throws java.io.IOException I/O exception
*/
public Summary getSummary(String text) throws IOException {<FILL_FUNCTION_BODY>
|
if (text == null) {
return null;
}
// Simplistic implementation. Finds the first fragments in the document
// containing any query terms.
//
// @TODO: check that phrases in the query are matched in the fragment
SToken[] tokens = getTokens(text); // parse text to token array
if (tokens.length == 0) {
return new Summary();
}
//
// Create a SortedSet that ranks excerpts according to
// how many query terms are present. An excerpt is
// a List full of Fragments and Highlights
//
SortedSet<Excerpt> excerptSet = new TreeSet<>((excerpt1, excerpt2) -> {
if (excerpt1 == null) {
return excerpt2 == null ? 0 : -1;
} else if (excerpt2 == null) {
return 1;
} else {
int numToks1 = excerpt1.numUniqueTokens();
int numToks2 = excerpt2.numUniqueTokens();
if (numToks1 < numToks2) {
return -1;
} else if (numToks1 == numToks2) {
return excerpt1.numFragments() - excerpt2.numFragments();
} else {
return 1;
}
}
});
//
// Iterate through all terms in the document
//
int lastExcerptPos = 0;
for (int i = 0; i < tokens.length; i++) {
//
// If we find a term that's in the query...
//
if (highlight.contains(tokens[i].toString())) {
//
// Start searching at a point SUM_CONTEXT terms back,
// and move SUM_CONTEXT terms into the future.
//
int startToken = (i > SUM_CONTEXT) ? i - SUM_CONTEXT : 0;
int endToken = Math.min(i + SUM_CONTEXT, tokens.length);
int offset = tokens[startToken].startOffset();
int j = startToken;
//
// Iterate from the start point to the finish, adding
// terms all the way. The end of the passage is always
// SUM_CONTEXT beyond the last query-term.
//
Excerpt excerpt = new Excerpt();
if (i != 0) {
excerpt.add(new Summary.Ellipsis());
}
//
// Iterate through as long as we're before the end of
// the document and we haven't hit the max-number-of-items
// -in-a-summary.
//
while ((j < endToken) && (j - startToken < SUM_LENGTH)) {
//
// Now grab the hit-element, if present
//
SToken t = tokens[j];
if (highlight.contains(t.toString())) {
excerpt.addToken(t.toString());
excerpt.add(new Summary.Fragment(text.substring(offset, t.startOffset())));
excerpt.add(new Summary.Highlight(text.substring(t.startOffset(), t.endOffset())));
offset = t.endOffset();
endToken = Math.min(j + SUM_CONTEXT, tokens.length);
}
j++;
}
lastExcerptPos = endToken;
//
// We found the series of search-term hits and added
// them (with intervening text) to the excerpt. Now
// we need to add the trailing edge of text.
//
// So if (j < tokens.length) then there is still trailing
// text to add. (We haven't hit the end of the source doc.)
// Add the words since the last hit-term insert.
//
if (j < tokens.length) {
excerpt.add(new Summary.Fragment(text.substring(offset, tokens[j].endOffset())));
}
//
// Remember how many terms are in this excerpt
//
excerpt.setNumTerms(j - startToken);
//
// Store the excerpt for later sorting
//
excerptSet.add(excerpt);
//
// Start SUM_CONTEXT places away. The next
// search for relevant excerpts begins at i-SUM_CONTEXT
//
i = j + SUM_CONTEXT;
}
}
//
// If the target text doesn't appear, then we just
// excerpt the first SUM_LENGTH words from the document.
//
if (excerptSet.isEmpty()) {
Excerpt excerpt = new Excerpt();
int excerptLen = Math.min(SUM_LENGTH, tokens.length);
lastExcerptPos = excerptLen;
excerpt.add(new Summary.Fragment(text.substring(tokens[0].startOffset(), tokens[excerptLen - 1].startOffset())));
excerpt.setNumTerms(excerptLen);
excerptSet.add(excerpt);
}
//
// Now choose the best items from the excerpt set.
// Stop when our Summary grows too large.
//
double tokenCount = 0;
Summary s = new Summary();
while (tokenCount <= SUM_LENGTH && !excerptSet.isEmpty()) {
Excerpt excerpt = excerptSet.last();
excerptSet.remove(excerpt);
double tokenFraction = (1.0 * excerpt.getNumTerms()) / excerpt.numFragments();
for (Summary.Fragment f : excerpt.elements()) {
// Don't add fragments if it takes us over the max-limit
if (tokenCount + tokenFraction <= SUM_LENGTH) {
s.add(f);
}
tokenCount += tokenFraction;
}
}
if (tokenCount > 0 && lastExcerptPos < tokens.length) {
s.add(new Summary.Ellipsis());
}
return s;
| 357
| 1,585
| 1,942
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/Summary.java
|
Ellipsis
|
toString
|
class Ellipsis extends Fragment {
/* Constructs an ellipsis fragment for the given text. */
public Ellipsis() {
super(" ... ");
}
/* Returns true. */
@Override
public boolean isEllipsis() {
return true;
}
/* Returns an HTML representation of this fragment. */
@Override
public String toString() {
return "<b> ... </b>";
}
}
private final List<Fragment> fragments = new ArrayList<>();
private static final Fragment[] FRAGMENT_PROTO = new Fragment[0];
/* Adds a fragment to a summary.*/
public void add(Fragment fragment) {
fragments.add(fragment);
}
/**
* Returns an array of all of this summary's fragments.
* @return fragment array
*/
public Fragment[] getFragments() {
return fragments.toArray(FRAGMENT_PROTO);
}
/**
* Returns an HTML representation of this fragment.
* @return string representation
*/
@Override
public String toString() {<FILL_FUNCTION_BODY>
|
StringBuilder buffer = new StringBuilder();
for (Fragment fragment : fragments) {
buffer.append(fragment);
}
return buffer.toString();
| 295
| 41
| 336
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/TermEscaperBase.java
|
TermEscaperBase
|
consume
|
class TermEscaperBase {
private StringBuilder out;
/**
* "Runs the scanner [as documented by JFlex].
* <p>[The method] can be used to get the next token from the input."
* <p>"Consume[s] input until one of the expressions in the specification
* is matched or an error occurs."
* @return a value returned by the lexer specification if defined or the
* {@code EOF} value upon reading end-of-file
* @throws IOException if an error occurs reading the input
*/
abstract boolean yylex() throws IOException;
/**
* @param out the target to append
*/
void setOut(StringBuilder out) {
this.out = out;
}
void appendOut(char c) {
out.append(c);
}
void appendOut(String s) {
out.append(s);
}
/**
* Call {@link #yylex()} until {@code false}, which consumes all input so
* that the argument to {@link #setOut(StringBuilder)} contains the entire
* transformation.
*/
@SuppressWarnings("java:S3626")
void consume() {<FILL_FUNCTION_BODY>}
}
|
try {
while (yylex()) {
continue;
}
} catch (IOException ex) {
// cannot get here with StringBuilder operations
}
| 324
| 45
| 369
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/FormattedLines.java
|
FormattedLines
|
merge
|
class FormattedLines {
private final SortedMap<Integer, String> lines = new TreeMap<>();
private String footer;
private boolean limited;
/*
* Gets a count of the number of lines in the instance.
*/
public int getCount() {
return lines.size();
}
/**
* @return the footer
*/
public String getFooter() {
return footer;
}
public void setFooter(String value) {
footer = value;
}
/*
* Gets a value indicating if lines were limited.
*/
public boolean isLimited() {
return limited;
}
/*
* Sets a value indicating if lines were limited.
*/
public void setLimited(boolean value) {
limited = value;
}
/**
* Removes the highest line from the instance.
* @return a defined value
* @throws NoSuchElementException if the instance is empty
*/
public String pop() {
return lines.remove(lines.lastKey());
}
/**
* Sets the specified String line for the specified line number, replacing
* any previous entry for the same line number.
* @param lineno a value
* @param line a defined instance
* @return the former value or {@code null}
*/
public String put(int lineno, String line) {
if (line == null) {
throw new IllegalArgumentException("line is null");
}
return lines.put(lineno, line);
}
/**
* Creates a new instance with lines merged from this instance and
* {@code other}. Any lines in common for the same line number are taken
* from this instance rather than {@code other}; and likewise for
* {@link #getFooter()}.
* <p>
* {@link #isLimited()} will be {@code true} if either is {@code true}, but
* the value is suspect since it cannot be truly known if the merged result
* is actually the unlimited result.
* @param other a defined instance
* @return a defined instance
*/
public FormattedLines merge(FormattedLines other) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
StringBuilder bld = new StringBuilder();
for (String line : lines.values()) {
bld.append(line);
}
String f = footer;
if (f != null && limited) {
bld.append(f);
}
return bld.toString();
}
}
|
FormattedLines res = new FormattedLines();
res.lines.putAll(this.lines);
for (Map.Entry<Integer, String> kv : other.lines.entrySet()) {
res.lines.putIfAbsent(kv.getKey(), kv.getValue());
}
res.setFooter(this.footer != null ? this.footer : other.footer);
res.setLimited(this.limited || other.limited);
return res;
| 655
| 124
| 779
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/LineHighlight.java
|
LineHighlight
|
condenseMarkups
|
class LineHighlight {
private final int lineno;
private List<PhraseHighlight> markups;
/** Offset of elided left part. */
private int lelide;
/** Offset of elide right part. */
private int relide;
private boolean didLelide;
private boolean didRelide;
public LineHighlight(int lineno) {
if (lineno < 0) {
throw new IllegalArgumentException("lineno cannot be negative");
}
this.lineno = lineno;
}
/**
* Gets the number of markups.
* @return zero or greater
*/
public int countMarkups() {
return markups == null ? 0 : markups.size();
}
/**
* Gets the highlight at the specified position.
* @param i index of element to return
* @return defined instance
*/
public PhraseHighlight getMarkup(int i) {
return markups.get(i);
}
/**
* Sort and condense overlapping markup highlights.
*/
public void condenseMarkups() {<FILL_FUNCTION_BODY>}
/**
* Adds the specified highlight.
* @param phi a defined instance
*/
public void addMarkup(PhraseHighlight phi) {
if (phi == null) {
throw new IllegalArgumentException("phi is null");
}
if (markups == null) {
markups = new ArrayList<>();
}
markups.add(phi);
}
/**
* @return the lineno
*/
public int getLineno() {
return lineno;
}
/**
* Gets the left elide value.
* @return zero or greater
*/
public int getLelide() {
return lelide;
}
/**
* Sets the left elide value.
* @param value integer value
*/
public void setLelide(int value) {
if (value < 0) {
throw new IllegalArgumentException("value is negative");
}
this.lelide = value;
}
/**
* Gets the right elide value.
* @return zero or greater
*/
public int getRelide() {
return relide;
}
/**
* Sets the right elide value.
* @param value integer value
*/
public void setRelide(int value) {
if (value < 0) {
throw new IllegalArgumentException("value is negative");
}
this.relide = value;
}
/**
* Append a substring with
* {@link Util#htmlize(java.lang.CharSequence, java.lang.Appendable, boolean)},
* taking into account any positive {@link #getLelide()} or
* {@link #getRelide()}.
* @param dest appendable object
* @param line line value
* @param start start offset
* @param end end offset
* @throws IOException I/O
*/
public void hsub(Appendable dest, String line, int start, int end)
throws IOException {
boolean lell = false;
boolean rell = false;
if (start < lelide) {
lell = true;
start = lelide;
}
if (end < lelide) {
end = lelide;
}
if (relide > 0) {
if (start > relide) {
start = relide;
}
if (end > relide) {
rell = true;
end = relide;
}
}
String str = line.substring(start, end);
if (lell && !didLelide) {
dest.append(HtmlConsts.HELLIP);
didLelide = true;
}
Util.htmlize(str, dest, true);
if (rell && !didRelide) {
dest.append(HtmlConsts.HELLIP);
didRelide = true;
}
}
/**
* Calls {@link #hsub(java.lang.Appendable, java.lang.String, int, int)}
* with {@code dest}, {@code line}, {@code loff}, and {@code line}
* {@link String#length()}.
* @param dest appendable object
* @param line line value
* @param loff start offset
* @throws IOException I/O
*/
public void hsub(Appendable dest, String line, int loff)
throws IOException {
hsub(dest, line, loff, line.length());
}
}
|
if (markups == null) {
return;
}
markups.sort(PhraseHighlightComparator.INSTANCE);
// Condense instances if there is overlap.
for (int i = 0; i + 1 < markups.size(); ++i) {
PhraseHighlight phi0 = markups.get(i);
PhraseHighlight phi1 = markups.get(i + 1);
if (phi0.overlaps(phi1)) {
phi0 = phi0.merge(phi1);
markups.set(i, phi0);
markups.remove(i + 1);
--i;
}
}
| 1,180
| 173
| 1,353
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/LineMatcher.java
|
LineMatcher
|
compareStrings
|
class LineMatcher {
// Line Matcher States
public static final int NOT_MATCHED = 0;
public static final int MATCHED = 1;
public static final int WAIT = 2;
/**
* Tells whether the matching should be done in a case-insensitive manner.
*/
private final boolean caseInsensitive;
/**
* Create a {@code LineMatcher} instance.
*
* @param caseInsensitive if {@code true}, matching should not consider
* case differences significant
*/
LineMatcher(boolean caseInsensitive) {
this.caseInsensitive = caseInsensitive;
}
/**
* Check if two strings are equal. If this is a case-insensitive matcher,
* the check will return true if the only difference between the strings
* is difference in case.
*/
boolean equal(String s1, String s2) {
return compareStrings(s1, s2) == 0;
}
/**
* Compare two strings and return -1, 0 or 1 if the first string is
* lexicographically smaller than, equal to or greater than the second
* string. If this is a case-insensitive matcher, case differences will
* be ignored.
*/
int compareStrings(String s1, String s2) {<FILL_FUNCTION_BODY>}
/**
* Normalize a string token for comparison with other string tokens. That
* is, convert to lower case if this is a case-insensitive matcher.
* Otherwise, return the string itself.
*/
String normalizeString(String s) {
if (s == null) {
return null;
} else if (caseInsensitive) {
return s.toLowerCase(Locale.ROOT);
} else {
return s;
}
}
public abstract int match(String line);
}
|
if (s1 == null) {
return s2 == null ? 0 : -1;
} else if (caseInsensitive) {
return s1.compareToIgnoreCase(s2);
} else {
return s1.compareTo(s2);
}
| 473
| 72
| 545
|
<no_super_class>
|
oracle_opengrok
|
opengrok/opengrok-indexer/src/main/java/org/opengrok/indexer/search/context/OGPassageScorer.java
|
OGPassageScorer
|
score
|
class OGPassageScorer extends PassageScorer {
private static final Logger LOGGER = LoggerFactory.getLogger(OGPassageScorer.class);
public OGPassageScorer() {
// Use non-default values so that the scorer object is easier to identify when debugging.
super(1, 2, 3);
}
@Override
public float score(Passage passage, int contentLength) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.log(Level.FINEST, "{0} -> {1}", new Object[]{passage, passage.getStartOffset()});
return -passage.getStartOffset();
| 124
| 50
| 174
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.