_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q2100
CmsXmlConfigUpdater.transform
train
public void transform(String name, String transform) throws Exception { File configFile = new File(m_configDir, name); File transformFile = new File(m_xsltDir, transform); try (InputStream stream = new FileInputStream(transformFile)) { StreamSource source = new StreamSource(stream); transform(configFile, source); } }
java
{ "resource": "" }
q2101
CmsXmlConfigUpdater.transformConfig
train
public void transformConfig() throws Exception { List<TransformEntry> entries = readTransformEntries(new File(m_xsltDir, "transforms.xml")); for (TransformEntry entry : entries) { transform(entry.getConfigFile(), entry.getXslt()); } m_isDone = true; }
java
{ "resource": "" }
q2102
CmsXmlConfigUpdater.validationErrors
train
public String validationErrors() { List<String> errors = new ArrayList<>(); for (File config : getConfigFiles()) { String filename = config.getName(); try (FileInputStream stream = new FileInputStream(config)) { CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(stream, false), new CmsXmlEntityResolver(null), true); } catch (CmsXmlException e) { errors.add(filename + ":" + e.getCause().getMessage()); } catch (Exception e) { errors.add(filename + ":" + e.getMessage()); } } if (errors.size() == 0) { return null; } String errString = CmsStringUtil.listAsString(errors, "\n"); JSONObject obj = new JSONObject(); try { obj.put("err", errString); } catch (JSONException e) { } return obj.toString(); }
java
{ "resource": "" }
q2103
CmsXmlConfigUpdater.getConfigFiles
train
private List<File> getConfigFiles() { String[] filenames = { "opencms-modules.xml", "opencms-system.xml", "opencms-vfs.xml", "opencms-importexport.xml", "opencms-sites.xml", "opencms-variables.xml", "opencms-scheduler.xml", "opencms-workplace.xml", "opencms-search.xml"}; List<File> result = new ArrayList<>(); for (String fn : filenames) { File file = new File(m_configDir, fn); if (file.exists()) { result.add(file); } } return result; }
java
{ "resource": "" }
q2104
CmsXmlConfigUpdater.readTransformEntries
train
private List<TransformEntry> readTransformEntries(File file) throws Exception { List<TransformEntry> result = new ArrayList<>(); try (FileInputStream fis = new FileInputStream(file)) { byte[] data = CmsFileUtil.readFully(fis, false); Document doc = CmsXmlUtils.unmarshalHelper(data, null, false); for (Node node : doc.selectNodes("//transform")) { Element elem = ((Element)node); String xslt = elem.attributeValue("xslt"); String conf = elem.attributeValue("config"); TransformEntry entry = new TransformEntry(conf, xslt); result.add(entry); } } return result; }
java
{ "resource": "" }
q2105
CmsXmlConfigUpdater.transform
train
private void transform(File file, Source transformSource) throws TransformerConfigurationException, IOException, SAXException, TransformerException, ParserConfigurationException { Transformer transformer = m_transformerFactory.newTransformer(transformSource); transformer.setOutputProperty(OutputKeys.ENCODING, "us-ascii"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); String configDirPath = m_configDir.getAbsolutePath(); configDirPath = configDirPath.replaceFirst("[/\\\\]$", ""); transformer.setParameter("configDir", configDirPath); XMLReader reader = m_parserFactory.newSAXParser().getXMLReader(); reader.setEntityResolver(NO_ENTITY_RESOLVER); Source source; if (file.exists()) { source = new SAXSource(reader, new InputSource(file.getCanonicalPath())); } else { source = new SAXSource(reader, new InputSource(new ByteArrayInputStream(DEFAULT_XML.getBytes("UTF-8")))); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); Result target = new StreamResult(baos); transformer.transform(source, target); byte[] transformedConfig = baos.toByteArray(); try (FileOutputStream output = new FileOutputStream(file)) { output.write(transformedConfig); } }
java
{ "resource": "" }
q2106
CmsJspNavElement.getSubNavigation
train
public List<CmsJspNavElement> getSubNavigation() { if (m_subNavigation == null) { if (m_resource.isFile()) { m_subNavigation = Collections.emptyList(); } else if (m_navContext == null) { try { throw new Exception("Can not get subnavigation because navigation context is not set."); } catch (Exception e) { LOG.warn(e.getLocalizedMessage(), e); m_subNavigation = Collections.emptyList(); } } else { CmsJspNavBuilder navBuilder = m_navContext.getNavBuilder(); m_subNavigation = navBuilder.getNavigationForFolder( navBuilder.getCmsObject().getSitePath(m_resource), m_navContext.getVisibility(), m_navContext.getFilter()); } } return m_subNavigation; }
java
{ "resource": "" }
q2107
CmsJspNavElement.getLocaleProperties
train
private Map<String, String> getLocaleProperties() { if (m_localeProperties == null) { m_localeProperties = CmsCollectionsGenericWrapper.createLazyMap( new CmsProperty.CmsPropertyLocaleTransformer(m_properties, m_locale)); } return m_localeProperties; }
java
{ "resource": "" }
q2108
CmsPatternPanelDailyController.setEveryWorkingDay
train
public void setEveryWorkingDay(final boolean isEveryWorkingDay) { if (m_model.isEveryWorkingDay() != isEveryWorkingDay) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay)); m_model.setInterval(getPatternDefaultValues().getInterval()); onValueChange(); } }); } }
java
{ "resource": "" }
q2109
CmsUploadBean.removeListener
train
private void removeListener(CmsUUID listenerId) { getRequest().getSession().removeAttribute(SESSION_ATTRIBUTE_LISTENER_ID); m_listeners.remove(listenerId); }
java
{ "resource": "" }
q2110
CmsFormatterBeanParser.parseAttributes
train
private Map<String, String> parseAttributes(I_CmsXmlContentLocation formatterLoc) { Map<String, String> result = new LinkedHashMap<>(); for (I_CmsXmlContentValueLocation mappingLoc : formatterLoc.getSubValues(N_ATTRIBUTE)) { String key = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_KEY)); String value = CmsConfigurationReader.getString(m_cms, mappingLoc.getSubValue(N_VALUE)); result.put(key, value); } return Collections.unmodifiableMap(result); }
java
{ "resource": "" }
q2111
CmsADEManager.getConfiguredWorkplaceBundles
train
public Set<String> getConfiguredWorkplaceBundles() { CmsADEConfigData configData = internalLookupConfiguration(null, null); return configData.getConfiguredWorkplaceBundles(); }
java
{ "resource": "" }
q2112
CmsLinkManager.removeOpenCmsContext
train
public static String removeOpenCmsContext(final String path) { String context = OpenCms.getSystemInfo().getOpenCmsContext(); if (path.startsWith(context + "/")) { return path.substring(context.length()); } String renderPrefix = OpenCms.getStaticExportManager().getVfsPrefix(); if (path.startsWith(renderPrefix + "/")) { return path.substring(renderPrefix.length()); } return path; }
java
{ "resource": "" }
q2113
CmsLinkManager.getPermalink
train
public String getPermalink(CmsObject cms, String resourceName, CmsUUID detailContentId) { String permalink = ""; try { permalink = substituteLink(cms, CmsPermalinkResourceHandler.PERMALINK_HANDLER); String id = cms.readResource(resourceName, CmsResourceFilter.ALL).getStructureId().toString(); permalink += id; if (detailContentId != null) { permalink += ":" + detailContentId; } String ext = CmsFileUtil.getExtension(resourceName); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(ext)) { permalink += ext; } CmsSite currentSite = OpenCms.getSiteManager().getCurrentSite(cms); String serverPrefix = null; if (currentSite == OpenCms.getSiteManager().getDefaultSite()) { Optional<CmsSite> siteForDefaultUri = OpenCms.getSiteManager().getSiteForDefaultUri(); if (siteForDefaultUri.isPresent()) { serverPrefix = siteForDefaultUri.get().getServerPrefix(cms, resourceName); } else { serverPrefix = OpenCms.getSiteManager().getWorkplaceServer(); } } else { serverPrefix = currentSite.getServerPrefix(cms, resourceName); } if (!permalink.startsWith(serverPrefix)) { permalink = serverPrefix + permalink; } } catch (CmsException e) { // if something wrong permalink = e.getLocalizedMessage(); if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } return permalink; }
java
{ "resource": "" }
q2114
CmsLinkManager.getPermalinkForCurrentPage
train
public String getPermalinkForCurrentPage(CmsObject cms) { return getPermalink(cms, cms.getRequestContext().getUri(), cms.getRequestContext().getDetailContentId()); }
java
{ "resource": "" }
q2115
CmsLinkManager.getWorkplaceLink
train
public String getWorkplaceLink(CmsObject cms, String resourceName, boolean forceSecure) { String result = substituteLinkForUnknownTarget(cms, resourceName, forceSecure); return appendServerPrefix(cms, result, resourceName, true); }
java
{ "resource": "" }
q2116
CmsSqlConsoleResultsForm.buildTable
train
private Table buildTable(CmsSqlConsoleResults results) { IndexedContainer container = new IndexedContainer(); int numCols = results.getColumns().size(); for (int c = 0; c < numCols; c++) { container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null); } int r = 0; for (List<Object> row : results.getData()) { Item item = container.addItem(Integer.valueOf(r)); for (int c = 0; c < numCols; c++) { item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c)); } r += 1; } Table table = new Table(); table.setContainerDataSource(container); for (int c = 0; c < numCols; c++) { String col = (results.getColumns().get(c)); table.setColumnHeader(Integer.valueOf(c), col); } table.setWidth("100%"); table.setHeight("100%"); table.setColumnCollapsingAllowed(true); return table; }
java
{ "resource": "" }
q2117
CmsPropertiesTab.updateImageInfo
train
private void updateImageInfo() { String crop = getCrop(); String point = getPoint(); m_imageInfoDisplay.fillContent(m_info, crop, point); }
java
{ "resource": "" }
q2118
CmsShell.getTopShell
train
public static CmsShell getTopShell() { ArrayList<CmsShell> shells = SHELL_STACK.get(); if (shells.isEmpty()) { return null; } return shells.get(shells.size() - 1); }
java
{ "resource": "" }
q2119
CmsShell.popShell
train
public static void popShell() { ArrayList<CmsShell> shells = SHELL_STACK.get(); if (shells.size() > 0) { shells.remove(shells.size() - 1); } }
java
{ "resource": "" }
q2120
CmsSearchConfigurationSorting.create
train
public static CmsSearchConfigurationSorting create( final String sortParam, final List<I_CmsSearchConfigurationSortOption> options, final I_CmsSearchConfigurationSortOption defaultOption) { return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption) ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption) : null; }
java
{ "resource": "" }
q2121
CmsResourceTypeStatResultList.init
train
public static CmsResourceTypeStatResultList init(CmsResourceTypeStatResultList resList) { if (resList == null) { return new CmsResourceTypeStatResultList(); } resList.deleteOld(); return resList; }
java
{ "resource": "" }
q2122
CmsExport.exportWithMinimalMetaData
train
protected boolean exportWithMinimalMetaData(String path) { String checkPath = path.startsWith("/") ? path + "/" : "/" + path + "/"; for (String p : m_parameters.getResourcesToExportWithMetaData()) { if (checkPath.startsWith(p)) { return false; } } return true; }
java
{ "resource": "" }
q2123
DOMImplWebkit.setDraggable
train
@Override public void setDraggable(Element elem, String draggable) { super.setDraggable(elem, draggable); if ("true".equals(draggable)) { elem.getStyle().setProperty("webkitUserDrag", "element"); } else { elem.getStyle().clearProperty("webkitUserDrag"); } }
java
{ "resource": "" }
q2124
CmsNewResourceTypeDialog.createParentXmlElements
train
protected void createParentXmlElements(CmsXmlContent xmlContent, String xmlPath, Locale l) { if (CmsXmlUtils.isDeepXpath(xmlPath)) { String parentPath = CmsXmlUtils.removeLastXpathElement(xmlPath); if (null == xmlContent.getValue(parentPath, l)) { createParentXmlElements(xmlContent, parentPath, l); xmlContent.addValue(m_cms, parentPath, l, CmsXmlUtils.getXpathIndexInt(parentPath) - 1); } } }
java
{ "resource": "" }
q2125
Scheme.join
train
public byte[] join(Map<Integer, byte[]> parts) { checkArgument(parts.size() > 0, "No parts provided"); final int[] lengths = parts.values().stream().mapToInt(v -> v.length).distinct().toArray(); checkArgument(lengths.length == 1, "Varying lengths of part values"); final byte[] secret = new byte[lengths[0]]; for (int i = 0; i < secret.length; i++) { final byte[][] points = new byte[parts.size()][2]; int j = 0; for (Map.Entry<Integer, byte[]> part : parts.entrySet()) { points[j][0] = part.getKey().byteValue(); points[j][1] = part.getValue()[i]; j++; } secret[i] = GF256.interpolate(points); } return secret; }
java
{ "resource": "" }
q2126
Processor.sink
train
public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) { io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system); return new Processor(p); }
java
{ "resource": "" }
q2127
Processor.source
train
public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) { io.gearpump.streaming.Processor<DataSourceTask<Object, Object>> p = DataSourceProcessor.apply(source, parallelism, description, taskConf, system); return new Processor(p); }
java
{ "resource": "" }
q2128
BeetlAntlrErrorStrategy.recoverInline
train
@Override public Token recoverInline(Parser recognizer) throws RecognitionException { // SINGLE TOKEN DELETION Token matchedSymbol = singleTokenDeletion(recognizer); if (matchedSymbol != null) { // we have deleted the extra token. // now, move past ttype token as if all were ok recognizer.consume(); return matchedSymbol; } // SINGLE TOKEN INSERTION if (singleTokenInsertion(recognizer)) { return getMissingSymbol(recognizer); } // BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR); // exception.pushToken(this.getGrammarToken(recognizer.getCurrentToken())); // throw exception; throw new InputMismatchException(recognizer); }
java
{ "resource": "" }
q2129
AntlrProgramBuilder.parseDirectiveStatement
train
protected DirectiveStatement parseDirectiveStatement(DirectiveStContext node) { DirectiveStContext stContext = (DirectiveStContext) node; DirectiveExpContext direExp = stContext.directiveExp(); Token token = direExp.Identifier().getSymbol(); String directive = token.getText().toLowerCase().intern(); TerminalNode value = direExp.StringLiteral(); List<TerminalNode> idNodeList = null; DirectiveExpIDListContext directExpidLisCtx = direExp.directiveExpIDList(); if (directExpidLisCtx != null) { idNodeList = directExpidLisCtx.Identifier(); } Set<String> idList = null; DirectiveStatement ds = null; if (value != null) { String idListValue = this.getStringValue(value.getText()); idList = new HashSet(Arrays.asList(idListValue.split(","))); ds = new DirectiveStatement(directive, idList, this.getBTToken(token)); } else if (idNodeList != null) { idList = new HashSet<String>(); for (TerminalNode t : idNodeList) { idList.add(t.getText()); } ds = new DirectiveStatement(directive, idList, this.getBTToken(token)); } else { ds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token)); } if (directive.equals("dynamic")) { if (ds.getIdList().size() == 0) { data.allDynamic = true; } else { data.dynamicObjectSet = ds.getIdList(); } ds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token)); return ds; } else if (directive.equalsIgnoreCase("safe_output_open".intern())) { this.pbCtx.isSafeOutput = true; return ds; } else if (directive.equalsIgnoreCase("safe_output_close".intern())) { this.pbCtx.isSafeOutput = false; return ds; } else { return ds; } }
java
{ "resource": "" }
q2130
NamingConventions.determineNamingConvention
train
public static NamingConvention determineNamingConvention( TypeElement type, Iterable<ExecutableElement> methods, Messager messager, Types types) { ExecutableElement beanMethod = null; ExecutableElement prefixlessMethod = null; for (ExecutableElement method : methods) { switch (methodNameConvention(method)) { case BEAN: beanMethod = firstNonNull(beanMethod, method); break; case PREFIXLESS: prefixlessMethod = firstNonNull(prefixlessMethod, method); break; default: break; } } if (prefixlessMethod != null) { if (beanMethod != null) { messager.printMessage( ERROR, "Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '" + beanMethod.getSimpleName() + "' and '" + prefixlessMethod.getSimpleName() + "'", type); } return new PrefixlessConvention(messager, types); } else { return new BeanConvention(messager, types); } }
java
{ "resource": "" }
q2131
SourceBuilder.add
train
public SourceBuilder add(String fmt, Object... args) { TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt); return this; }
java
{ "resource": "" }
q2132
SourceBuilder.addLine
train
public SourceBuilder addLine(String fmt, Object... args) { add(fmt, args); source.append(LINE_SEPARATOR); return this; }
java
{ "resource": "" }
q2133
Analyser.findUnderriddenMethods
train
private Map<StandardMethod, UnderrideLevel> findUnderriddenMethods( Iterable<ExecutableElement> methods) { Map<StandardMethod, ExecutableElement> standardMethods = new LinkedHashMap<>(); for (ExecutableElement method : methods) { Optional<StandardMethod> standardMethod = maybeStandardMethod(method); if (standardMethod.isPresent() && isUnderride(method)) { standardMethods.put(standardMethod.get(), method); } } if (standardMethods.containsKey(StandardMethod.EQUALS) != standardMethods.containsKey(StandardMethod.HASH_CODE)) { ExecutableElement underriddenMethod = standardMethods.containsKey(StandardMethod.EQUALS) ? standardMethods.get(StandardMethod.EQUALS) : standardMethods.get(StandardMethod.HASH_CODE); messager.printMessage(ERROR, "hashCode and equals must be implemented together on FreeBuilder types", underriddenMethod); } ImmutableMap.Builder<StandardMethod, UnderrideLevel> result = ImmutableMap.builder(); for (StandardMethod standardMethod : standardMethods.keySet()) { if (standardMethods.get(standardMethod).getModifiers().contains(Modifier.FINAL)) { result.put(standardMethod, UnderrideLevel.FINAL); } else { result.put(standardMethod, UnderrideLevel.OVERRIDEABLE); } } return result.build(); }
java
{ "resource": "" }
q2134
Analyser.hasToBuilderMethod
train
private boolean hasToBuilderMethod( DeclaredType builder, boolean isExtensible, Iterable<ExecutableElement> methods) { for (ExecutableElement method : methods) { if (isToBuilderMethod(builder, method)) { if (!isExtensible) { messager.printMessage(ERROR, "No accessible no-args Builder constructor available to implement toBuilder", method); } return true; } } return false; }
java
{ "resource": "" }
q2135
Analyser.generatedBuilderSimpleName
train
private String generatedBuilderSimpleName(TypeElement type) { String packageName = elements.getPackageOf(type).getQualifiedName().toString(); String originalName = type.getQualifiedName().toString(); checkState(originalName.startsWith(packageName + ".")); String nameWithoutPackage = originalName.substring(packageName.length() + 1); return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll("\\.", "_")); }
java
{ "resource": "" }
q2136
ToStringGenerator.addToString
train
public static void addToString( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, boolean forPartial) { String typename = (forPartial ? "partial " : "") + datatype.getType().getSimpleName(); Predicate<PropertyCodeGenerator> isOptional = generator -> { Initially initially = generator.initialState(); return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial)); }; boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional); boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional) && !generatorsByProperty.isEmpty(); code.addLine("") .addLine("@%s", Override.class) .addLine("public %s toString() {", String.class); if (allOptional) { bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename); } else if (anyOptional) { bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional); } else { bodyWithConcatenation(code, generatorsByProperty, typename); } code.addLine("}"); }
java
{ "resource": "" }
q2137
ToStringGenerator.bodyWithConcatenation
train
private static void bodyWithConcatenation( SourceBuilder code, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename) { code.add(" return \"%s{", typename); String prefix = ""; for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); code.add("%s%s=\" + %s + \"", prefix, property.getName(), (Excerpt) generator::addToStringValue); prefix = ", "; } code.add("}\";%n"); }
java
{ "resource": "" }
q2138
ToStringGenerator.bodyWithBuilder
train
private static void bodyWithBuilder( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename, Predicate<PropertyCodeGenerator> isOptional) { Variable result = new Variable("result"); code.add(" %1$s %2$s = new %1$s(\"%3$s{", StringBuilder.class, result, typename); boolean midStringLiteral = true; boolean midAppends = true; boolean prependCommas = false; PropertyCodeGenerator lastOptionalGenerator = generatorsByProperty.values() .stream() .filter(isOptional) .reduce((first, second) -> second) .get(); for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); if (isOptional.test(generator)) { if (midStringLiteral) { code.add("\")"); } if (midAppends) { code.add(";%n "); } code.add("if ("); if (generator.initialState() == Initially.OPTIONAL) { generator.addToStringCondition(code); } else { code.add("!%s.contains(%s.%s)", UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName()); } code.add(") {%n %s.append(\"", result); if (prependCommas) { code.add(", "); } code.add("%s=\").append(%s)", property.getName(), property.getField()); if (!prependCommas) { code.add(".append(\", \")"); } code.add(";%n }%n "); if (generator.equals(lastOptionalGenerator)) { code.add("return %s.append(\"", result); midStringLiteral = true; midAppends = true; } else { midStringLiteral = false; midAppends = false; } } else { if (!midAppends) { code.add("%s", result); } if (!midStringLiteral) { code.add(".append(\""); } if (prependCommas) { code.add(", "); } code.add("%s=\").append(%s)", property.getName(), (Excerpt) generator::addToStringValue); midStringLiteral = false; midAppends = true; prependCommas = true; } } checkState(prependCommas, "Unexpected state at end of toString method"); checkState(midAppends, "Unexpected state at end of toString method"); if (!midStringLiteral) { code.add(".append(\""); } code.add("}\").toString();%n", result); }
java
{ "resource": "" }
q2139
ToStringGenerator.bodyWithBuilderAndSeparator
train
private static void bodyWithBuilderAndSeparator( SourceBuilder code, Datatype datatype, Map<Property, PropertyCodeGenerator> generatorsByProperty, String typename) { Variable result = new Variable("result"); Variable separator = new Variable("separator"); code.addLine(" %1$s %2$s = new %1$s(\"%3$s{\");", StringBuilder.class, result, typename); if (generatorsByProperty.size() > 1) { // If there's a single property, we don't actually use the separator variable code.addLine(" %s %s = \"\";", String.class, separator); } Property first = generatorsByProperty.keySet().iterator().next(); Property last = getLast(generatorsByProperty.keySet()); for (Property property : generatorsByProperty.keySet()) { PropertyCodeGenerator generator = generatorsByProperty.get(property); switch (generator.initialState()) { case HAS_DEFAULT: throw new RuntimeException("Internal error: unexpected default field"); case OPTIONAL: code.addLine(" if (%s) {", (Excerpt) generator::addToStringCondition); break; case REQUIRED: code.addLine(" if (!%s.contains(%s.%s)) {", UNSET_PROPERTIES, datatype.getPropertyEnum(), property.getAllCapsName()); break; } code.add(" ").add(result); if (property != first) { code.add(".append(%s)", separator); } code.add(".append(\"%s=\").append(%s)", property.getName(), (Excerpt) generator::addToStringValue); if (property != last) { code.add(";%n %s = \", \"", separator); } code.add(";%n }%n"); } code.addLine(" return %s.append(\"}\").toString();", result); }
java
{ "resource": "" }
q2140
LazyName.addLazyDefinitions
train
public static void addLazyDefinitions(SourceBuilder code) { Set<Declaration> defined = new HashSet<>(); // Definitions may lazily declare new names; ensure we add them all List<Declaration> declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList()); while (!defined.containsAll(declarations)) { for (Declaration declaration : declarations) { if (defined.add(declaration)) { code.add(code.scope().get(declaration).definition); } } declarations = code.scope().keysOfType(Declaration.class).stream().sorted().collect(toList()); } }
java
{ "resource": "" }
q2141
PropertyCodeGenerator.addPartialFieldAssignment
train
public void addPartialFieldAssignment( SourceBuilder code, Excerpt finalField, String builder) { addFinalFieldAssignment(code, finalField, builder); }
java
{ "resource": "" }
q2142
MergeAction.addActionsTo
train
public static void addActionsTo( SourceBuilder code, Set<MergeAction> mergeActions, boolean forBuilder) { SetMultimap<String, String> nounsByVerb = TreeMultimap.create(); mergeActions.forEach(mergeAction -> { if (forBuilder || !mergeAction.builderOnly) { nounsByVerb.put(mergeAction.verb, mergeAction.noun); } }); List<String> verbs = ImmutableList.copyOf(nounsByVerb.keySet()); String lastVerb = getLast(verbs, null); for (String verb : nounsByVerb.keySet()) { code.add(", %s%s", (verbs.size() > 1 && verb.equals(lastVerb)) ? "and " : "", verb); List<String> nouns = ImmutableList.copyOf(nounsByVerb.get(verb)); for (int i = 0; i < nouns.size(); ++i) { String separator = (i == 0) ? "" : (i == nouns.size() - 1) ? " and" : ","; code.add("%s %s", separator, nouns.get(i)); } } }
java
{ "resource": "" }
q2143
Declarations.upcastToGeneratedBuilder
train
public static Variable upcastToGeneratedBuilder( SourceBuilder code, Datatype datatype, String builder) { return code.scope().computeIfAbsent(Declaration.UPCAST, () -> { Variable base = new Variable("base"); code.addLine(UPCAST_COMMENT) .addLine("%s %s = %s;", datatype.getGeneratedBuilder(), base, builder); return base; }); }
java
{ "resource": "" }
q2144
Declarations.freshBuilder
train
public static Optional<Variable> freshBuilder(SourceBuilder code, Datatype datatype) { if (!datatype.getBuilderFactory().isPresent()) { return Optional.empty(); } return Optional.of(code.scope().computeIfAbsent(Declaration.FRESH_BUILDER, () -> { Variable defaults = new Variable("defaults"); code.addLine("%s %s = %s;", datatype.getGeneratedBuilder(), defaults, datatype.getBuilderFactory().get() .newBuilder(datatype.getBuilder(), TypeInference.INFERRED_TYPES)); return defaults; })); }
java
{ "resource": "" }
q2145
Type.javadocMethodLink
train
public JavadocLink javadocMethodLink(String memberName, Type... types) { return new JavadocLink("%s#%s(%s)", getQualifiedName(), memberName, (Excerpt) code -> { String separator = ""; for (Type type : types) { code.add("%s%s", separator, type.getQualifiedName()); separator = ", "; } }); }
java
{ "resource": "" }
q2146
Type.typeParameters
train
public Excerpt typeParameters() { if (getTypeParameters().isEmpty()) { return Excerpts.EMPTY; } else { return Excerpts.add("<%s>", Excerpts.join(", ", getTypeParameters())); } }
java
{ "resource": "" }
q2147
AbstractRule.createViolation
train
protected Violation createViolation(Integer lineNumber, String sourceLine, String message) { Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine(sourceLine); violation.setLineNumber(lineNumber); violation.setMessage(message); return violation; }
java
{ "resource": "" }
q2148
AbstractRule.createViolation
train
protected Violation createViolation(SourceCode sourceCode, ASTNode node, String message) { String sourceLine = sourceCode.line(node.getLineNumber()-1); return createViolation(node.getLineNumber(), sourceLine, message); }
java
{ "resource": "" }
q2149
AbstractRule.createViolationForImport
train
protected Violation createViolationForImport(SourceCode sourceCode, ImportNode importNode, String message) { Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, importNode); Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine((String) importInfo.get("sourceLine")); violation.setLineNumber((Integer) importInfo.get("lineNumber")); violation.setMessage(message); return violation; }
java
{ "resource": "" }
q2150
AbstractRule.createViolationForImport
train
protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) { Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias); Violation violation = new Violation(); violation.setRule(this); violation.setSourceLine((String) importInfo.get("sourceLine")); violation.setLineNumber((Integer) importInfo.get("lineNumber")); violation.setMessage(violationMessage); return violation; }
java
{ "resource": "" }
q2151
AbstractAstVisitorRule.shouldApplyThisRuleTo
train
protected boolean shouldApplyThisRuleTo(ClassNode classNode) { // TODO Consider caching applyTo, doNotApplyTo and associated WildcardPatterns boolean shouldApply = true; String applyTo = getApplyToClassNames(); String doNotApplyTo = getDoNotApplyToClassNames(); if (applyTo != null && applyTo.length() > 0) { WildcardPattern pattern = new WildcardPattern(applyTo, true); shouldApply = pattern.matches(classNode.getNameWithoutPackage()) || pattern.matches(classNode.getName()); } if (shouldApply && doNotApplyTo != null && doNotApplyTo.length() > 0) { WildcardPattern pattern = new WildcardPattern(doNotApplyTo, true); shouldApply = !pattern.matches(classNode.getNameWithoutPackage()) && !pattern.matches(classNode.getName()); } return shouldApply; }
java
{ "resource": "" }
q2152
AntFileSetSourceAnalyzer.analyze
train
public Results analyze(RuleSet ruleSet) { long startTime = System.currentTimeMillis(); DirectoryResults reportResults = new DirectoryResults(); int numThreads = Runtime.getRuntime().availableProcessors() - 1; numThreads = numThreads > 0 ? numThreads : 1; ExecutorService pool = Executors.newFixedThreadPool(numThreads); for (FileSet fileSet : fileSets) { processFileSet(fileSet, ruleSet, pool); } pool.shutdown(); try { boolean completed = pool.awaitTermination(POOL_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!completed) { throw new IllegalStateException("Thread Pool terminated before comp<FileResults>letion"); } } catch (InterruptedException e) { throw new IllegalStateException("Thread Pool interrupted before completion"); } addDirectoryResults(reportResults); LOG.info("Analysis time=" + (System.currentTimeMillis() - startTime) + "ms"); return reportResults; }
java
{ "resource": "" }
q2153
AstUtil.isPredefinedConstant
train
private static boolean isPredefinedConstant(Expression expression) { if (expression instanceof PropertyExpression) { Expression object = ((PropertyExpression) expression).getObjectExpression(); Expression property = ((PropertyExpression) expression).getProperty(); if (object instanceof VariableExpression) { List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName()); if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) { return true; } } } return false; }
java
{ "resource": "" }
q2154
AstUtil.isMapLiteralWithOnlyConstantValues
train
public static boolean isMapLiteralWithOnlyConstantValues(Expression expression) { if (expression instanceof MapExpression) { List<MapEntryExpression> entries = ((MapExpression) expression).getMapEntryExpressions(); for (MapEntryExpression entry : entries) { if (!isConstantOrConstantLiteral(entry.getKeyExpression()) || !isConstantOrConstantLiteral(entry.getValueExpression())) { return false; } } return true; } return false; }
java
{ "resource": "" }
q2155
AstUtil.isListLiteralWithOnlyConstantValues
train
public static boolean isListLiteralWithOnlyConstantValues(Expression expression) { if (expression instanceof ListExpression) { List<Expression> expressions = ((ListExpression) expression).getExpressions(); for (Expression e : expressions) { if (!isConstantOrConstantLiteral(e)) { return false; } } return true; } return false; }
java
{ "resource": "" }
q2156
AstUtil.isConstant
train
public static boolean isConstant(Expression expression, Object expected) { return expression instanceof ConstantExpression && expected.equals(((ConstantExpression) expression).getValue()); }
java
{ "resource": "" }
q2157
AstUtil.getMethodArguments
train
public static List<? extends Expression> getMethodArguments(ASTNode methodCall) { if (methodCall instanceof ConstructorCallExpression) { return extractExpressions(((ConstructorCallExpression) methodCall).getArguments()); } else if (methodCall instanceof MethodCallExpression) { return extractExpressions(((MethodCallExpression) methodCall).getArguments()); } else if (methodCall instanceof StaticMethodCallExpression) { return extractExpressions(((StaticMethodCallExpression) methodCall).getArguments()); } else if (respondsTo(methodCall, "getArguments")) { throw new RuntimeException(); // TODO: remove, should never happen } return new ArrayList<Expression>(); }
java
{ "resource": "" }
q2158
AstUtil.isMethodNamed
train
public static boolean isMethodNamed(MethodCallExpression methodCall, String methodNamePattern, Integer numArguments) { Expression method = methodCall.getMethod(); // !important: performance enhancement boolean IS_NAME_MATCH = false; if (method instanceof ConstantExpression) { if (((ConstantExpression) method).getValue() instanceof String) { IS_NAME_MATCH = ((String)((ConstantExpression) method).getValue()).matches(methodNamePattern); } } if (IS_NAME_MATCH && numArguments != null) { return AstUtil.getMethodArguments(methodCall).size() == numArguments; } return IS_NAME_MATCH; }
java
{ "resource": "" }
q2159
AstUtil.isConstructorCall
train
public static boolean isConstructorCall(Expression expression, List<String> classNames) { return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName()); }
java
{ "resource": "" }
q2160
AstUtil.isConstructorCall
train
public static boolean isConstructorCall(Expression expression, String classNamePattern) { return expression instanceof ConstructorCallExpression && expression.getType().getName().matches(classNamePattern); }
java
{ "resource": "" }
q2161
AstUtil.getAnnotation
train
public static AnnotationNode getAnnotation(AnnotatedNode node, String name) { List<AnnotationNode> annotations = node.getAnnotations(); for (AnnotationNode annot : annotations) { if (annot.getClassNode().getName().equals(name)) { return annot; } } return null; }
java
{ "resource": "" }
q2162
AstUtil.hasAnnotation
train
public static boolean hasAnnotation(AnnotatedNode node, String name) { return AstUtil.getAnnotation(node, name) != null; }
java
{ "resource": "" }
q2163
AstUtil.hasAnyAnnotation
train
public static boolean hasAnyAnnotation(AnnotatedNode node, String... names) { for (String name : names) { if (hasAnnotation(node, name)) { return true; } } return false; }
java
{ "resource": "" }
q2164
AstUtil.getVariableExpressions
train
public static List<Expression> getVariableExpressions(DeclarationExpression declarationExpression) { Expression leftExpression = declarationExpression.getLeftExpression(); // !important: performance enhancement if (leftExpression instanceof ArrayExpression) { List<Expression> expressions = ((ArrayExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof ListExpression) { List<Expression> expressions = ((ListExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof TupleExpression) { List<Expression> expressions = ((TupleExpression) leftExpression).getExpressions(); return expressions.isEmpty() ? Arrays.asList(leftExpression) : expressions; } else if (leftExpression instanceof VariableExpression) { return Arrays.asList(leftExpression); } // todo: write warning return Collections.emptyList(); }
java
{ "resource": "" }
q2165
AstUtil.isFinalVariable
train
public static boolean isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) { if (isFromGeneratedSourceCode(declarationExpression)) { return false; } List<Expression> variableExpressions = getVariableExpressions(declarationExpression); if (!variableExpressions.isEmpty()) { Expression variableExpression = variableExpressions.get(0); int startOfDeclaration = declarationExpression.getColumnNumber(); int startOfVariableName = variableExpression.getColumnNumber(); int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode); String sourceLine = sourceCode.getLines().get(sourceLineNumber-1); String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ? sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : ""; return modifiers.contains("final"); } return false; }
java
{ "resource": "" }
q2166
AstUtil.isTrue
train
public static boolean isTrue(Expression expression) { if (expression == null) { return false; } if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) { if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression && "TRUE".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) { return true; } } return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isTrueExpression()) || "Boolean.TRUE".equals(expression.getText()); }
java
{ "resource": "" }
q2167
AstUtil.isFalse
train
public static boolean isFalse(Expression expression) { if (expression == null) { return false; } if (expression instanceof PropertyExpression && classNodeImplementsType(((PropertyExpression) expression).getObjectExpression().getType(), Boolean.class)) { if (((PropertyExpression) expression).getProperty() instanceof ConstantExpression && "FALSE".equals(((ConstantExpression) ((PropertyExpression) expression).getProperty()).getValue())) { return true; } } return ((expression instanceof ConstantExpression) && ((ConstantExpression) expression).isFalseExpression()) || "Boolean.FALSE".equals(expression.getText()); }
java
{ "resource": "" }
q2168
AstUtil.respondsTo
train
public static boolean respondsTo(Object object, String methodName) { MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object); if (!metaClass.respondsTo(object, methodName).isEmpty()) { return true; } Map properties = DefaultGroovyMethods.getProperties(object); return properties.containsKey(methodName); }
java
{ "resource": "" }
q2169
AstUtil.classNodeImplementsType
train
public static boolean classNodeImplementsType(ClassNode node, Class target) { ClassNode targetNode = ClassHelper.make(target); if (node.implementsInterface(targetNode)) { return true; } if (node.isDerivedFrom(targetNode)) { return true; } if (node.getName().equals(target.getName())) { return true; } if (node.getName().equals(target.getSimpleName())) { return true; } if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getName())) { return true; } if (node.getSuperClass() != null && node.getSuperClass().getName().equals(target.getSimpleName())) { return true; } if (node.getInterfaces() != null) { for (ClassNode declaredInterface : node.getInterfaces()) { if (classNodeImplementsType(declaredInterface, target)) { return true; } } } return false; }
java
{ "resource": "" }
q2170
AstUtil.isClosureDeclaration
train
public static boolean isClosureDeclaration(ASTNode expression) { if (expression instanceof DeclarationExpression) { if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) { return true; } } if (expression instanceof FieldNode) { ClassNode type = ((FieldNode) expression).getType(); if (AstUtil.classNodeImplementsType(type, Closure.class)) { return true; } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) { return true; } } return false; }
java
{ "resource": "" }
q2171
AstUtil.getParameterNames
train
public static List<String> getParameterNames(MethodNode node) { ArrayList<String> result = new ArrayList<String>(); if (node.getParameters() != null) { for (Parameter parameter : node.getParameters()) { result.add(parameter.getName()); } } return result; }
java
{ "resource": "" }
q2172
AstUtil.getArgumentNames
train
public static List<String> getArgumentNames(MethodCallExpression methodCall) { ArrayList<String> result = new ArrayList<String>(); Expression arguments = methodCall.getArguments(); List<Expression> argExpressions = null; if (arguments instanceof ArrayExpression) { argExpressions = ((ArrayExpression) arguments).getExpressions(); } else if (arguments instanceof ListExpression) { argExpressions = ((ListExpression) arguments).getExpressions(); } else if (arguments instanceof TupleExpression) { argExpressions = ((TupleExpression) arguments).getExpressions(); } else { LOG.warn("getArgumentNames arguments is not an expected type"); } if (argExpressions != null) { for (Expression exp : argExpressions) { if (exp instanceof VariableExpression) { result.add(((VariableExpression) exp).getName()); } } } return result; }
java
{ "resource": "" }
q2173
AstUtil.isSafe
train
public static boolean isSafe(Expression expression) { if (expression instanceof MethodCallExpression) { return ((MethodCallExpression) expression).isSafe(); } if (expression instanceof PropertyExpression) { return ((PropertyExpression) expression).isSafe(); } return false; }
java
{ "resource": "" }
q2174
AstUtil.isSpreadSafe
train
public static boolean isSpreadSafe(Expression expression) { if (expression instanceof MethodCallExpression) { return ((MethodCallExpression) expression).isSpreadSafe(); } if (expression instanceof PropertyExpression) { return ((PropertyExpression) expression).isSpreadSafe(); } return false; }
java
{ "resource": "" }
q2175
AstUtil.isMethodNode
train
public static boolean isMethodNode(ASTNode node, String methodNamePattern, Integer numArguments, Class returnType) { if (!(node instanceof MethodNode)) { return false; } if (!(((MethodNode) node).getName().matches(methodNamePattern))) { return false; } if (numArguments != null && ((MethodNode)node).getParameters() != null && ((MethodNode)node).getParameters().length != numArguments) { return false; } if (returnType != null && !AstUtil.classNodeImplementsType(((MethodNode) node).getReturnType(), returnType)) { return false; } return true; }
java
{ "resource": "" }
q2176
AstUtil.isVariable
train
public static boolean isVariable(ASTNode expression, String pattern) { return (expression instanceof VariableExpression && ((VariableExpression) expression).getName().matches(pattern)); }
java
{ "resource": "" }
q2177
AstUtil.getClassForClassNode
train
private static Class getClassForClassNode(ClassNode type) { // todo hamlet - move to a different "InferenceUtil" object Class primitiveType = getPrimitiveType(type); if (primitiveType != null) { return primitiveType; } else if (classNodeImplementsType(type, String.class)) { return String.class; } else if (classNodeImplementsType(type, ReentrantLock.class)) { return ReentrantLock.class; } else if (type.getName() != null && type.getName().endsWith("[]")) { return Object[].class; // better type inference could be done, but oh well } return null; }
java
{ "resource": "" }
q2178
AstUtil.findFirstNonAnnotationLine
train
public static int findFirstNonAnnotationLine(ASTNode node, SourceCode sourceCode) { if (node instanceof AnnotatedNode && !((AnnotatedNode) node).getAnnotations().isEmpty()) { // HACK: Groovy line numbers are broken when annotations have a parameter :( // so we must look at the lineNumber, not the lastLineNumber AnnotationNode lastAnnotation = null; for (AnnotationNode annotation : ((AnnotatedNode) node).getAnnotations()) { if (lastAnnotation == null) lastAnnotation = annotation; else if (lastAnnotation.getLineNumber() < annotation.getLineNumber()) lastAnnotation = annotation; } String rawLine = getRawLine(sourceCode, lastAnnotation.getLastLineNumber()-1); if(rawLine == null) { return node.getLineNumber(); } // is the annotation the last thing on the line? if (rawLine.length() > lastAnnotation.getLastColumnNumber()) { // no it is not return lastAnnotation.getLastLineNumber(); } // yes it is the last thing, return the next thing return lastAnnotation.getLastLineNumber() + 1; } return node.getLineNumber(); }
java
{ "resource": "" }
q2179
AbstractAstVisitor.isFirstVisit
train
protected boolean isFirstVisit(Object expression) { if (visited.contains(expression)) { return false; } visited.add(expression); return true; }
java
{ "resource": "" }
q2180
AbstractAstVisitor.sourceLineTrimmed
train
protected String sourceLineTrimmed(ASTNode node) { return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1); }
java
{ "resource": "" }
q2181
AbstractAstVisitor.sourceLine
train
protected String sourceLine(ASTNode node) { return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1); }
java
{ "resource": "" }
q2182
SlackHttpClient.buildJsonResponse
train
@Deprecated public static <T> T buildJsonResponse(Response response, Class<T> clazz) throws IOException, SlackApiException { if (response.code() == 200) { String body = response.body().string(); DETAILED_LOGGER.accept(new HttpResponseListener.State(SlackConfig.DEFAULT, response, body)); return GsonFactory.createSnakeCase().fromJson(body, clazz); } else { String body = response.body().string(); throw new SlackApiException(response, body); } }
java
{ "resource": "" }
q2183
Slack.send
train
public WebhookResponse send(String url, Payload payload) throws IOException { SlackHttpClient httpClient = getHttpClient(); Response httpResponse = httpClient.postJsonPostRequest(url, payload); String body = httpResponse.body().string(); httpClient.runHttpResponseListeners(httpResponse, body); return WebhookResponse.builder() .code(httpResponse.code()) .message(httpResponse.message()) .body(body) .build(); }
java
{ "resource": "" }
q2184
RTMClient.updateSession
train
private void updateSession(Session newSession) { if (this.currentSession == null) { this.currentSession = newSession; } else { synchronized (this.currentSession) { this.currentSession = newSession; } } }
java
{ "resource": "" }
q2185
RTMEventHandler.getEventClass
train
public Class<E> getEventClass() { if (cachedClazz != null) { return cachedClazz; } Class<?> clazz = this.getClass(); while (clazz != Object.class) { try { Type mySuperclass = clazz.getGenericSuperclass(); Type tType = ((ParameterizedType) mySuperclass).getActualTypeArguments()[0]; cachedClazz = (Class<E>) Class.forName(tType.getTypeName()); return cachedClazz; } catch (Exception e) { } clazz = clazz.getSuperclass(); } throw new IllegalStateException("Failed to load event class - " + this.getClass().getCanonicalName()); }
java
{ "resource": "" }
q2186
AbstractSpringFieldTagProcessor.computeId
train
protected final String computeId( final ITemplateContext context, final IProcessableElementTag tag, final String name, final boolean sequence) { String id = tag.getAttributeValue(this.idAttributeDefinition.getAttributeName()); if (!org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(id)) { return (StringUtils.hasText(id) ? id : null); } id = FieldUtils.idFromName(name); if (sequence) { final Integer count = context.getIdentifierSequences().getAndIncrementIDSeq(id); return id + count.toString(); } return id; }
java
{ "resource": "" }
q2187
Themes.code
train
public String code(final String code) { if (this.theme == null) { throw new TemplateProcessingException("Theme cannot be resolved because RequestContext was not found. " + "Are you using a Context object without a RequestContext variable?"); } return this.theme.getMessageSource().getMessage(code, null, "", this.locale); }
java
{ "resource": "" }
q2188
ManagedServerBootCmdFactory.resolveDirectoryGrouping
train
private static DirectoryGrouping resolveDirectoryGrouping(final ModelNode model, final ExpressionResolver expressionResolver) { try { return DirectoryGrouping.forName(HostResourceDefinition.DIRECTORY_GROUPING.resolveModelAttribute(expressionResolver, model).asString()); } catch (OperationFailedException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q2189
ManagedServerBootCmdFactory.addPathProperty
train
private String addPathProperty(final List<String> command, final String typeName, final String propertyName, final Map<String, String> properties, final DirectoryGrouping directoryGrouping, final File typeDir, File serverDir) { final String result; final String value = properties.get(propertyName); if (value == null) { switch (directoryGrouping) { case BY_TYPE: result = getAbsolutePath(typeDir, "servers", serverName); break; case BY_SERVER: default: result = getAbsolutePath(serverDir, typeName); break; } properties.put(propertyName, result); } else { final File dir = new File(value); switch (directoryGrouping) { case BY_TYPE: result = getAbsolutePath(dir, "servers", serverName); break; case BY_SERVER: default: result = getAbsolutePath(dir, serverName); break; } } command.add(String.format("-D%s=%s", propertyName, result)); return result; }
java
{ "resource": "" }
q2190
LoggingProfileDeploymentProcessor.findLoggingProfile
train
private String findLoggingProfile(final ResourceRoot resourceRoot) { final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST); if (manifest != null) { final String loggingProfile = manifest.getMainAttributes().getValue(LOGGING_PROFILE); if (loggingProfile != null) { LoggingLogger.ROOT_LOGGER.debugf("Logging profile '%s' found in '%s'.", loggingProfile, resourceRoot); return loggingProfile; } } return null; }
java
{ "resource": "" }
q2191
ArgumentValueState.getBytesToken
train
public static int getBytesToken(ParsingContext ctx) { String input = ctx.getInput().substring(ctx.getLocation()); int tokenOffset = 0; int i = 0; char[] inputChars = input.toCharArray(); for (; i < input.length(); i += 1) { char c = inputChars[i]; if (c == ' ') { continue; } if (c != BYTES_TOKEN_CHARS[tokenOffset]) { return -1; } else { tokenOffset += 1; if (tokenOffset == BYTES_TOKEN_CHARS.length) { // Found the token. return i; } } } return -1; }
java
{ "resource": "" }
q2192
RbacSanityCheckOperation.addOperation
train
public static void addOperation(final OperationContext context) { RbacSanityCheckOperation added = context.getAttachment(KEY); if (added == null) { // TODO support managed domain if (!context.isNormalServer()) return; context.addStep(createOperation(), INSTANCE, Stage.MODEL); context.attach(KEY, INSTANCE); } }
java
{ "resource": "" }
q2193
Operations.getFailureDescription
train
public static ModelNode getFailureDescription(final ModelNode result) { if (isSuccessfulOutcome(result)) { throw ControllerClientLogger.ROOT_LOGGER.noFailureDescription(); } if (result.hasDefined(FAILURE_DESCRIPTION)) { return result.get(FAILURE_DESCRIPTION); } return new ModelNode(); }
java
{ "resource": "" }
q2194
Operations.getOperationAddress
train
public static ModelNode getOperationAddress(final ModelNode op) { return op.hasDefined(OP_ADDR) ? op.get(OP_ADDR) : new ModelNode(); }
java
{ "resource": "" }
q2195
Operations.getOperationName
train
public static String getOperationName(final ModelNode op) { if (op.hasDefined(OP)) { return op.get(OP).asString(); } throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound(); }
java
{ "resource": "" }
q2196
Operations.createReadResourceOperation
train
public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) { final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address); op.get(RECURSIVE).set(recursive); return op; }
java
{ "resource": "" }
q2197
DefaultOperationRequestBuilder.buildRequest
train
public ModelNode buildRequest() throws OperationFormatException { ModelNode address = request.get(Util.ADDRESS); if(prefix.isEmpty()) { address.setEmptyList(); } else { Iterator<Node> iterator = prefix.iterator(); while (iterator.hasNext()) { OperationRequestAddress.Node node = iterator.next(); if (node.getName() != null) { address.add(node.getType(), node.getName()); } else if (iterator.hasNext()) { throw new OperationFormatException( "The node name is not specified for type '" + node.getType() + "'"); } } } if(!request.hasDefined(Util.OPERATION)) { throw new OperationFormatException("The operation name is missing or the format of the operation request is wrong."); } return request; }
java
{ "resource": "" }
q2198
ManagementXml_5.parseUsersAuthentication
train
private void parseUsersAuthentication(final XMLExtendedStreamReader reader, final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException { final ModelNode usersAddress = realmAddress.clone().add(AUTHENTICATION, USERS); list.add(Util.getEmptyOperation(ADD, usersAddress)); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { requireNamespace(reader, namespace); final Element element = Element.forName(reader.getLocalName()); switch (element) { case USER: { parseUser(reader, usersAddress, list); break; } default: { throw unexpectedElement(reader); } } } }
java
{ "resource": "" }
q2199
JmxAction.getActionEffects
train
public Set<Action.ActionEffect> getActionEffects() { switch(getImpact()) { case CLASSLOADING: case WRITE: return WRITES; case READ_ONLY: return READS; default: throw new IllegalStateException(); } }
java
{ "resource": "" }