_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1300
|
Task.setBaselineStartText
|
train
|
public void setBaselineStartText(int baselineNumber, String value)
{
set(selectField(TaskFieldLists.BASELINE_STARTS, baselineNumber), value);
}
|
java
|
{
"resource": ""
}
|
q1301
|
Task.getCompleteThrough
|
train
|
public Date getCompleteThrough()
{
Date value = (Date) getCachedValue(TaskField.COMPLETE_THROUGH);
if (value == null)
{
int percentComplete = NumberHelper.getInt(getPercentageComplete());
switch (percentComplete)
{
case 0:
{
break;
}
case 100:
{
value = getActualFinish();
break;
}
default:
{
Date actualStart = getActualStart();
Duration duration = getDuration();
if (actualStart != null && duration != null)
{
double durationValue = (duration.getDuration() * percentComplete) / 100d;
duration = Duration.getInstance(durationValue, duration.getUnits());
ProjectCalendar calendar = getEffectiveCalendar();
value = calendar.getDate(actualStart, duration, true);
}
break;
}
}
set(TaskField.COMPLETE_THROUGH, value);
}
return value;
}
|
java
|
{
"resource": ""
}
|
q1302
|
Task.getTaskMode
|
train
|
public TaskMode getTaskMode()
{
return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;
}
|
java
|
{
"resource": ""
}
|
q1303
|
Task.getEffectiveCalendar
|
train
|
public ProjectCalendar getEffectiveCalendar()
{
ProjectCalendar result = getCalendar();
if (result == null)
{
result = getParentFile().getDefaultCalendar();
}
return result;
}
|
java
|
{
"resource": ""
}
|
q1304
|
Task.removePredecessor
|
train
|
public boolean removePredecessor(Task targetTask, RelationType type, Duration lag)
{
boolean matchFound = false;
//
// Retrieve the list of predecessors
//
List<Relation> predecessorList = getPredecessors();
if (!predecessorList.isEmpty())
{
//
// Ensure that we have a valid lag duration
//
if (lag == null)
{
lag = Duration.getInstance(0, TimeUnit.DAYS);
}
//
// Ensure that there is a predecessor relationship between
// these two tasks, and remove it.
//
matchFound = removeRelation(predecessorList, targetTask, type, lag);
//
// If we have removed a predecessor, then we must remove the
// corresponding successor entry from the target task list
//
if (matchFound)
{
//
// Retrieve the list of successors
//
List<Relation> successorList = targetTask.getSuccessors();
if (!successorList.isEmpty())
{
//
// Ensure that there is a successor relationship between
// these two tasks, and remove it.
//
removeRelation(successorList, this, type, lag);
}
}
}
return matchFound;
}
|
java
|
{
"resource": ""
}
|
q1305
|
Task.removeRelation
|
train
|
private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)
{
boolean matchFound = false;
for (Relation relation : relationList)
{
if (relation.getTargetTask() == targetTask)
{
if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)
{
matchFound = relationList.remove(relation);
break;
}
}
}
return matchFound;
}
|
java
|
{
"resource": ""
}
|
q1306
|
Task.isRelated
|
train
|
private boolean isRelated(Task task, List<Relation> list)
{
boolean result = false;
for (Relation relation : list)
{
if (relation.getTargetTask().getUniqueID().intValue() == task.getUniqueID().intValue())
{
result = true;
break;
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q1307
|
PmdRuleSet.writeTo
|
train
|
public void writeTo(Writer destination) {
Element eltRuleset = new Element("ruleset");
addAttribute(eltRuleset, "name", name);
addChild(eltRuleset, "description", description);
for (PmdRule pmdRule : rules) {
Element eltRule = new Element("rule");
addAttribute(eltRule, "ref", pmdRule.getRef());
addAttribute(eltRule, "class", pmdRule.getClazz());
addAttribute(eltRule, "message", pmdRule.getMessage());
addAttribute(eltRule, "name", pmdRule.getName());
addAttribute(eltRule, "language", pmdRule.getLanguage());
addChild(eltRule, "priority", String.valueOf(pmdRule.getPriority()));
if (pmdRule.hasProperties()) {
Element ruleProperties = processRuleProperties(pmdRule);
if (ruleProperties.getContentSize() > 0) {
eltRule.addContent(ruleProperties);
}
}
eltRuleset.addContent(eltRule);
}
XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
try {
serializer.output(new Document(eltRuleset), destination);
} catch (IOException e) {
throw new IllegalStateException("An exception occurred while serializing PmdRuleSet.", e);
}
}
|
java
|
{
"resource": ""
}
|
q1308
|
XmlRuleSetFactory.create
|
train
|
@Override
public PmdRuleSet create() {
final SAXBuilder parser = new SAXBuilder();
final Document dom;
try {
dom = parser.build(source);
} catch (JDOMException | IOException e) {
if (messages != null) {
messages.addErrorText(INVALID_INPUT + " : " + e.getMessage());
}
LOG.error(INVALID_INPUT, e);
return new PmdRuleSet();
}
final Element eltResultset = dom.getRootElement();
final Namespace namespace = eltResultset.getNamespace();
final PmdRuleSet result = new PmdRuleSet();
final String name = eltResultset.getAttributeValue("name");
final Element descriptionElement = getChild(eltResultset, namespace);
result.setName(name);
if (descriptionElement != null) {
result.setDescription(descriptionElement.getValue());
}
for (Element eltRule : getChildren(eltResultset, "rule", namespace)) {
PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue("ref"));
pmdRule.setClazz(eltRule.getAttributeValue("class"));
pmdRule.setName(eltRule.getAttributeValue("name"));
pmdRule.setMessage(eltRule.getAttributeValue("message"));
parsePmdPriority(eltRule, pmdRule, namespace);
parsePmdProperties(eltRule, pmdRule, namespace);
result.addRule(pmdRule);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q1309
|
TextRangeCalculator.calculateBeginLine
|
train
|
private static int calculateBeginLine(RuleViolation pmdViolation) {
int minLine = Math.min(pmdViolation.getBeginLine(), pmdViolation.getEndLine());
return minLine > 0 ? minLine : calculateEndLine(pmdViolation);
}
|
java
|
{
"resource": ""
}
|
q1310
|
SearchViewFacade.findViewById
|
train
|
@Nullable public View findViewById(int id) {
if (searchView != null) {
return searchView.findViewById(id);
} else if (supportView != null) {
return supportView.findViewById(id);
}
throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
}
|
java
|
{
"resource": ""
}
|
q1311
|
SearchViewFacade.getContext
|
train
|
@NonNull public Context getContext() {
if (searchView != null) {
return searchView.getContext();
} else if (supportView != null) {
return supportView.getContext();
}
throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
}
|
java
|
{
"resource": ""
}
|
q1312
|
SearchViewFacade.getQuery
|
train
|
@NonNull public CharSequence getQuery() {
if (searchView != null) {
return searchView.getQuery();
} else if (supportView != null) {
return supportView.getQuery();
}
throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
}
|
java
|
{
"resource": ""
}
|
q1313
|
SearchViewFacade.setOnQueryTextListener
|
train
|
public void setOnQueryTextListener(@NonNull final SearchView.OnQueryTextListener listener) {
if (searchView != null) {
searchView.setOnQueryTextListener(listener);
} else if (supportView != null) {
supportView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {
@Override public boolean onQueryTextSubmit(String query) {
return listener.onQueryTextSubmit(query);
}
@Override public boolean onQueryTextChange(String newText) {
return listener.onQueryTextChange(newText);
}
});
} else {
throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
}
}
|
java
|
{
"resource": ""
}
|
q1314
|
SearchViewFacade.setOnCloseListener
|
train
|
public void setOnCloseListener(@NonNull final android.support.v7.widget.SearchView.OnCloseListener listener) {
if (searchView != null) {
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override public boolean onClose() {
return listener.onClose();
}
});
} else if (supportView != null) {
supportView.setOnCloseListener(listener);
} else {
throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
}
}
|
java
|
{
"resource": ""
}
|
q1315
|
Searcher.get
|
train
|
public static Searcher get(String variant) {
final Searcher searcher = instances.get(variant);
if (searcher == null) {
throw new IllegalStateException(Errors.SEARCHER_GET_BEFORE_CREATE);
}
return searcher;
}
|
java
|
{
"resource": ""
}
|
q1316
|
Searcher.reset
|
train
|
@NonNull
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher reset() {
lastResponsePage = 0;
lastRequestPage = 0;
lastResponseId = 0;
endReached = false;
clearFacetRefinements();
cancelPendingRequests();
numericRefinements.clear();
return this;
}
|
java
|
{
"resource": ""
}
|
q1317
|
Searcher.cancelPendingRequests
|
train
|
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher cancelPendingRequests() {
if (pendingRequests.size() != 0) {
for (int i = 0; i < pendingRequests.size(); i++) {
int reqId = pendingRequests.keyAt(i);
Request r = pendingRequests.valueAt(i);
if (!r.isFinished() && !r.isCancelled()) {
cancelRequest(r, reqId);
}
}
}
return this;
}
|
java
|
{
"resource": ""
}
|
q1318
|
Searcher.addBooleanFilter
|
train
|
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher addBooleanFilter(String attribute, Boolean value) {
booleanFilterMap.put(attribute, value);
rebuildQueryFacetFilters();
return this;
}
|
java
|
{
"resource": ""
}
|
q1319
|
Searcher.addFacet
|
train
|
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher addFacet(String... attributes) {
for (String attribute : attributes) {
final Integer value = facetRequestCount.get(attribute);
facetRequestCount.put(attribute, value == null ? 1 : value + 1);
if (value == null || value == 0) {
facets.add(attribute);
}
}
rebuildQueryFacets();
return this;
}
|
java
|
{
"resource": ""
}
|
q1320
|
Searcher.deleteFacet
|
train
|
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher deleteFacet(String... attributes) {
for (String attribute : attributes) {
facetRequestCount.put(attribute, 0);
facets.remove(attribute);
}
rebuildQueryFacets();
return this;
}
|
java
|
{
"resource": ""
}
|
q1321
|
NumericRefinement.checkOperatorIsValid
|
train
|
public static void checkOperatorIsValid(int operatorCode) {
switch (operatorCode) {
case OPERATOR_LT:
case OPERATOR_LE:
case OPERATOR_EQ:
case OPERATOR_NE:
case OPERATOR_GE:
case OPERATOR_GT:
case OPERATOR_UNKNOWN:
return;
default:
throw new IllegalStateException(String.format(Locale.US, ERROR_INVALID_CODE, operatorCode));
}
}
|
java
|
{
"resource": ""
}
|
q1322
|
JSONUtils.getStringFromJSONPath
|
train
|
public static String getStringFromJSONPath(JSONObject record, String path) {
final Object object = getObjectFromJSONPath(record, path);
return object == null ? null : object.toString();
}
|
java
|
{
"resource": ""
}
|
q1323
|
JSONUtils.getMapFromJSONPath
|
train
|
public static HashMap<String, String> getMapFromJSONPath(JSONObject record, String path) {
return getObjectFromJSONPath(record, path);
}
|
java
|
{
"resource": ""
}
|
q1324
|
Hits.enableKeyboardAutoHiding
|
train
|
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public void enableKeyboardAutoHiding() {
keyboardListener = new OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dx != 0 || dy != 0) {
imeManager.hideSoftInputFromWindow(
Hits.this.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
super.onScrolled(recyclerView, dx, dy);
}
};
addOnScrollListener(keyboardListener);
}
|
java
|
{
"resource": ""
}
|
q1325
|
InstantSearch.search
|
train
|
public void search(String query) {
final Query newQuery = searcher.getQuery().setQuery(query);
searcher.setQuery(newQuery).search();
}
|
java
|
{
"resource": ""
}
|
q1326
|
InstantSearch.registerFilters
|
train
|
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public void registerFilters(List<AlgoliaFilter> filters) {
for (final AlgoliaFilter filter : filters) {
searcher.addFacet(filter.getAttribute());
}
}
|
java
|
{
"resource": ""
}
|
q1327
|
InstantSearch.registerWidget
|
train
|
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public void registerWidget(View widget) {
prepareWidget(widget);
if (widget instanceof AlgoliaResultsListener) {
AlgoliaResultsListener listener = (AlgoliaResultsListener) widget;
if (!this.resultListeners.contains(listener)) {
this.resultListeners.add(listener);
}
searcher.registerResultListener(listener);
}
if (widget instanceof AlgoliaErrorListener) {
AlgoliaErrorListener listener = (AlgoliaErrorListener) widget;
if (!this.errorListeners.contains(listener)) {
this.errorListeners.add(listener);
}
searcher.registerErrorListener(listener);
}
if (widget instanceof AlgoliaSearcherListener) {
AlgoliaSearcherListener listener = (AlgoliaSearcherListener) widget;
listener.initWithSearcher(searcher);
}
}
|
java
|
{
"resource": ""
}
|
q1328
|
InstantSearch.processAllListeners
|
train
|
private List<String> processAllListeners(View rootView) {
List<String> refinementAttributes = new ArrayList<>();
// Register any AlgoliaResultsListener (unless it has a different variant than searcher)
final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);
if (resultListeners.isEmpty()) {
throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);
}
for (AlgoliaResultsListener listener : resultListeners) {
if (!this.resultListeners.contains(listener)) {
final String variant = BindingHelper.getVariantForView((View) listener);
if (variant == null || searcher.variant.equals(variant)) {
this.resultListeners.add(listener);
searcher.registerResultListener(listener);
prepareWidget(listener, refinementAttributes);
}
}
}
// Register any AlgoliaErrorListener (unless it has a different variant than searcher)
final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);
for (AlgoliaErrorListener listener : errorListeners) {
if (!this.errorListeners.contains(listener)) {
final String variant = BindingHelper.getVariantForView((View) listener);
if (variant == null || searcher.variant.equals(variant)) {
this.errorListeners.add(listener);
}
}
searcher.registerErrorListener(listener);
prepareWidget(listener, refinementAttributes);
}
// Register any AlgoliaSearcherListener (unless it has a different variant than searcher)
final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);
for (AlgoliaSearcherListener listener : searcherListeners) {
final String variant = BindingHelper.getVariantForView((View) listener);
if (variant == null || searcher.variant.equals(variant)) {
listener.initWithSearcher(searcher);
prepareWidget(listener, refinementAttributes);
}
}
return refinementAttributes;
}
|
java
|
{
"resource": ""
}
|
q1329
|
AccountsRestClient.suggestAccounts
|
train
|
@Override
public SuggestAccountsRequest suggestAccounts() throws RestApiException {
return new SuggestAccountsRequest() {
@Override
public List<AccountInfo> get() throws RestApiException {
return AccountsRestClient.this.suggestAccounts(this);
}
};
}
|
java
|
{
"resource": ""
}
|
q1330
|
Url.encode
|
train
|
public static String encode(String component) {
if (component != null) {
try {
return URLEncoder.encode(component, UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("JVM must support UTF-8", e);
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q1331
|
GerritRestClient.getXsrfFromHtmlBody
|
train
|
private Optional<String> getXsrfFromHtmlBody(HttpResponse loginResponse) throws IOException {
Optional<Cookie> gerritAccountCookie = findGerritAccountCookie();
if (gerritAccountCookie.isPresent()) {
Matcher matcher = GERRIT_AUTH_PATTERN.matcher(EntityUtils.toString(loginResponse.getEntity(), Consts.UTF_8));
if (matcher.find()) {
return Optional.of(matcher.group(1));
}
}
return Optional.absent();
}
|
java
|
{
"resource": ""
}
|
q1332
|
GerritRestClient.getCredentialsProvider
|
train
|
private BasicCredentialsProvider getCredentialsProvider() {
return new BasicCredentialsProvider() {
private Set<AuthScope> authAlreadyTried = Sets.newHashSet();
@Override
public Credentials getCredentials(AuthScope authscope) {
if (authAlreadyTried.contains(authscope)) {
return null;
}
authAlreadyTried.add(authscope);
return super.getCredentials(authscope);
}
};
}
|
java
|
{
"resource": ""
}
|
q1333
|
BinaryResult.asString
|
train
|
public String asString() throws IOException {
long len = getContentLength();
ByteArrayOutputStream buf;
if (0 < len) {
buf = new ByteArrayOutputStream((int) len);
} else {
buf = new ByteArrayOutputStream();
}
writeTo(buf);
return decode(buf.toByteArray(), getCharacterEncoding());
}
|
java
|
{
"resource": ""
}
|
q1334
|
PreemptiveAuthHttpRequestInterceptor.isForGerritHost
|
train
|
private boolean isForGerritHost(HttpRequest request) {
if (!(request instanceof HttpRequestWrapper)) return false;
HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();
if (!(originalRequest instanceof HttpRequestBase)) return false;
URI uri = ((HttpRequestBase) originalRequest).getURI();
URI authDataUri = URI.create(authData.getHost());
if (uri == null || uri.getHost() == null) return false;
boolean hostEquals = uri.getHost().equals(authDataUri.getHost());
boolean portEquals = uri.getPort() == authDataUri.getPort();
return hostEquals && portEquals;
}
|
java
|
{
"resource": ""
}
|
q1335
|
FileUtils.getRelativePathName
|
train
|
public static String getRelativePathName(Path root, Path path) {
Path relative = root.relativize(path);
return Files.isDirectory(path) && !relative.toString().endsWith("/") ? String.format("%s/", relative.toString()) : relative.toString();
}
|
java
|
{
"resource": ""
}
|
q1336
|
_DefaultConnectionContext.dispose
|
train
|
@PreDestroy
public final void dispose() {
getConnectionPool().ifPresent(PoolResources::dispose);
getThreadPool().dispose();
try {
ObjectName name = getByteBufAllocatorObjectName();
if (ManagementFactory.getPlatformMBeanServer().isRegistered(name)) {
ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);
}
} catch (JMException e) {
this.logger.error("Unable to register ByteBufAllocator MBean", e);
}
}
|
java
|
{
"resource": ""
}
|
q1337
|
ResourceUtils.getEntity
|
train
|
public static <T, R extends Resource<T>> T getEntity(R resource) {
return resource.getEntity();
}
|
java
|
{
"resource": ""
}
|
q1338
|
ResourceUtils.getResources
|
train
|
public static <R extends Resource<?>, U extends PaginatedResponse<R>> Flux<R> getResources(U response) {
return Flux.fromIterable(response.getResources());
}
|
java
|
{
"resource": ""
}
|
q1339
|
JobUtils.waitForCompletion
|
train
|
public static Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, String jobId) {
return requestJobV3(cloudFoundryClient, jobId)
.filter(job -> JobState.PROCESSING != job.getState())
.repeatWhenEmpty(exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout))
.filter(job -> JobState.FAILED == job.getState())
.flatMap(JobUtils::getError);
}
|
java
|
{
"resource": ""
}
|
q1340
|
TimeUtils.asTime
|
train
|
public static String asTime(long time) {
if (time > HOUR) {
return String.format("%.1f h", (time / HOUR));
} else if (time > MINUTE) {
return String.format("%.1f m", (time / MINUTE));
} else if (time > SECOND) {
return String.format("%.1f s", (time / SECOND));
} else {
return String.format("%d ms", time);
}
}
|
java
|
{
"resource": ""
}
|
q1341
|
View.buildMatcher
|
train
|
private ClassMatcher buildMatcher(String tagText) {
// check there are at least @match <type> and a parameter
String[] strings = StringUtil.tokenize(tagText);
if (strings.length < 2) {
System.err.println("Skipping uncomplete @match tag, type missing: " + tagText + " in view " + viewDoc);
return null;
}
try {
if (strings[0].equals("class")) {
return new PatternMatcher(Pattern.compile(strings[1]));
} else if (strings[0].equals("context")) {
return new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(),
false);
} else if (strings[0].equals("outgoingContext")) {
return new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(),
false);
} else if (strings[0].equals("interface")) {
return new InterfaceMatcher(root, Pattern.compile(strings[1]));
} else if (strings[0].equals("subclass")) {
return new SubclassMatcher(root, Pattern.compile(strings[1]));
} else {
System.err.println("Skipping @match tag, unknown match type, in view " + viewDoc);
}
} catch (PatternSyntaxException pse) {
System.err.println("Skipping @match tag due to invalid regular expression '" + tagText
+ "'" + " in view " + viewDoc);
} catch (Exception e) {
System.err.println("Skipping @match tag due to an internal error '" + tagText
+ "'" + " in view " + viewDoc);
e.printStackTrace();
}
return null;
}
|
java
|
{
"resource": ""
}
|
q1342
|
ContextMatcher.addToGraph
|
train
|
private void addToGraph(ClassDoc cd) {
// avoid adding twice the same class, but don't rely on cg.getClassInfo
// since there are other ways to add a classInfor than printing the class
if (visited.contains(cd.toString()))
return;
visited.add(cd.toString());
cg.printClass(cd, false);
cg.printRelations(cd);
if (opt.inferRelationships)
cg.printInferredRelations(cd);
if (opt.inferDependencies)
cg.printInferredDependencies(cd);
}
|
java
|
{
"resource": ""
}
|
q1343
|
UmlGraphDoc.optionLength
|
train
|
public static int optionLength(String option) {
int result = Standard.optionLength(option);
if (result != 0)
return result;
else
return UmlGraph.optionLength(option);
}
|
java
|
{
"resource": ""
}
|
q1344
|
UmlGraphDoc.start
|
train
|
public static boolean start(RootDoc root) {
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", running the standard doclet");
Standard.start(root);
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", altering javadocs");
try {
String outputFolder = findOutputPath(root.options());
Options opt = UmlGraph.buildOptions(root);
opt.setOptions(root.options());
// in javadoc enumerations are always printed
opt.showEnumerations = true;
opt.relativeLinksForSourcePackages = true;
// enable strict matching for hide expressions
opt.strictMatching = true;
// root.printNotice(opt.toString());
generatePackageDiagrams(root, opt, outputFolder);
generateContextDiagrams(root, opt, outputFolder);
} catch(Throwable t) {
root.printWarning("Error: " + t.toString());
t.printStackTrace();
return false;
}
return true;
}
|
java
|
{
"resource": ""
}
|
q1345
|
UmlGraphDoc.generateContextDiagrams
|
train
|
private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)
throws IOException {
Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {
public int compare(ClassDoc cd1, ClassDoc cd2) {
return cd1.name().compareTo(cd2.name());
}
});
for (ClassDoc classDoc : root.classes())
classDocs.add(classDoc);
ContextView view = null;
for (ClassDoc classDoc : classDocs) {
try {
if(view == null)
view = new ContextView(outputFolder, classDoc, root, opt);
else
view.setContextCenter(classDoc);
UmlGraph.buildGraph(root, view, classDoc);
runGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);
alterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),
classDoc.name() + ".html", Pattern.compile(".*(Class|Interface|Enum) " + classDoc.name() + ".*") , root);
} catch (Exception e) {
throw new RuntimeException("Error generating " + classDoc.name(), e);
}
}
}
|
java
|
{
"resource": ""
}
|
q1346
|
UmlGraphDoc.alterHtmlDocs
|
train
|
private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,
String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {
// setup files
File output = new File(outputFolder, packageName.replace(".", "/"));
File htmlFile = new File(output, htmlFileName);
File alteredFile = new File(htmlFile.getAbsolutePath() + ".uml");
if (!htmlFile.exists()) {
System.err.println("Expected file not found: " + htmlFile.getAbsolutePath());
return;
}
// parse & rewrite
BufferedWriter writer = null;
BufferedReader reader = null;
boolean matched = false;
try {
writer = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(alteredFile), opt.outputEncoding));
reader = new BufferedReader(new InputStreamReader(new
FileInputStream(htmlFile), opt.outputEncoding));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
if (!matched && insertPointPattern.matcher(line).matches()) {
matched = true;
String tag;
if (opt.autoSize)
tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);
else
tag = String.format(UML_DIV_TAG, className);
if (opt.collapsibleDiagrams)
tag = String.format(EXPANDABLE_UML, tag, "Show UML class diagram", "Hide UML class diagram");
writer.write("<!-- UML diagram added by UMLGraph version " +
Version.VERSION +
" (http://www.spinellis.gr/umlgraph/) -->");
writer.newLine();
writer.write(tag);
writer.newLine();
}
}
} finally {
if (writer != null)
writer.close();
if (reader != null)
reader.close();
}
// if altered, delete old file and rename new one to the old file name
if (matched) {
htmlFile.delete();
alteredFile.renameTo(htmlFile);
} else {
root.printNotice("Warning, could not find a line that matches the pattern '" + insertPointPattern.pattern()
+ "'.\n Class diagram reference not inserted");
alteredFile.delete();
}
}
|
java
|
{
"resource": ""
}
|
q1347
|
UmlGraphDoc.findOutputPath
|
train
|
private static String findOutputPath(String[][] options) {
for (int i = 0; i < options.length; i++) {
if (options[i][0].equals("-d"))
return options[i][1];
}
return ".";
}
|
java
|
{
"resource": ""
}
|
q1348
|
Options.setAll
|
train
|
public void setAll() {
showAttributes = true;
showEnumerations = true;
showEnumConstants = true;
showOperations = true;
showConstructors = true;
showVisibility = true;
showType = true;
}
|
java
|
{
"resource": ""
}
|
q1349
|
Options.optionLength
|
train
|
public static int optionLength(String option) {
if(matchOption(option, "qualify", true) ||
matchOption(option, "qualifyGenerics", true) ||
matchOption(option, "hideGenerics", true) ||
matchOption(option, "horizontal", true) ||
matchOption(option, "all") ||
matchOption(option, "attributes", true) ||
matchOption(option, "enumconstants", true) ||
matchOption(option, "operations", true) ||
matchOption(option, "enumerations", true) ||
matchOption(option, "constructors", true) ||
matchOption(option, "visibility", true) ||
matchOption(option, "types", true) ||
matchOption(option, "autosize", true) ||
matchOption(option, "commentname", true) ||
matchOption(option, "nodefontabstractitalic", true) ||
matchOption(option, "postfixpackage", true) ||
matchOption(option, "noguillemot", true) ||
matchOption(option, "views", true) ||
matchOption(option, "inferrel", true) ||
matchOption(option, "useimports", true) ||
matchOption(option, "collapsible", true) ||
matchOption(option, "inferdep", true) ||
matchOption(option, "inferdepinpackage", true) ||
matchOption(option, "hideprivateinner", true) ||
matchOption(option, "compact", true))
return 1;
else if(matchOption(option, "nodefillcolor") ||
matchOption(option, "nodefontcolor") ||
matchOption(option, "nodefontsize") ||
matchOption(option, "nodefontname") ||
matchOption(option, "nodefontclasssize") ||
matchOption(option, "nodefontclassname") ||
matchOption(option, "nodefonttagsize") ||
matchOption(option, "nodefonttagname") ||
matchOption(option, "nodefontpackagesize") ||
matchOption(option, "nodefontpackagename") ||
matchOption(option, "edgefontcolor") ||
matchOption(option, "edgecolor") ||
matchOption(option, "edgefontsize") ||
matchOption(option, "edgefontname") ||
matchOption(option, "shape") ||
matchOption(option, "output") ||
matchOption(option, "outputencoding") ||
matchOption(option, "bgcolor") ||
matchOption(option, "hide") ||
matchOption(option, "include") ||
matchOption(option, "apidocroot") ||
matchOption(option, "apidocmap") ||
matchOption(option, "d") ||
matchOption(option, "view") ||
matchOption(option, "inferreltype") ||
matchOption(option, "inferdepvis") ||
matchOption(option, "collpackages") ||
matchOption(option, "nodesep") ||
matchOption(option, "ranksep") ||
matchOption(option, "dotexecutable") ||
matchOption(option, "link"))
return 2;
else if(matchOption(option, "contextPattern") ||
matchOption(option, "linkoffline"))
return 3;
else
return 0;
}
|
java
|
{
"resource": ""
}
|
q1350
|
Options.addApiDocRoots
|
train
|
private void addApiDocRoots(String packageListUrl) {
BufferedReader br = null;
packageListUrl = fixApiDocRoot(packageListUrl);
try {
URL url = new URL(packageListUrl + "/package-list");
br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while((line = br.readLine()) != null) {
line = line + ".";
Pattern pattern = Pattern.compile(line.replace(".", "\\.") + "[^\\.]*");
apiDocMap.put(pattern, packageListUrl);
}
} catch(IOException e) {
System.err.println("Errors happened while accessing the package-list file at "
+ packageListUrl);
} finally {
if(br != null)
try {
br.close();
} catch (IOException e) {}
}
}
|
java
|
{
"resource": ""
}
|
q1351
|
Options.fixApiDocRoot
|
train
|
private String fixApiDocRoot(String str) {
if (str == null)
return null;
String fixed = str.trim();
if (fixed.isEmpty())
return "";
if (File.separatorChar != '/')
fixed = fixed.replace(File.separatorChar, '/');
if (!fixed.endsWith("/"))
fixed = fixed + "/";
return fixed;
}
|
java
|
{
"resource": ""
}
|
q1352
|
Options.setOptions
|
train
|
public void setOptions(Doc p) {
if (p == null)
return;
for (Tag tag : p.tags("opt"))
setOption(StringUtil.tokenize(tag.text()));
}
/**
* Check if the supplied string matches an entity specified
* with the -hide parameter.
* @return true if the string matches.
*/
public boolean matchesHideExpression(String s) {
for (Pattern hidePattern : hidePatterns) {
// micro-optimization because the "all pattern" is heavily used in UmlGraphDoc
if(hidePattern == allPattern)
return true;
Matcher m = hidePattern.matcher(s);
if (strictMatching ? m.matches() : m.find())
return true;
}
return false;
}
/**
* Check if the supplied string matches an entity specified
* with the -include parameter.
* @return true if the string matches.
*/
public boolean matchesIncludeExpression(String s) {
for (Pattern includePattern : includePatterns) {
Matcher m = includePattern.matcher(s);
if (strictMatching ? m.matches() : m.find())
return true;
}
return false;
}
/**
* Check if the supplied string matches an entity specified
* with the -collpackages parameter.
* @return true if the string matches.
*/
public boolean matchesCollPackageExpression(String s) {
for (Pattern collPattern : collPackages) {
Matcher m = collPattern.matcher(s);
if (strictMatching ? m.matches() : m.find())
return true;
}
return false;
}
// ----------------------------------------------------------------
// OptionProvider methods
// ----------------------------------------------------------------
public Options getOptionsFor(ClassDoc cd) {
Options localOpt = getGlobalOptions();
localOpt.setOptions(cd);
return localOpt;
}
public Options getOptionsFor(String name) {
return getGlobalOptions();
}
public Options getGlobalOptions() {
return (Options) clone();
}
public void overrideForClass(Options opt, ClassDoc cd) {
// nothing to do
}
|
java
|
{
"resource": ""
}
|
q1353
|
RelationPattern.addRelation
|
train
|
public void addRelation(RelationType relationType, RelationDirection direction) {
int idx = relationType.ordinal();
directions[idx] = directions[idx].sum(direction);
}
|
java
|
{
"resource": ""
}
|
q1354
|
ClassGraph.qualifiedName
|
train
|
private static String qualifiedName(Options opt, String r) {
if (opt.hideGenerics)
r = removeTemplate(r);
// Fast path - nothing to do:
if (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0))
return r;
StringBuilder buf = new StringBuilder(r.length());
qualifiedNameInner(opt, r, buf, 0, !opt.showQualified);
return buf.toString();
}
|
java
|
{
"resource": ""
}
|
q1355
|
ClassGraph.visibility
|
train
|
private String visibility(Options opt, ProgramElementDoc e) {
return opt.showVisibility ? Visibility.get(e).symbol : " ";
}
|
java
|
{
"resource": ""
}
|
q1356
|
ClassGraph.parameter
|
train
|
private String parameter(Options opt, Parameter p[]) {
StringBuilder par = new StringBuilder(1000);
for (int i = 0; i < p.length; i++) {
par.append(p[i].name() + typeAnnotation(opt, p[i].type()));
if (i + 1 < p.length)
par.append(", ");
}
return par.toString();
}
|
java
|
{
"resource": ""
}
|
q1357
|
ClassGraph.type
|
train
|
private String type(Options opt, Type t, boolean generics) {
return ((generics ? opt.showQualifiedGenerics : opt.showQualified) ? //
t.qualifiedTypeName() : t.typeName()) //
+ (opt.hideGenerics ? "" : typeParameters(opt, t.asParameterizedType()));
}
|
java
|
{
"resource": ""
}
|
q1358
|
ClassGraph.typeParameters
|
train
|
private String typeParameters(Options opt, ParameterizedType t) {
if (t == null)
return "";
StringBuffer tp = new StringBuffer(1000).append("<");
Type args[] = t.typeArguments();
for (int i = 0; i < args.length; i++) {
tp.append(type(opt, args[i], true));
if (i != args.length - 1)
tp.append(", ");
}
return tp.append(">").toString();
}
|
java
|
{
"resource": ""
}
|
q1359
|
ClassGraph.attributes
|
train
|
private void attributes(Options opt, FieldDoc fd[]) {
for (FieldDoc f : fd) {
if (hidden(f))
continue;
stereotype(opt, f, Align.LEFT);
String att = visibility(opt, f) + f.name();
if (opt.showType)
att += typeAnnotation(opt, f.type());
tableLine(Align.LEFT, att);
tagvalue(opt, f);
}
}
|
java
|
{
"resource": ""
}
|
q1360
|
ClassGraph.operations
|
train
|
private boolean operations(Options opt, ConstructorDoc m[]) {
boolean printed = false;
for (ConstructorDoc cd : m) {
if (hidden(cd))
continue;
stereotype(opt, cd, Align.LEFT);
String cs = visibility(opt, cd) + cd.name() //
+ (opt.showType ? "(" + parameter(opt, cd.parameters()) + ")" : "()");
tableLine(Align.LEFT, cs);
tagvalue(opt, cd);
printed = true;
}
return printed;
}
|
java
|
{
"resource": ""
}
|
q1361
|
ClassGraph.operations
|
train
|
private boolean operations(Options opt, MethodDoc m[]) {
boolean printed = false;
for (MethodDoc md : m) {
if (hidden(md))
continue;
// Filter-out static initializer method
if (md.name().equals("<clinit>") && md.isStatic() && md.isPackagePrivate())
continue;
stereotype(opt, md, Align.LEFT);
String op = visibility(opt, md) + md.name() + //
(opt.showType ? "(" + parameter(opt, md.parameters()) + ")" + typeAnnotation(opt, md.returnType())
: "()");
tableLine(Align.LEFT, (md.isAbstract() ? Font.ABSTRACT : Font.NORMAL).wrap(opt, op));
printed = true;
tagvalue(opt, md);
}
return printed;
}
|
java
|
{
"resource": ""
}
|
q1362
|
ClassGraph.nodeProperties
|
train
|
private void nodeProperties(Options opt) {
Options def = opt.getGlobalOptions();
if (opt.nodeFontName != def.nodeFontName)
w.print(",fontname=\"" + opt.nodeFontName + "\"");
if (opt.nodeFontColor != def.nodeFontColor)
w.print(",fontcolor=\"" + opt.nodeFontColor + "\"");
if (opt.nodeFontSize != def.nodeFontSize)
w.print(",fontsize=" + fmt(opt.nodeFontSize));
w.print(opt.shape.style);
w.println("];");
}
|
java
|
{
"resource": ""
}
|
q1363
|
ClassGraph.tagvalue
|
train
|
private void tagvalue(Options opt, Doc c) {
Tag tags[] = c.tags("tagvalue");
if (tags.length == 0)
return;
for (Tag tag : tags) {
String t[] = tokenize(tag.text());
if (t.length != 2) {
System.err.println("@tagvalue expects two fields: " + tag.text());
continue;
}
tableLine(Align.RIGHT, Font.TAG.wrap(opt, "{" + t[0] + " = " + t[1] + "}"));
}
}
|
java
|
{
"resource": ""
}
|
q1364
|
ClassGraph.stereotype
|
train
|
private void stereotype(Options opt, Doc c, Align align) {
for (Tag tag : c.tags("stereotype")) {
String t[] = tokenize(tag.text());
if (t.length != 1) {
System.err.println("@stereotype expects one field: " + tag.text());
continue;
}
tableLine(align, guilWrap(opt, t[0]));
}
}
|
java
|
{
"resource": ""
}
|
q1365
|
ClassGraph.hidden
|
train
|
private boolean hidden(ProgramElementDoc c) {
if (c.tags("hidden").length > 0 || c.tags("view").length > 0)
return true;
Options opt = optionProvider.getOptionsFor(c instanceof ClassDoc ? (ClassDoc) c : c.containingClass());
return opt.matchesHideExpression(c.toString()) //
|| (opt.hidePrivateInner && c instanceof ClassDoc && c.isPrivate() && ((ClassDoc) c).containingClass() != null);
}
|
java
|
{
"resource": ""
}
|
q1366
|
ClassGraph.hidden
|
train
|
private boolean hidden(String className) {
className = removeTemplate(className);
ClassInfo ci = classnames.get(className);
return ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);
}
|
java
|
{
"resource": ""
}
|
q1367
|
ClassGraph.allRelation
|
train
|
private void allRelation(Options opt, RelationType rt, ClassDoc from) {
String tagname = rt.lower;
for (Tag tag : from.tags(tagname)) {
String t[] = tokenize(tag.text()); // l-src label l-dst target
t = t.length == 1 ? new String[] { "-", "-", "-", t[0] } : t; // Shorthand
if (t.length != 4) {
System.err.println("Error in " + from + "\n" + tagname + " expects four fields (l-src label l-dst target): " + tag.text());
return;
}
ClassDoc to = from.findClass(t[3]);
if (to != null) {
if(hidden(to))
continue;
relation(opt, rt, from, to, t[0], t[1], t[2]);
} else {
if(hidden(t[3]))
continue;
relation(opt, rt, from, from.toString(), to, t[3], t[0], t[1], t[2]);
}
}
}
|
java
|
{
"resource": ""
}
|
q1368
|
ClassGraph.printRelations
|
train
|
public void printRelations(ClassDoc c) {
Options opt = optionProvider.getOptionsFor(c);
if (hidden(c) || c.name().equals("")) // avoid phantom classes, they may pop up when the source uses annotations
return;
// Print generalization (through the Java superclass)
Type s = c.superclassType();
ClassDoc sc = s != null && !s.qualifiedTypeName().equals(Object.class.getName()) ? s.asClassDoc() : null;
if (sc != null && !c.isEnum() && !hidden(sc))
relation(opt, RelationType.EXTENDS, c, sc, null, null, null);
// Print generalizations (through @extends tags)
for (Tag tag : c.tags("extends"))
if (!hidden(tag.text()))
relation(opt, RelationType.EXTENDS, c, c.findClass(tag.text()), null, null, null);
// Print realizations (Java interfaces)
for (Type iface : c.interfaceTypes()) {
ClassDoc ic = iface.asClassDoc();
if (!hidden(ic))
relation(opt, RelationType.IMPLEMENTS, c, ic, null, null, null);
}
// Print other associations
allRelation(opt, RelationType.COMPOSED, c);
allRelation(opt, RelationType.NAVCOMPOSED, c);
allRelation(opt, RelationType.HAS, c);
allRelation(opt, RelationType.NAVHAS, c);
allRelation(opt, RelationType.ASSOC, c);
allRelation(opt, RelationType.NAVASSOC, c);
allRelation(opt, RelationType.DEPEND, c);
}
|
java
|
{
"resource": ""
}
|
q1369
|
ClassGraph.printExtraClasses
|
train
|
public void printExtraClasses(RootDoc root) {
Set<String> names = new HashSet<String>(classnames.keySet());
for(String className: names) {
ClassInfo info = getClassInfo(className, true);
if (info.nodePrinted)
continue;
ClassDoc c = root.classNamed(className);
if(c != null) {
printClass(c, false);
continue;
}
// Handle missing classes:
Options opt = optionProvider.getOptionsFor(className);
if(opt.matchesHideExpression(className))
continue;
w.println(linePrefix + "// " + className);
w.print(linePrefix + info.name + "[label=");
externalTableStart(opt, className, classToUrl(className));
innerTableStart();
String qualifiedName = qualifiedName(opt, className);
int startTemplate = qualifiedName.indexOf('<');
int idx = qualifiedName.lastIndexOf('.', startTemplate < 0 ? qualifiedName.length() - 1 : startTemplate);
if(opt.postfixPackage && idx > 0 && idx < (qualifiedName.length() - 1)) {
String packageName = qualifiedName.substring(0, idx);
String cn = qualifiedName.substring(idx + 1);
tableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(cn)));
tableLine(Align.CENTER, Font.PACKAGE.wrap(opt, packageName));
} else {
tableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(qualifiedName)));
}
innerTableEnd();
externalTableEnd();
if (className == null || className.length() == 0)
w.print(",URL=\"" + classToUrl(className) + "\"");
nodeProperties(opt);
}
}
|
java
|
{
"resource": ""
}
|
q1370
|
ClassGraph.printInferredRelations
|
train
|
public void printInferredRelations(ClassDoc c) {
// check if the source is excluded from inference
if (hidden(c))
return;
Options opt = optionProvider.getOptionsFor(c);
for (FieldDoc field : c.fields(false)) {
if(hidden(field))
continue;
// skip statics
if(field.isStatic())
continue;
// skip primitives
FieldRelationInfo fri = getFieldRelationInfo(field);
if (fri == null)
continue;
// check if the destination is excluded from inference
if (hidden(fri.cd))
continue;
// if source and dest are not already linked, add a dependency
RelationPattern rp = getClassInfo(c, true).getRelation(fri.cd.toString());
if (rp == null) {
String destAdornment = fri.multiple ? "*" : "";
relation(opt, opt.inferRelationshipType, c, fri.cd, "", "", destAdornment);
}
}
}
|
java
|
{
"resource": ""
}
|
q1371
|
ClassGraph.printInferredDependencies
|
train
|
public void printInferredDependencies(ClassDoc c) {
if (hidden(c))
return;
Options opt = optionProvider.getOptionsFor(c);
Set<Type> types = new HashSet<Type>();
// harvest method return and parameter types
for (MethodDoc method : filterByVisibility(c.methods(false), opt.inferDependencyVisibility)) {
types.add(method.returnType());
for (Parameter parameter : method.parameters()) {
types.add(parameter.type());
}
}
// and the field types
if (!opt.inferRelationships) {
for (FieldDoc field : filterByVisibility(c.fields(false), opt.inferDependencyVisibility)) {
types.add(field.type());
}
}
// see if there are some type parameters
if (c.asParameterizedType() != null) {
ParameterizedType pt = c.asParameterizedType();
types.addAll(Arrays.asList(pt.typeArguments()));
}
// see if type parameters extend something
for(TypeVariable tv: c.typeParameters()) {
if(tv.bounds().length > 0 )
types.addAll(Arrays.asList(tv.bounds()));
}
// and finally check for explicitly imported classes (this
// assumes there are no unused imports...)
if (opt.useImports)
types.addAll(Arrays.asList(importedClasses(c)));
// compute dependencies
for (Type type : types) {
// skip primitives and type variables, as well as dependencies
// on the source class
if (type.isPrimitive() || type instanceof WildcardType || type instanceof TypeVariable
|| c.toString().equals(type.asClassDoc().toString()))
continue;
// check if the destination is excluded from inference
ClassDoc fc = type.asClassDoc();
if (hidden(fc))
continue;
// check if source and destination are in the same package and if we are allowed
// to infer dependencies between classes in the same package
if(!opt.inferDepInPackage && c.containingPackage().equals(fc.containingPackage()))
continue;
// if source and dest are not already linked, add a dependency
RelationPattern rp = getClassInfo(c, true).getRelation(fc.toString());
if (rp == null || rp.matchesOne(new RelationPattern(RelationDirection.OUT))) {
relation(opt, RelationType.DEPEND, c, fc, "", "", "");
}
}
}
|
java
|
{
"resource": ""
}
|
q1372
|
ClassGraph.filterByVisibility
|
train
|
private <T extends ProgramElementDoc> List<T> filterByVisibility(T[] docs, Visibility visibility) {
if (visibility == Visibility.PRIVATE)
return Arrays.asList(docs);
List<T> filtered = new ArrayList<T>();
for (T doc : docs) {
if (Visibility.get(doc).compareTo(visibility) > 0)
filtered.add(doc);
}
return filtered;
}
|
java
|
{
"resource": ""
}
|
q1373
|
ClassGraph.firstInnerTableStart
|
train
|
private void firstInnerTableStart(Options opt) {
w.print(linePrefix + linePrefix + "<tr>" + opt.shape.extraColumn() +
"<td><table border=\"0\" cellspacing=\"0\" " +
"cellpadding=\"1\">" + linePostfix);
}
|
java
|
{
"resource": ""
}
|
q1374
|
AbstractMavenScroogeMojo.extractThriftFile
|
train
|
private File extractThriftFile(String artifactId, String fileName, Set<File> thriftFiles) {
for (File thriftFile : thriftFiles) {
boolean fileFound = false;
if (fileName.equals(thriftFile.getName())) {
for (String pathComponent : thriftFile.getPath().split(File.separator)) {
if (pathComponent.equals(artifactId)) {
fileFound = true;
}
}
}
if (fileFound) {
return thriftFile;
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q1375
|
AbstractMavenScroogeMojo.execute
|
train
|
public void execute() throws MojoExecutionException, MojoFailureException {
try {
Set<File> thriftFiles = findThriftFiles();
final File outputDirectory = getOutputDirectory();
ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());
Set<String> compileRoots = new HashSet<String>();
compileRoots.add("scrooge");
if (thriftFiles.isEmpty()) {
getLog().info("No thrift files to compile.");
} else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {
getLog().info("Generated thrift files up to date, skipping compile.");
attachFiles(compileRoots);
} else {
outputDirectory.mkdirs();
// Quick fix to fix issues with two mvn installs in a row (ie no clean)
cleanDirectory(outputDirectory);
getLog().info(format("compiling thrift files %s with Scrooge", thriftFiles));
synchronized(lock) {
ScroogeRunner runner = new ScroogeRunner();
Map<String, String> thriftNamespaceMap = new HashMap<String, String>();
for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {
thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());
}
// Include thrifts from resource as well.
Set<File> includes = thriftIncludes;
includes.add(getResourcesOutputDirectory());
// Include thrift root
final File thriftSourceRoot = getThriftSourceRoot();
if (thriftSourceRoot != null && thriftSourceRoot.exists()) {
includes.add(thriftSourceRoot);
}
runner.compile(
getLog(),
includeOutputDirectoryNamespace ? new File(outputDirectory, "scrooge") : outputDirectory,
thriftFiles,
includes,
thriftNamespaceMap,
language,
thriftOpts);
}
attachFiles(compileRoots);
}
} catch (IOException e) {
throw new MojoExecutionException("An IO error occurred", e);
}
}
|
java
|
{
"resource": ""
}
|
q1376
|
AbstractMavenScroogeMojo.lastModified
|
train
|
private long lastModified(Set<File> files) {
long result = 0;
for (File file : files) {
if (file.lastModified() > result)
result = file.lastModified();
}
return result;
}
|
java
|
{
"resource": ""
}
|
q1377
|
AbstractMavenScroogeMojo.findThriftFiles
|
train
|
private Set<File> findThriftFiles() throws IOException, MojoExecutionException {
final File thriftSourceRoot = getThriftSourceRoot();
Set<File> thriftFiles = new HashSet<File>();
if (thriftSourceRoot != null && thriftSourceRoot.exists()) {
thriftFiles.addAll(findThriftFilesInDirectory(thriftSourceRoot));
}
getLog().info("finding thrift files in dependencies");
extractFilesFromDependencies(findThriftDependencies(), getResourcesOutputDirectory());
if (buildExtractedThrift && getResourcesOutputDirectory().exists()) {
thriftFiles.addAll(findThriftFilesInDirectory(getResourcesOutputDirectory()));
}
getLog().info("finding thrift files in referenced (reactor) projects");
thriftFiles.addAll(getReferencedThriftFiles());
return thriftFiles;
}
|
java
|
{
"resource": ""
}
|
q1378
|
AbstractMavenScroogeMojo.findThriftDependencies
|
train
|
private Set<Artifact> findThriftDependencies() throws IOException, MojoExecutionException {
Set<Artifact> thriftDependencies = new HashSet<Artifact>();
Set<Artifact> deps = new HashSet<Artifact>();
deps.addAll(project.getArtifacts());
deps.addAll(project.getDependencyArtifacts());
Map<String, Artifact> depsMap = new HashMap<String, Artifact>();
for (Artifact dep : deps) {
depsMap.put(dep.getId(), dep);
}
for (Artifact artifact : deps) {
// This artifact has an idl classifier.
if (isIdlCalssifier(artifact, classifier)) {
thriftDependencies.add(artifact);
} else {
if (isDepOfIdlArtifact(artifact, depsMap)) {
// Fetch idl artifact for dependency of an idl artifact.
try {
Artifact idlArtifact = MavenScroogeCompilerUtil.getIdlArtifact(
artifact,
artifactFactory,
artifactResolver,
localRepository,
remoteArtifactRepositories,
classifier);
thriftDependencies.add(idlArtifact);
} catch (MojoExecutionException e) {
/* Do nothing as this artifact is not an idl artifact
binary jars may have dependency on thrift lib etc.
*/
getLog().debug("Could not fetch idl jar for " + artifact);
}
}
}
}
return thriftDependencies;
}
|
java
|
{
"resource": ""
}
|
q1379
|
AbstractMavenScroogeMojo.getRecursiveThriftFiles
|
train
|
protected List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory) throws IOException {
return getRecursiveThriftFiles(project, outputDirectory, new ArrayList<File>());
}
|
java
|
{
"resource": ""
}
|
q1380
|
AbstractMavenScroogeMojo.getRecursiveThriftFiles
|
train
|
List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files) throws IOException {
HashFunction hashFun = Hashing.md5();
File dir = new File(new File(project.getFile().getParent(), "target"), outputDirectory);
if (dir.exists()) {
URI baseDir = getFileURI(dir);
for (File f : findThriftFilesInDirectory(dir)) {
URI fileURI = getFileURI(f);
String relPath = baseDir.relativize(fileURI).getPath();
File destFolder = getResourcesOutputDirectory();
destFolder.mkdirs();
File destFile = new File(destFolder, relPath);
if (!destFile.exists() || (destFile.isFile() && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {
getLog().info(format("copying %s to %s", f.getCanonicalPath(), destFile.getCanonicalPath()));
copyFile(f, destFile);
}
files.add(destFile);
}
}
Map<String, MavenProject> refs = project.getProjectReferences();
for (String name : refs.keySet()) {
getRecursiveThriftFiles(refs.get(name), outputDirectory, files);
}
return files;
}
|
java
|
{
"resource": ""
}
|
q1381
|
AbstractMavenScroogeMojo.isDepOfIdlArtifact
|
train
|
private boolean isDepOfIdlArtifact(Artifact artifact, Map<String, Artifact> depsMap) {
List<String> depTrail = artifact.getDependencyTrail();
// depTrail can be null sometimes, which seems like a maven bug
if (depTrail != null) {
for (String name : depTrail) {
Artifact dep = depsMap.get(name);
if (dep != null && isIdlCalssifier(dep, classifier)) {
return true;
}
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q1382
|
MavenScroogeCompilerUtil.getIdlArtifact
|
train
|
public static Artifact getIdlArtifact(Artifact artifact, ArtifactFactory artifactFactory,
ArtifactResolver artifactResolver,
ArtifactRepository localRepository,
List<ArtifactRepository> remoteRepos,
String classifier)
throws MojoExecutionException {
Artifact idlArtifact = artifactFactory.createArtifactWithClassifier(
artifact.getGroupId(),
artifact.getArtifactId(),
artifact.getVersion(),
"jar",
classifier);
try {
artifactResolver.resolve(idlArtifact, remoteRepos, localRepository);
return idlArtifact;
} catch (final ArtifactResolutionException e) {
throw new MojoExecutionException(
"Failed to resolve one or more idl artifacts:\n\n" + e.getMessage(), e);
} catch (final ArtifactNotFoundException e) {
throw new MojoExecutionException(
"Failed to resolve one or more idl artifacts:\n\n" + e.getMessage(), e);
}
}
|
java
|
{
"resource": ""
}
|
q1383
|
Func.lift
|
train
|
public static<Z> Function0<Z> lift(Func0<Z> f) {
return bridge.lift(f);
}
|
java
|
{
"resource": ""
}
|
q1384
|
Func.lift
|
train
|
public static<A, Z> Function1<A, Z> lift(Func1<A, Z> f) {
return bridge.lift(f);
}
|
java
|
{
"resource": ""
}
|
q1385
|
Func.lift
|
train
|
public static<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) {
return bridge.lift(f);
}
|
java
|
{
"resource": ""
}
|
q1386
|
Func.lift
|
train
|
public static<A, B, C, Z> Function3<A, B, C, Z> lift(Func3<A, B, C, Z> f) {
return bridge.lift(f);
}
|
java
|
{
"resource": ""
}
|
q1387
|
Func.lift
|
train
|
public static<A, B, C, D, Z> Function4<A, B, C, D, Z> lift(Func4<A, B, C, D, Z> f) {
return bridge.lift(f);
}
|
java
|
{
"resource": ""
}
|
q1388
|
Func.lift
|
train
|
public static<Z> Function0<Z> lift(Callable<Z> f) {
return bridge.lift(f);
}
|
java
|
{
"resource": ""
}
|
q1389
|
Css.sel
|
train
|
public static CssSel sel(String selector, String value) {
return j.sel(selector, value);
}
|
java
|
{
"resource": ""
}
|
q1390
|
VendorJ.vendor
|
train
|
public static<T> Vendor<T> vendor(Func0<T> f) {
return j.vendor(f);
}
|
java
|
{
"resource": ""
}
|
q1391
|
VendorJ.vendor
|
train
|
public static<T> Vendor<T> vendor(Callable<T> f) {
return j.vendor(f);
}
|
java
|
{
"resource": ""
}
|
q1392
|
VarsJ.vendSessionVar
|
train
|
public static<T> SessionVar<T> vendSessionVar(T defValue) {
return (new VarsJBridge()).vendSessionVar(defValue, new Exception());
}
|
java
|
{
"resource": ""
}
|
q1393
|
VarsJ.vendSessionVar
|
train
|
public static<T> SessionVar<T> vendSessionVar(Callable<T> defFunc) {
return (new VarsJBridge()).vendSessionVar(defFunc, new Exception());
}
|
java
|
{
"resource": ""
}
|
q1394
|
Router.dispatchCommand
|
train
|
protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) {
routingFor(routable1)
.routees()
.forEach(routee -> routee.receiveCommand(action, routable1));
}
|
java
|
{
"resource": ""
}
|
q1395
|
CoreSyncMongoIterableImpl.first
|
train
|
@Nullable
public ResultT first() {
final CoreRemoteMongoCursor<ResultT> cursor = iterator();
if (!cursor.hasNext()) {
return null;
}
return cursor.next();
}
|
java
|
{
"resource": ""
}
|
q1396
|
CoreSyncMongoIterableImpl.map
|
train
|
public <U> CoreRemoteMongoIterable<U> map(final Function<ResultT, U> mapper) {
return new CoreRemoteMappingIterable<>(this, mapper);
}
|
java
|
{
"resource": ""
}
|
q1397
|
CoreSyncMongoIterableImpl.into
|
train
|
public <A extends Collection<? super ResultT>> A into(final A target) {
forEach(new Block<ResultT>() {
@Override
public void apply(@Nonnull final ResultT t) {
target.add(t);
}
});
return target;
}
|
java
|
{
"resource": ""
}
|
q1398
|
AwsServiceClientImpl.withCodecRegistry
|
train
|
public AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) {
return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher);
}
|
java
|
{
"resource": ""
}
|
q1399
|
CoreStitchAppClient.callFunction
|
train
|
public void callFunction(
final String name,
final List<?> args,
final @Nullable Long requestTimeout) {
this.functionService.callFunction(name, args, requestTimeout);
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.