instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class StudentDetails {
protected int id;
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String passportNumber;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
|
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the passportNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPassportNumber() {
return passportNumber;
}
/**
* Sets the value of the passportNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPassportNumber(String value) {
this.passportNumber = value;
}
}
|
repos\spring-boot-examples-master\spring-boot-tutorial-soap-web-services\src\main\java\com\in28minutes\students\StudentDetails.java
| 2
|
请完成以下Java代码
|
public String getSqlLinkColumnName()
{
return _sqlLinkColumnName;
}
public String getSqlParentLinkColumnName()
{
return _sqlParentLinkColumnName;
}
public Builder setSqlWhereClause(final String sqlWhereClause)
{
assertNotBuilt();
Check.assumeNotNull(sqlWhereClause, "Parameter sqlWhereClause is not null");
_sqlWhereClause = sqlWhereClause;
return this;
}
public Builder addField(@NonNull final DocumentFieldDataBindingDescriptor field)
{
assertNotBuilt();
final SqlDocumentFieldDataBindingDescriptor sqlField = SqlDocumentFieldDataBindingDescriptor.cast(field);
_fieldsByFieldName.put(sqlField.getFieldName(), sqlField);
return this;
}
private Map<String, SqlDocumentFieldDataBindingDescriptor> getFieldsByFieldName()
{
return _fieldsByFieldName;
}
public SqlDocumentFieldDataBindingDescriptor getField(final String fieldName)
{
final SqlDocumentFieldDataBindingDescriptor field = getFieldsByFieldName().get(fieldName);
if (field == null)
{
throw new AdempiereException("Field " + fieldName + " not found in " + this);
}
|
return field;
}
private List<SqlDocumentFieldDataBindingDescriptor> getKeyFields()
{
return getFieldsByFieldName()
.values()
.stream()
.filter(SqlDocumentFieldDataBindingDescriptor::isKeyColumn)
.collect(ImmutableList.toImmutableList());
}
private Optional<String> getSqlSelectVersionById()
{
if (getFieldsByFieldName().get(FIELDNAME_Version) == null)
{
return Optional.empty();
}
final List<SqlDocumentFieldDataBindingDescriptor> keyColumns = getKeyFields();
if (keyColumns.size() != 1)
{
return Optional.empty();
}
final String keyColumnName = keyColumns.get(0).getColumnName();
final String sql = "SELECT " + FIELDNAME_Version + " FROM " + getTableName() + " WHERE " + keyColumnName + "=?";
return Optional.of(sql);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentEntityDataBindingDescriptor.java
| 1
|
请完成以下Java代码
|
public LookupValue lookupUser(@Nullable final UserId userId)
{
if (userId == null)
{
return null;
}
return userLookup.findById(userId.getRepoId());
}
public LookupValue lookupProduct(@Nullable final ProductId productId)
{
if (productId == null)
{
return null;
}
return productLookup.findById(productId.getRepoId());
}
public LookupValue lookupPriceType(@NonNull final PriceSpecificationType priceType)
{
return priceTypeLookup.findById(priceType.getCode());
}
public LookupValue lookupPricingSystem(@Nullable final PricingSystemId pricingSystemId)
{
if (pricingSystemId == null)
{
return null;
}
return pricingSystemLookup.findById(pricingSystemId.getRepoId());
}
public LookupValue lookupPaymentTerm(@Nullable final PaymentTermId paymentTermId)
{
if (paymentTermId == null)
{
return null;
}
return paymentTermLookup.findById(paymentTermId.getRepoId());
}
public LookupValue lookupCurrency(@Nullable final CurrencyId currencyId)
{
if (currencyId == null)
{
return null;
}
return currencyIdLookup.findById(currencyId.getRepoId());
}
public LookupValuesPage getFieldTypeahead(@NonNull final String fieldName, final String query)
{
return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), query);
|
}
public LookupValuesList getFieldDropdown(@NonNull final String fieldName)
{
return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), 20).getValues();
}
private LookupDataSource getLookupDataSource(@NonNull final String fieldName)
{
if (PricingConditionsRow.FIELDNAME_PaymentTerm.equals(fieldName))
{
return paymentTermLookup;
}
else if (PricingConditionsRow.FIELDNAME_BasePriceType.equals(fieldName))
{
return priceTypeLookup;
}
else if (PricingConditionsRow.FIELDNAME_BasePricingSystem.equals(fieldName))
{
return pricingSystemLookup;
}
else if (PricingConditionsRow.FIELDNAME_C_Currency_ID.equals(fieldName))
{
return currencyIdLookup;
}
else
{
throw new AdempiereException("Field " + fieldName + " does not exist or it's not a lookup field");
}
}
public String getTemporaryPriceConditionsColor()
{
return temporaryPriceConditionsColorCache.getOrLoad(0, this::retrieveTemporaryPriceConditionsColor);
}
private String retrieveTemporaryPriceConditionsColor()
{
final ColorId temporaryPriceConditionsColorId = Services.get(IOrderLinePricingConditions.class).getTemporaryPriceConditionsColorId();
return toHexString(Services.get(IColorRepository.class).getColorById(temporaryPriceConditionsColorId));
}
private static String toHexString(@Nullable final MFColor color)
{
if (color == null)
{
return null;
}
final Color awtColor = color.toFlatColor().getFlatColor();
return ColorValue.toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowLookups.java
| 1
|
请完成以下Java代码
|
public static void removeDuplicatesFromOutputDirectory(File outputDirectory, File originDirectory) {
if (originDirectory.isDirectory()) {
String[] files = originDirectory.list();
Assert.state(files != null, "'files' must not be null");
for (String name : files) {
File targetFile = new File(outputDirectory, name);
if (targetFile.exists() && targetFile.canWrite()) {
if (!targetFile.isDirectory()) {
targetFile.delete();
}
else {
FileUtils.removeDuplicatesFromOutputDirectory(targetFile, new File(originDirectory, name));
}
}
}
}
}
/**
* Returns {@code true} if the given jar file has been signed.
* @param file the file to check
* @return if the file has been signed
* @throws IOException on IO error
*/
public static boolean isSignedJarFile(@Nullable File file) throws IOException {
|
if (file == null) {
return false;
}
try (JarFile jarFile = new JarFile(file)) {
if (hasDigestEntry(jarFile.getManifest())) {
return true;
}
}
return false;
}
private static boolean hasDigestEntry(@Nullable Manifest manifest) {
return (manifest != null) && manifest.getEntries().values().stream().anyMatch(FileUtils::hasDigestName);
}
private static boolean hasDigestName(Attributes attributes) {
return attributes.keySet().stream().anyMatch(FileUtils::isDigestName);
}
private static boolean isDigestName(Object name) {
return String.valueOf(name).toUpperCase(Locale.ROOT).endsWith("-DIGEST");
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\FileUtils.java
| 1
|
请完成以下Java代码
|
public int getC_Order_MFGWarehouse_Report_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Order_MFGWarehouse_Report_ID);
}
@Override
public de.metas.printing.model.I_C_Print_Job_Instructions getC_Print_Job_Instructions()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class);
}
@Override
public void setC_Print_Job_Instructions(de.metas.printing.model.I_C_Print_Job_Instructions C_Print_Job_Instructions)
{
set_ValueFromPO(COLUMNNAME_C_Print_Job_Instructions_ID, de.metas.printing.model.I_C_Print_Job_Instructions.class, C_Print_Job_Instructions);
}
@Override
public void setC_Print_Job_Instructions_ID (int C_Print_Job_Instructions_ID)
{
if (C_Print_Job_Instructions_ID < 1)
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, null);
else
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, Integer.valueOf(C_Print_Job_Instructions_ID));
}
@Override
public int getC_Print_Job_Instructions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID);
}
@Override
public de.metas.printing.model.I_C_Print_Package getC_Print_Package()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class);
}
@Override
public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package)
{
set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_Value (COLUMNNAME_C_Print_Package_ID, null);
else
set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
|
else
set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public org.compiere.model.I_S_Resource getS_Resource()
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions_v.java
| 1
|
请完成以下Java代码
|
public class HandlerDiscoverer extends AbstractGatewayDiscoverer {
@Override
public void discover() {
doDiscover(HandlerSupplier.class, HandlerFunction.class);
doDiscover(HandlerSupplier.class, HandlerDiscoverer.Result.class);
}
public static class Result {
private final HandlerFunction<ServerResponse> handlerFunction;
private final List<HandlerFilterFunction<ServerResponse, ServerResponse>> lowerPrecedenceFilters;
private final List<HandlerFilterFunction<ServerResponse, ServerResponse>> higherPrecedenceFilters;
public Result(HandlerFunction<ServerResponse> handlerFunction,
List<HandlerFilterFunction<ServerResponse, ServerResponse>> lowerPrecedenceFilters,
List<HandlerFilterFunction<ServerResponse, ServerResponse>> higherPrecedenceFilters) {
this.handlerFunction = handlerFunction;
|
this.lowerPrecedenceFilters = Objects.requireNonNullElse(lowerPrecedenceFilters, Collections.emptyList());
this.higherPrecedenceFilters = Objects.requireNonNullElse(higherPrecedenceFilters, Collections.emptyList());
}
public HandlerFunction<ServerResponse> getHandlerFunction() {
return handlerFunction;
}
public List<HandlerFilterFunction<ServerResponse, ServerResponse>> getLowerPrecedenceFilters() {
return lowerPrecedenceFilters;
}
public List<HandlerFilterFunction<ServerResponse, ServerResponse>> getHigherPrecedenceFilters() {
return higherPrecedenceFilters;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\HandlerDiscoverer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ImmutableList<IssueEntity> getUpStreamForId(@NonNull final IssueId issueId)
{
final Optional<IssueEntity> issue = getIssueForId(issueId);
if (!issue.isPresent())
{
return ImmutableList.of();
}
return this.root.getNode(issue.get())
.map(Node::getUpStream)
.orElse(new ArrayList<>())
.stream()
.map(Node::getValue)
.collect(ImmutableList.toImmutableList());
|
}
private Optional<IssueEntity> getIssueForId(@NonNull final IssueId issueId)
{
return listIssues()
.stream()
.filter(issueEntity -> issueId.equalsNullSafe(issueEntity.getIssueId()))
.findFirst();
}
private IssueHierarchy(final Node<IssueEntity> root)
{
this.root = root;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\hierarchy\IssueHierarchy.java
| 2
|
请完成以下Java代码
|
public static final Builder builder()
{
return new Builder();
}
private final String tableName;
private final boolean async;
private CounterDocHandlerInterceptor(final Builder builder)
{
super();
this.tableName = builder.getTableName();
this.async = builder.isAsync();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("tableName", tableName)
.add("async", async)
.toString();
}
@Override
protected void onInit(final IModelValidationEngine engine, final I_AD_Client client)
{
engine.addDocValidate(tableName, this);
}
@Override
public void onDocValidate(final Object model, final DocTimingType timing) throws Exception
{
if (timing != DocTimingType.AFTER_COMPLETE)
{
return; // nothing to do
}
final ICounterDocBL counterDocumentBL = Services.get(ICounterDocBL.class);
if (!counterDocumentBL.isCreateCounterDocument(model))
{
return; // nothing to do
}
counterDocumentBL.createCounterDocument(model, async);
}
/** {@link CounterDocHandlerInterceptor} instance builder */
public static final class Builder
{
private String tableName;
private boolean async = false;
|
private Builder()
{
super();
}
public CounterDocHandlerInterceptor build()
{
return new CounterDocHandlerInterceptor(this);
}
public Builder setTableName(String tableName)
{
this.tableName = tableName;
return this;
}
private final String getTableName()
{
Check.assumeNotEmpty(tableName, "tableName not empty");
return tableName;
}
public Builder setAsync(boolean async)
{
this.async = async;
return this;
}
private boolean isAsync()
{
return async;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\model\interceptor\CounterDocHandlerInterceptor.java
| 1
|
请完成以下Java代码
|
public List<ProcessInstanceQueryImpl> getQueries() {
return queries;
}
public void addOrQuery(ProcessInstanceQueryImpl orQuery) {
orQuery.isOrQueryActive = true;
this.queries.add(orQuery);
}
public void setOrQueryActive() {
isOrQueryActive = true;
}
public boolean isOrQueryActive() {
return isOrQueryActive;
}
public String[] getActivityIds() {
return activityIds;
}
public String getBusinessKey() {
return businessKey;
}
public String getBusinessKeyLike() {
return businessKeyLike;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String[] getProcessDefinitionKeyNotIn() {
return processDefinitionKeyNotIn;
}
public String getDeploymentId() {
return deploymentId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public boolean isWithIncident() {
return withIncident;
}
public String getIncidentId() {
return incidentId;
}
public String getIncidentType() {
|
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getIncidentMessageLike() {
return incidentMessageLike;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isRootProcessInstances() {
return isRootProcessInstances;
}
public boolean isProcessDefinitionWithoutTenantId() {
return isProcessDefinitionWithoutTenantId;
}
public boolean isLeafProcessInstances() {
return isLeafProcessInstances;
}
public String[] getTenantIds() {
return tenantIds;
}
@Override
public ProcessInstanceQuery or() {
if (this != queries.get(0)) {
throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query");
}
ProcessInstanceQueryImpl orQuery = new ProcessInstanceQueryImpl();
orQuery.isOrQueryActive = true;
orQuery.queries = queries;
queries.add(orQuery);
return orQuery;
}
@Override
public ProcessInstanceQuery endOr() {
if (!queries.isEmpty() && this != queries.get(queries.size()-1)) {
throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()");
}
return queries.get(0);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final PInstanceId pinstanceId = getPinstanceId();
final Iterator<I_PP_Order_Candidate> orderCandidates = ppOrderCandidateService.retrieveOCForSelection(pinstanceId);
while (orderCandidates.hasNext())
{
ppOrderCandidateService.reopenCandidate(orderCandidates.next());
}
return MSG_OK;
}
@Override
@RunOutOfTrx
protected void prepare()
{
if (createSelection() <= 0)
{
throw new AdempiereException(MSG_SELECTED_CLOSED_CANDIDATE);
}
}
private int createSelection()
{
final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder();
final PInstanceId adPInstanceId = getPinstanceId();
Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null");
DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
return queryBuilder
.create()
.createSelection(adPInstanceId);
}
|
@NonNull
private IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder()
{
final IQueryFilter<I_PP_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
return queryBL
.createQueryBuilder(I_PP_Order_Candidate.class, getCtx(), ITrx.TRXNAME_None)
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_Processed, true)
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false)
.filter(userSelectionFilter)
.addOnlyActiveRecordsFilter();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_ReOpenSelection.java
| 1
|
请完成以下Java代码
|
public class DefaultHttpFirewall implements HttpFirewall {
private boolean allowUrlEncodedSlash;
@Override
public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
FirewalledRequest firewalledRequest = new RequestWrapper(request);
if (!isNormalized(firewalledRequest.getServletPath()) || !isNormalized(firewalledRequest.getPathInfo())) {
throw new RequestRejectedException(
"Un-normalized paths are not supported: " + firewalledRequest.getServletPath()
+ ((firewalledRequest.getPathInfo() != null) ? firewalledRequest.getPathInfo() : ""));
}
String requestURI = firewalledRequest.getRequestURI();
if (containsInvalidUrlEncodedSlash(requestURI)) {
throw new RequestRejectedException("The requestURI cannot contain encoded slash. Got " + requestURI);
}
return firewalledRequest;
}
@Override
public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
return new FirewalledResponse(response);
}
/**
* <p>
* Sets if the application should allow a URL encoded slash character.
* </p>
* <p>
* If true (default is false), a URL encoded slash will be allowed in the URL.
* Allowing encoded slashes can cause security vulnerabilities in some situations
* depending on how the container constructs the HttpServletRequest.
* </p>
* @param allowUrlEncodedSlash the new value (default false)
*/
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
this.allowUrlEncodedSlash = allowUrlEncodedSlash;
}
private boolean containsInvalidUrlEncodedSlash(String uri) {
|
if (this.allowUrlEncodedSlash || uri == null) {
return false;
}
return uri.contains("%2f") || uri.contains("%2F");
}
/**
* Checks whether a path is normalized (doesn't contain path traversal sequences like
* "./", "/../" or "/.")
* @param path the path to test
* @return true if the path doesn't contain any path-traversal character sequences.
*/
private boolean isNormalized(String path) {
if (path == null) {
return true;
}
for (int i = path.length(); i > 0;) {
int slashIndex = path.lastIndexOf('/', i - 1);
int gap = i - slashIndex;
if (gap == 2 && path.charAt(slashIndex + 1) == '.') {
// ".", "/./" or "/."
return false;
}
if (gap == 3 && path.charAt(slashIndex + 1) == '.' && path.charAt(slashIndex + 2) == '.') {
return false;
}
i = slashIndex;
}
return true;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\DefaultHttpFirewall.java
| 1
|
请完成以下Java代码
|
public ScriptEngineRequest.Builder createScriptRequest(VariableContainer variableContainer) {
validateParameters();
String language = Objects.toString(this.language.getValue(variableContainer), null);
if (language == null) {
throw new FlowableIllegalStateException("'language' evaluated to null for listener of type 'script'");
}
ScriptEngineRequest.Builder builder = ScriptEngineRequest.builder();
return builder.language(language).script(getScript()).scopeContainer(variableContainer);
}
protected Object evaluateScriptRequest(ScriptEngineRequest.Builder requestBuilder) {
ScriptEngineRequest request = requestBuilder.build();
Object result = evaluateScript(getScriptingEngines(), request);
if (resultVariable != null) {
VariableContainer variableContainer = request.getScopeContainer();
String resultVariable = Objects.toString(this.resultVariable.getValue(variableContainer), null);
if (variableContainer != null && resultVariable != null) {
variableContainer.setVariable(resultVariable, result);
}
}
return result;
}
protected Object evaluateScript(ScriptingEngines scriptingEngines, ScriptEngineRequest request) {
return scriptingEngines.evaluate(request).getResult();
}
protected void validateParameters() {
if (script == null) {
throw new FlowableIllegalStateException("The field 'script' should be set on " + getClass().getSimpleName());
}
if (language == null) {
throw new FlowableIllegalStateException("The field 'language' should be set on " + getClass().getSimpleName());
}
}
protected abstract ScriptingEngines getScriptingEngines();
public void setScript(String script) {
this.script = script;
}
|
/**
* Sets the script as Expression for backwards compatibility.
* Requires to for 'field' injection of scripts.
* Expression is not evaluated
*/
public void setScript(Expression script) {
this.script = script.getExpressionText();
}
public String getScript() {
return script;
}
public void setLanguage(Expression language) {
this.language = language;
}
public void setResultVariable(Expression resultVariable) {
this.resultVariable = resultVariable;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\AbstractScriptEvaluator.java
| 1
|
请完成以下Java代码
|
public class HUSubProducerBPartnerAttributeHandler
implements IAttributeValueGeneratorAdapter, IAttributeValueCalloutAdapter, IAttributeValuesProviderFactory
{
@Override
public String getAttributeValueType()
{
return HUSubProducerBPartnerAttributeValuesProvider.ATTRIBUTEVALUETYPE;
}
@Override
public IAttributeValuesProvider createAttributeValuesProvider(final @NotNull Attribute attribute)
{
return new HUSubProducerBPartnerAttributeValuesProvider(attribute.getAttributeCode());
}
/**
* Calls {@link ISubProducerAttributeBL#updateAttributesOnSubProducerChanged(Properties, IAttributeSet, boolean)} if at least one of valueOld and valueNew can be converted to not-zero BigDecimals.
*
* @param valueOld old attribute value. converted to BigDecimal using {@link ConversionHelper#toBigDecimal(Object)}
* @param valueNew analog to valueOld
*/
@Override
public void onValueChanged(final IAttributeValueContext attributeValueContext,
final IAttributeSet attributeSet,
final org.compiere.model.I_M_Attribute attribute,
final Object valueOld,
final Object valueNew)
{
final BigDecimal valueOldBD = ConversionHelper.toBigDecimal(valueOld);
final BigDecimal valueNewBD = ConversionHelper.toBigDecimal(valueNew);
if (valueNewBD.signum() == 0 && valueOldBD.signum() == 0)
{
// nothing to change in this case
return;
}
// task 08782: goal of this parameter: we don't want to reset a pre-existing value unless the procuser is actually changed.
final boolean subProducerInitialized = valueNewBD.signum() != 0 && valueOldBD.signum() == 0;
final Properties ctx = InterfaceWrapperHelper.getCtx(attribute);
Services.get(ISubProducerAttributeBL.class).updateAttributesOnSubProducerChanged(ctx, attributeSet, subProducerInitialized);
|
}
@Override
public Object generateSeedValue(final IAttributeSet attributeSet, final org.compiere.model.I_M_Attribute attribute, final Object valueInitialDefault)
{
// we don't support a value different from null
Check.assumeNull(valueInitialDefault, "valueInitialDefault null");
return HUSubProducerBPartnerAttributeValuesProvider.staticNullValue();
}
@Override
public boolean isReadonlyUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final org.compiere.model.I_M_Attribute attribute)
{
final I_M_HU hu = Services.get(IHUAttributesBL.class).getM_HU_OrNull(attributeSet);
if (hu == null)
{
// If there is no HU (e.g. ASI), consider it editable
return false;
}
final String huStatus = hu.getHUStatus();
if (!X_M_HU.HUSTATUS_Planning.equals(huStatus))
{
// Allow editing only Planning HUs
return true;
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUSubProducerBPartnerAttributeHandler.java
| 1
|
请完成以下Java代码
|
public final class FactLineMatchKey
{
private final String string;
private FactLineMatchKey(@NonNull final String string)
{
this.string = StringUtils.trimBlankToNull(string);
if (this.string == null)
{
throw new AdempiereException("invalid blank/null matching key");
}
}
@Nullable
public static FactLineMatchKey ofNullableString(final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
return stringNorm != null ? new FactLineMatchKey(stringNorm) : null;
}
public static FactLineMatchKey ofString(final String string)
{
return new FactLineMatchKey(string);
}
|
public static FactLineMatchKey ofFactLine(@NonNull final FactLine factLine)
{
return ofString(
Util.ArrayKey.builder()
// no need to include AD_Table_ID/Record_ID because we always match on document level
.append(Math.max(factLine.getLine_ID(), 0))
.append(factLine.getAccountConceptualName())
.append(CostElementId.toRepoId(factLine.getCostElementId()))
.append(TaxId.toRepoId(factLine.getTaxId()))
.append(Math.max(factLine.getM_Locator_ID(), 0))
.build()
.toString()
);
}
@Deprecated
@Override
public String toString() {return getAsString();}
public String getAsString()
{
return string;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactLineMatchKey.java
| 1
|
请完成以下Java代码
|
public class X_C_CostClassification_Trl extends org.compiere.model.PO implements I_C_CostClassification_Trl, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 309024709L;
/** Standard Constructor */
public X_C_CostClassification_Trl (final Properties ctx, final int C_CostClassification_Trl_ID, @Nullable final String trxName)
{
super (ctx, C_CostClassification_Trl_ID, trxName);
}
/** Load Constructor */
public X_C_CostClassification_Trl (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AD_Language AD_Reference_ID=106
* Reference name: AD_Language
*/
public static final int AD_LANGUAGE_AD_Reference_ID=106;
@Override
public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setC_CostClassification_ID (final int C_CostClassification_ID)
{
if (C_CostClassification_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CostClassification_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CostClassification_ID, C_CostClassification_ID);
}
@Override
public int getC_CostClassification_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
|
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CostClassification_Trl.java
| 1
|
请完成以下Java代码
|
private WarehouseId getWarehouseId(final IRangeAwareParams params, final String warehouseParameterName)
{
final WarehouseId warehouseId = WarehouseId.ofRepoIdOrNull(params.getParameterAsInt(warehouseParameterName, -1));
if (warehouseId == null)
{
throw new FillMandatoryException(warehouseParameterName);
}
return warehouseId;
}
@Override
@RunOutOfTrx
protected String doIt()
{
final LocatorId locatorToId = warehouseBL.getOrCreateDefaultLocatorId(warehouseToId);
final OrgId orgId = warehouseBL.getWarehouseOrgId(warehouseToId);
final BPartnerLocationId orgBPLocationId = bpartnerOrgBL.retrieveOrgBPLocationId(orgId);
HUs2DDOrderProducer.newProducer(ddOrderMoveScheduleService)
.setLocatorToId(locatorToId)
.setBpartnerLocationId(orgBPLocationId)
.setHUs(retrieveHUs())
.setWarehouseFromId(warehouseFromId)
.process();
return MSG_OK;
}
private Iterator<HUToDistribute> retrieveHUs()
|
{
return handlingUnitsDAO.createHUQueryBuilder()
.setContext(getCtx(), ITrx.TRXNAME_ThreadInherited)
.setOnlyTopLevelHUs()
.addOnlyInWarehouseId(warehouseFromId)
.addOnlyWithAttribute(IHUMaterialTrackingBL.ATTRIBUTENAME_IsQualityInspection, IHUMaterialTrackingBL.ATTRIBUTEVALUE_IsQualityInspection_Yes)
.addHUStatusToInclude(X_M_HU.HUSTATUS_Active)
.addFilter(ddOrderMoveScheduleService.getHUsNotAlreadyScheduledToMoveFilter())
//
.createQuery()
.stream(I_M_HU.class)
.map(HUToDistribute::ofHU)
.iterator();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\process\DD_Order_GenerateForQualityInspectionFlaggedHUs.java
| 1
|
请完成以下Java代码
|
public Mono<Instance> save(Instance instance) {
return this.eventStore.append(instance.getUnsavedEvents()).then(Mono.just(instance.clearUnsavedEvents()));
}
@Override
public Flux<Instance> findAll() {
return this.eventStore.findAll()
.groupBy(InstanceEvent::getInstance)
.flatMap((f) -> f.reduce(Instance.create(f.key()), Instance::apply));
}
@Override
public Mono<Instance> find(InstanceId id) {
return this.eventStore.find(id)
.collectList()
.filter((e) -> !e.isEmpty())
.map((e) -> Instance.create(id).apply(e));
}
@Override
public Flux<Instance> findByName(String name) {
return findAll().filter((a) -> a.isRegistered() && name.equals(a.getRegistration().getName()));
}
|
@Override
public Mono<Instance> compute(InstanceId id, BiFunction<InstanceId, Instance, Mono<Instance>> remappingFunction) {
return this.find(id)
.flatMap((application) -> remappingFunction.apply(id, application))
.switchIfEmpty(Mono.defer(() -> remappingFunction.apply(id, null)))
.flatMap(this::save)
.retryWhen(this.retryOptimisticLockException);
}
@Override
public Mono<Instance> computeIfPresent(InstanceId id,
BiFunction<InstanceId, Instance, Mono<Instance>> remappingFunction) {
return this.find(id)
.flatMap((application) -> remappingFunction.apply(id, application))
.flatMap(this::save)
.retryWhen(this.retryOptimisticLockException);
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\EventsourcingInstanceRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig() {
return FreeMarkerLanguageDriverConfig.newInstance();
}
}
/**
* Configuration class for mybatis-velocity 2.0 or under.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(org.mybatis.scripting.velocity.Driver.class)
@ConditionalOnMissingClass("org.mybatis.scripting.velocity.VelocityLanguageDriverConfig")
@SuppressWarnings("deprecation")
public static class LegacyVelocityConfiguration {
@Bean
@ConditionalOnMissingBean
org.mybatis.scripting.velocity.Driver velocityLanguageDriver() {
return new org.mybatis.scripting.velocity.Driver();
}
}
/**
* Configuration class for mybatis-velocity 2.1.x or above.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ VelocityLanguageDriver.class, VelocityLanguageDriverConfig.class })
public static class VelocityConfiguration {
@Bean
@ConditionalOnMissingBean
VelocityLanguageDriver velocityLanguageDriver(VelocityLanguageDriverConfig config) {
return new VelocityLanguageDriver(config);
}
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".velocity")
public VelocityLanguageDriverConfig velocityLanguageDriverConfig() {
return VelocityLanguageDriverConfig.newInstance();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ThymeleafLanguageDriver.class)
public static class ThymeleafConfiguration {
@Bean
@ConditionalOnMissingBean
ThymeleafLanguageDriver thymeleafLanguageDriver(ThymeleafLanguageDriverConfig config) {
return new ThymeleafLanguageDriver(config);
}
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf")
|
public ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig() {
return ThymeleafLanguageDriverConfig.newInstance();
}
// This class provides to avoid the https://github.com/spring-projects/spring-boot/issues/21626 as workaround.
@SuppressWarnings("unused")
private static class MetadataThymeleafLanguageDriverConfig extends ThymeleafLanguageDriverConfig {
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf.dialect")
@Override
public DialectConfig getDialect() {
return super.getDialect();
}
@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf.template-file")
@Override
public TemplateFileConfig getTemplateFile() {
return super.getTemplateFile();
}
}
}
}
|
repos\spring-boot-starter-master\mybatis-spring-boot-autoconfigure\src\main\java\org\mybatis\spring\boot\autoconfigure\MybatisLanguageDriverAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public static HalProcessDefinition fromProcessDefinition(ProcessDefinition processDefinition, ProcessEngine processEngine) {
HalProcessDefinition halProcDef = new HalProcessDefinition();
halProcDef.id = processDefinition.getId();
halProcDef.key = processDefinition.getKey();
halProcDef.category = processDefinition.getCategory();
halProcDef.description = processDefinition.getDescription();
halProcDef.name = processDefinition.getName();
halProcDef.version = processDefinition.getVersion();
halProcDef.versionTag = processDefinition.getVersionTag();
halProcDef.resource = processDefinition.getResourceName();
halProcDef.deploymentId = processDefinition.getDeploymentId();
halProcDef.diagram = processDefinition.getDiagramResourceName();
halProcDef.suspended = processDefinition.isSuspended();
halProcDef.contextPath = ApplicationContextPathUtil.getApplicationPathForDeployment(processEngine, processDefinition.getDeploymentId());
halProcDef.linker.createLink(REL_SELF, processDefinition.getId());
halProcDef.linker.createLink(REL_DEPLOYMENT, processDefinition.getDeploymentId());
halProcDef.linker.createLink(REL_DEPLOYMENT_RESOURCE, processDefinition.getDeploymentId(), processDefinition.getResourceName());
return halProcDef;
}
public String getId() {
return id;
}
public String getKey() {
return key;
}
public String getCategory() {
return category;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
|
public int getVersion() {
return version;
}
public String getVersionTag() {
return versionTag;
}
public String getResource() {
return resource;
}
public String getDeploymentId() {
return deploymentId;
}
public String getDiagram() {
return diagram;
}
public boolean isSuspended() {
return suspended;
}
public String getContextPath() {
return contextPath;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\processDefinition\HalProcessDefinition.java
| 1
|
请完成以下Java代码
|
public class EncryptablePropertySourceMethodInterceptor<T> extends CachingDelegateEncryptablePropertySource<T> implements MethodInterceptor {
/**
* <p>Constructor for EncryptablePropertySourceMethodInterceptor.</p>
*
* @param delegate a {@link org.springframework.core.env.PropertySource} object
* @param resolver a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver} object
* @param filter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter} object
*/
public EncryptablePropertySourceMethodInterceptor(PropertySource<T> delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
super(delegate, resolver, filter);
}
/** {@inheritDoc} */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (isRefreshCall(invocation)) {
refresh();
return null;
}
if (isGetDelegateCall(invocation)) {
return getDelegate();
}
if (isGetPropertyCall(invocation)) {
return getProperty(getNameArgument(invocation));
}
|
return invocation.proceed();
}
private String getNameArgument(MethodInvocation invocation) {
return (String) invocation.getArguments()[0];
}
private boolean isGetDelegateCall(MethodInvocation invocation) {
return invocation.getMethod().getName().equals("getDelegate");
}
private boolean isRefreshCall(MethodInvocation invocation) {
return invocation.getMethod().getName().equals("refresh");
}
private boolean isGetPropertyCall(MethodInvocation invocation) {
return invocation.getMethod().getName().equals("getProperty")
&& invocation.getMethod().getParameters().length == 1
&& invocation.getMethod().getParameters()[0].getType() == String.class;
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\aop\EncryptablePropertySourceMethodInterceptor.java
| 1
|
请完成以下Java代码
|
public ManagedThreadFactory getThreadFactory() {
return threadFactory;
}
public void setThreadFactory(ManagedThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
protected void initAsyncJobExecutionThreadPool() {
if (threadFactory == null) {
log.warn("A managed thread factory was not found, falling back to self-managed threads");
super.initAsyncJobExecutionThreadPool();
} else {
if (threadPoolQueue == null) {
log.info("Creating thread pool queue of size {}", queueSize);
threadPoolQueue = new ArrayBlockingQueue<Runnable>(queueSize);
}
if (executorService == null) {
log.info(
"Creating executor service with corePoolSize {}, maxPoolSize {} and keepAliveTime {}",
corePoolSize,
maxPoolSize,
keepAliveTime
|
);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
keepAliveTime,
TimeUnit.MILLISECONDS,
threadPoolQueue,
threadFactory
);
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executorService = threadPoolExecutor;
}
startJobAcquisitionThread();
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\ManagedAsyncJobExecutor.java
| 1
|
请完成以下Java代码
|
public void removeLoopVariable(ActivityExecution execution, String variableName) {
execution.removeVariableLocal(variableName);
}
// Getters and Setters ///////////////////////////////////////////////////////////
public Expression getLoopCardinalityExpression() {
return loopCardinalityExpression;
}
public void setLoopCardinalityExpression(Expression loopCardinalityExpression) {
this.loopCardinalityExpression = loopCardinalityExpression;
}
public Expression getCompletionConditionExpression() {
return completionConditionExpression;
}
public void setCompletionConditionExpression(Expression completionConditionExpression) {
this.completionConditionExpression = completionConditionExpression;
}
public Expression getCollectionExpression() {
return collectionExpression;
}
public void setCollectionExpression(Expression collectionExpression) {
this.collectionExpression = collectionExpression;
}
public String getCollectionVariable() {
return collectionVariable;
|
}
public void setCollectionVariable(String collectionVariable) {
this.collectionVariable = collectionVariable;
}
public String getCollectionElementVariable() {
return collectionElementVariable;
}
public void setCollectionElementVariable(String collectionElementVariable) {
this.collectionElementVariable = collectionElementVariable;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java
| 1
|
请完成以下Java代码
|
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
|
public YearMonth getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(YearMonth releaseDate) {
this.releaseDate = releaseDate;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title
+ ", isbn=" + isbn + ", releaseDate=" + releaseDate + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootYearMonth\src\main\java\com\bookstore\entity\Book.java
| 1
|
请完成以下Java代码
|
private UserNotificationRequest createInvoiceGeneratedEvent(
@NonNull final I_C_Invoice invoice,
@Nullable final UserId recipientUserId)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner bpartner = bpartnerDAO.getById(invoice.getC_BPartner_ID());
final String bpValue = bpartner.getValue();
final String bpName = bpartner.getName();
final TableRecordReference invoiceRef = TableRecordReference.of(invoice);
return newUserNotificationRequest()
.recipientUserId(recipientUserId != null ? recipientUserId : UserId.ofRepoId(invoice.getCreatedBy()))
.contentADMessage(MSG_Event_InvoiceGenerated)
.contentADMessageParam(invoiceRef)
|
.contentADMessageParam(bpValue)
.contentADMessageParam(bpName)
.targetAction(TargetRecordAction.of(invoiceRef))
.build();
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC);
}
private void postNotification(final UserNotificationRequest notification)
{
Services.get(INotificationBL.class).sendAfterCommit(notification);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\invoice\event\InvoiceUserNotificationsProducer.java
| 1
|
请完成以下Java代码
|
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 根据值获取名称
*
* @param value
* @return
*/
public static String getNameByValue(String value){
if (oConvertUtils.isEmpty(value)) {
return null;
}
for (DepartCategoryEnum val : values()) {
if (val.getValue().equals(value)) {
return val.getName();
|
}
}
return value;
}
/**
* 根据名称获取值
*
* @param name
* @return
*/
public static String getValueByName(String name){
if (oConvertUtils.isEmpty(name)) {
return null;
}
for (DepartCategoryEnum val : values()) {
if (val.getName().equals(name)) {
return val.getValue();
}
}
return name;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\DepartCategoryEnum.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CFUAAOAuth2ClientController {
@Value("${resource.server.url}")
private String remoteResourceServer;
private RestTemplate restTemplate;
private OAuth2AuthorizedClientService authorizedClientService;
public CFUAAOAuth2ClientController(OAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientService = authorizedClientService;
this.restTemplate = new RestTemplate();
}
@RequestMapping("/")
public String index(OAuth2AuthenticationToken authenticationToken) {
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
String response = "Hello, " + authenticationToken.getPrincipal().getName();
response += "</br></br>";
response += "Here is your accees token :</br>" + oAuth2AccessToken.getTokenValue();
response += "</br>";
response += "</br>You can use it to call these Resource Server APIs:";
response += "</br></br>";
response += "<a href='/read'>Call Resource Server Read API</a>";
response += "</br>";
response += "<a href='/write'>Call Resource Server Write API</a>";
return response;
}
@RequestMapping("/read")
public String read(OAuth2AuthenticationToken authenticationToken) {
String url = remoteResourceServer + "/read";
return callResourceServer(authenticationToken, url);
}
@RequestMapping("/write")
public String write(OAuth2AuthenticationToken authenticationToken) {
String url = remoteResourceServer + "/write";
return callResourceServer(authenticationToken, url);
|
}
private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) {
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue());
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<String> responseEntity = null;
String response = null;
try {
responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
response = responseEntity.getBody();
} catch (HttpClientErrorException e) {
response = e.getMessage();
}
return response;
}
}
|
repos\tutorials-master\security-modules\cloud-foundry-uaa\cf-uaa-oauth2-client\src\main\java\com\baeldung\cfuaa\oauth2\client\CFUAAOAuth2ClientController.java
| 2
|
请完成以下Java代码
|
public class ArrayListOfArrayList {
public static void main(String args[]) {
int vertexCount = 3;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>(vertexCount);
//Initializing each element of ArrayList with ArrayList
for(int i = 0; i< vertexCount; i++) {
graph.add(new ArrayList<Integer>());
}
//We can add any number of columns to each row
graph.get(0).add(1);
graph.get(1).add(2);
graph.get(2).add(0);
|
graph.get(1).add(0);
graph.get(2).add(1);
graph.get(0).add(2);
vertexCount = graph.size();
for(int i = 0; i < vertexCount; i++) {
int edgeCount = graph.get(i).size();
for(int j = 0; j < edgeCount; j++) {
Integer startVertex = i;
Integer endVertex = graph.get(i).get(j);
System.out.printf("Vertex %d is connected to vertex %d%n", startVertex, endVertex);
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-array-list\src\main\java\com\baeldung\list\multidimensional\ArrayListOfArrayList.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected TenantProfile validateUpdate(TenantId tenantId, TenantProfile tenantProfile) {
TenantProfile old = tenantProfileDao.findById(TenantId.SYS_TENANT_ID, tenantProfile.getId().getId());
if (old == null) {
throw new DataValidationException("Can't update non existing tenant profile!");
}
return old;
}
private void validateQueueConfiguration(TenantProfileQueueConfiguration queue) {
validateQueueName(queue.getName());
validateQueueTopic(queue.getTopic());
if (queue.getPollInterval() < 1) {
throw new DataValidationException("Queue poll interval should be more then 0!");
}
if (queue.getPartitions() < 1) {
throw new DataValidationException("Queue partitions should be more then 0!");
}
if (queue.getPackProcessingTimeout() < 1) {
throw new DataValidationException("Queue pack processing timeout should be more then 0!");
}
SubmitStrategy submitStrategy = queue.getSubmitStrategy();
if (submitStrategy == null) {
throw new DataValidationException("Queue submit strategy can't be null!");
}
if (submitStrategy.getType() == null) {
throw new DataValidationException("Queue submit strategy type can't be null!");
}
if (submitStrategy.getType() == SubmitStrategyType.BATCH && submitStrategy.getBatchSize() < 1) {
throw new DataValidationException("Queue submit strategy batch size should be more then 0!");
}
ProcessingStrategy processingStrategy = queue.getProcessingStrategy();
|
if (processingStrategy == null) {
throw new DataValidationException("Queue processing strategy can't be null!");
}
if (processingStrategy.getType() == null) {
throw new DataValidationException("Queue processing strategy type can't be null!");
}
if (processingStrategy.getRetries() < 0) {
throw new DataValidationException("Queue processing strategy retries can't be less then 0!");
}
if (processingStrategy.getFailurePercentage() < 0 || processingStrategy.getFailurePercentage() > 100) {
throw new DataValidationException("Queue processing strategy failure percentage should be in a range from 0 to 100!");
}
if (processingStrategy.getPauseBetweenRetries() < 0) {
throw new DataValidationException("Queue processing strategy pause between retries can't be less then 0!");
}
if (processingStrategy.getMaxPauseBetweenRetries() < processingStrategy.getPauseBetweenRetries()) {
throw new DataValidationException("Queue processing strategy MAX pause between retries can't be less then pause between retries!");
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\TenantProfileDataValidator.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> queryByAppAndResource(String app, String identity, Long startTime, Long endTime) {
if (StringUtil.isEmpty(app)) {
return Result.ofFail(-1, "app can't be null or empty");
}
if (StringUtil.isEmpty(identity)) {
return Result.ofFail(-1, "identity can't be null or empty");
}
if (endTime == null) {
endTime = System.currentTimeMillis();
}
if (startTime == null) {
startTime = endTime - 1000 * 60;
}
if (endTime - startTime > maxQueryIntervalMs) {
return Result.ofFail(-1, "time intervalMs is too big, must <= 1h");
}
List<MetricEntity> entities = metricStore.queryByAppAndResourceBetween(
app, identity, startTime, endTime);
List<MetricVo> vos = MetricVo.fromMetricEntities(entities, identity);
|
return Result.ofSuccess(sortMetricVoAndDistinct(vos));
}
private Iterable<MetricVo> sortMetricVoAndDistinct(List<MetricVo> vos) {
if (vos == null) {
return null;
}
Map<Long, MetricVo> map = new TreeMap<>();
for (MetricVo vo : vos) {
MetricVo oldVo = map.get(vo.getTimestamp());
if (oldVo == null || vo.getGmtCreate() > oldVo.getGmtCreate()) {
map.put(vo.getTimestamp(), vo);
}
}
return map.values();
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\MetricController.java
| 2
|
请完成以下Java代码
|
private static void sortAndAddMapEntriesToList(
@NonNull final Multimap<IPair<String, AttributeId>, AttributeValueId> groupNameToAttributeValueIds,
@NonNull final Builder<DimensionSpecGroup> list)
{
final Collection<Entry<IPair<String, AttributeId>, Collection<AttributeValueId>>> //
entrySet = groupNameToAttributeValueIds.asMap().entrySet();
final ArrayList<DimensionSpecGroup> newGroups = new ArrayList<>();
for (final Entry<IPair<String, AttributeId>, Collection<AttributeValueId>> entry : entrySet)
{
final String groupName = entry.getKey().getLeft();
final ITranslatableString groupNameTrl = TranslatableStrings.constant(groupName);
final Optional<AttributeId> groupAttributeId = Optional.ofNullable(entry.getKey().getRight());
final AttributesKey attributesKey = createAttributesKey(entry.getValue());
final DimensionSpecGroup newGroup = new DimensionSpecGroup(
() -> groupNameTrl,
attributesKey,
groupAttributeId);
|
newGroups.add(newGroup);
}
newGroups.sort(Comparator.comparing(DimensionSpecGroup::getAttributesKey));
list.addAll(newGroups);
}
private static AttributesKey createAttributesKey(final Collection<AttributeValueId> values)
{
return AttributesKey.ofParts(
values.stream()
.map(AttributesKeyPart::ofAttributeValueId)
.collect(ImmutableSet.toImmutableSet()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java\de\metas\dimension\DimensionSpec.java
| 1
|
请完成以下Java代码
|
default BigDecimal getQtyAsBigDecimal()
{
return getQty().toBigDecimal();
}
default Quantity getQty(@NonNull final UomId uomId)
{
final I_C_UOM uomRecord = Services.get(IUOMDAO.class).getById(uomId);
return getQty(uomRecord);
}
/**
* Gets storage Qty, converted to given UOM.
*
* @return Qty converted to given UOM.
*/
Quantity getQty(I_C_UOM uom);
/**
* @return storage capacity
|
*/
BigDecimal getQtyCapacity();
IAllocationRequest removeQty(IAllocationRequest request);
IAllocationRequest addQty(IAllocationRequest request);
void markStaled();
boolean isEmpty();
/**
* @return true if this storage allows negative storages
*/
boolean isAllowNegativeStorage();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\IProductStorage.java
| 1
|
请完成以下Java代码
|
public iframe setWidth(int width)
{
addAttribute("width",Integer.toString(width));
return this;
}
/**
Sets the marginheight="" attribute
@param marginheight the marginheight="" attribute
*/
public iframe setMarginHeight(int marginheight)
{
setMarginHeight(Integer.toString(marginheight));
return this;
}
/**
Sets the marginheight="" attribute
@param marginheight the marginheight="" attribute
*/
public iframe setMarginHeight(String marginheight)
{
addAttribute("marginheight",marginheight);
return this;
}
/**
Sets the scrolling="" attribute
@param scrolling the scrolling="" attribute
*/
public iframe setScrolling(String scrolling)
{
addAttribute("scrolling",scrolling);
return this;
}
/**
Sets the align="" attribute.
@param align sets the align="" attribute. You can
use the AlignType.* variables for convience.
*/
public iframe setAlign(String align)
{
addAttribute("align",align);
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public iframe addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public iframe addElement(String hashcode,String element)
{
|
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public iframe addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public iframe addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public iframe removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\iframe.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User implements Serializable {
/**
* 编号
*/
@Id
@GeneratedValue
private Long id;
/**
* 名称
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 出生时间
*/
private String birthday;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
}
|
repos\springboot-learning-example-master\chapter-5-spring-boot-paging-sorting\src\main\java\spring\boot\core\domain\User.java
| 2
|
请完成以下Java代码
|
public String getId() {
return this.id;
}
@Override
public void putObject(Object key, Object value) {
if (value != null) {
// 向Redis中添加数据,有效时间是2天
redisTemplate.opsForValue().set(key.toString(), value, 2, TimeUnit.DAYS);
}
}
@Override
public Object getObject(Object key) {
try {
if (key != null) {
Object obj = redisTemplate.opsForValue().get(key.toString());
return obj;
}
} catch (Exception e) {
logger.error("redis ");
}
return null;
}
@Override
public Object removeObject(Object key) {
try {
if (key != null) {
redisTemplate.delete(key.toString());
}
} catch (Exception e) {
}
return null;
}
@Override
public void clear() {
logger.debug("清空缓存");
try {
Set<String> keys = redisTemplate.keys("*:" + this.id + "*");
|
if (!CollectionUtils.isEmpty(keys)) {
redisTemplate.delete(keys);
}
} catch (Exception e) {
}
}
@Override
public int getSize() {
Long size = (Long) redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.dbSize();
}
});
return size.intValue();
}
@Override
public ReadWriteLock getReadWriteLock() {
return this.readWriteLock;
}
}
|
repos\spring-boot-student-master\spring-boot-student-mybatis-redis\src\main\java\com\xiaolyuh\redis\cache\MybatisRedisCache.java
| 1
|
请完成以下Java代码
|
public void setM_Material_Tracking_Report_Line(de.metas.materialtracking.ch.lagerkonf.model.I_M_Material_Tracking_Report_Line M_Material_Tracking_Report_Line)
{
set_ValueFromPO(COLUMNNAME_M_Material_Tracking_Report_Line_ID, de.metas.materialtracking.ch.lagerkonf.model.I_M_Material_Tracking_Report_Line.class, M_Material_Tracking_Report_Line);
}
/** Set M_Material_Tracking_Report_Line.
@param M_Material_Tracking_Report_Line_ID M_Material_Tracking_Report_Line */
@Override
public void setM_Material_Tracking_Report_Line_ID (int M_Material_Tracking_Report_Line_ID)
{
if (M_Material_Tracking_Report_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_Line_ID, Integer.valueOf(M_Material_Tracking_Report_Line_ID));
}
/** Get M_Material_Tracking_Report_Line.
@return M_Material_Tracking_Report_Line */
@Override
public int getM_Material_Tracking_Report_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Report_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order)
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order);
}
/** Set Produktionsauftrag.
@param PP_Order_ID Produktionsauftrag */
@Override
public void setPP_Order_ID (int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_Value (COLUMNNAME_PP_Order_ID, null);
else
set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID));
}
/** Get Produktionsauftrag.
@return Produktionsauftrag */
@Override
public int getPP_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausgelagerte Menge.
@param QtyIssued Ausgelagerte Menge */
@Override
public void setQtyIssued (java.math.BigDecimal QtyIssued)
{
set_Value (COLUMNNAME_QtyIssued, QtyIssued);
|
}
/** Get Ausgelagerte Menge.
@return Ausgelagerte Menge */
@Override
public java.math.BigDecimal getQtyIssued ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Empfangene Menge.
@param QtyReceived Empfangene Menge */
@Override
public void setQtyReceived (java.math.BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
/** Get Empfangene Menge.
@return Empfangene Menge */
@Override
public java.math.BigDecimal getQtyReceived ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report_Line_Alloc.java
| 1
|
请完成以下Java代码
|
protected boolean isAutoFetchingEnabled() {
return isAutoFetchingEnabled;
}
protected BackoffStrategy getBackoffStrategy() {
return backoffStrategy;
}
public String getDefaultSerializationFormat() {
return defaultSerializationFormat;
}
public String getDateFormat() {
return dateFormat;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
|
}
public ValueMappers getValueMappers() {
return valueMappers;
}
public TypedValues getTypedValues() {
return typedValues;
}
public EngineClient getEngineClient() {
return engineClient;
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void codeProcessingUrl(
@RequestParam(value = "code") String code, @RequestParam(value = "state") String state,
HttpServletRequest request, HttpServletResponse response) throws ThingsboardException, IOException {
Optional<Cookie> prevUrlOpt = CookieUtils.getCookie(request, PREV_URI_COOKIE_NAME);
Optional<Cookie> cookieState = CookieUtils.getCookie(request, STATE_COOKIE_NAME);
String baseUrl = this.systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request);
String prevUri = baseUrl + (prevUrlOpt.isPresent() ? prevUrlOpt.get().getValue() : "/settings/outgoing-mail");
if (cookieState.isEmpty() || !cookieState.get().getValue().equals(state)) {
CookieUtils.deleteCookie(request, response, STATE_COOKIE_NAME);
throw new ThingsboardException("Refresh token was not generated, invalid state param", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
CookieUtils.deleteCookie(request, response, STATE_COOKIE_NAME);
CookieUtils.deleteCookie(request, response, PREV_URI_COOKIE_NAME);
AdminSettings adminSettings = checkNotNull(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, MAIL_SETTINGS_KEY), "No Administration mail settings found");
JsonNode jsonValue = adminSettings.getJsonValue();
String clientId = checkNotNull(jsonValue.get("clientId"), "No clientId was configured").asText();
String clientSecret = checkNotNull(jsonValue.get("clientSecret"), "No client secret was configured").asText();
|
String clientRedirectUri = checkNotNull(jsonValue.get("redirectUri"), "No Redirect uri was configured").asText();
String tokenUri = checkNotNull(jsonValue.get("tokenUri"), "No authorization uri was configured").asText();
TokenResponse tokenResponse;
try {
tokenResponse = new AuthorizationCodeTokenRequest(new NetHttpTransport(), new GsonFactory(), new GenericUrl(tokenUri), code)
.setRedirectUri(clientRedirectUri)
.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret))
.execute();
} catch (IOException e) {
log.warn("Unable to retrieve refresh token: {}", e.getMessage());
throw new ThingsboardException("Error while requesting access token: " + e.getMessage(), ThingsboardErrorCode.GENERAL);
}
((ObjectNode) jsonValue).put("refreshToken", tokenResponse.getRefreshToken());
((ObjectNode) jsonValue).put("tokenGenerated", true);
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, adminSettings);
response.sendRedirect(prevUri);
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\AdminController.java
| 2
|
请完成以下Java代码
|
public int getM_AttributeSetInstance_ID()
{
final Object asiObj = infoWindow.getValue(rowIndexModel, COLUMNNAME_M_AttributeSetInstance_ID);
if (asiObj == null)
{
return -1;
}
else if (asiObj instanceof KeyNamePair)
{
return ((KeyNamePair)asiObj).getKey();
}
else if (asiObj instanceof Number)
{
return ((Number)asiObj).intValue();
}
else
{
throw new AdempiereException("Unsupported value for " + COLUMNNAME_M_AttributeSetInstance_ID + ": " + asiObj);
}
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
throw new UnsupportedOperationException();
}
@Override
public void setQty(final BigDecimal qty)
{
infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_Qty_CU, rowIndexModel, qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_Qty_CU);
return qty;
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
throw new UnsupportedOperationException();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final KeyNamePair huPiItemProductKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_M_HU_PI_Item_Product_ID);
if (huPiItemProductKNP == null)
{
return -1;
}
final int piItemProductId = huPiItemProductKNP.getKey();
if (piItemProductId <= 0)
{
return -1;
}
return piItemProductId;
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_QtyPacks);
return qty;
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_QtyPacks, rowIndexModel, qtyPacks);
}
@Override
|
public int getC_UOM_ID()
{
return Services.get(IProductBL.class).getStockUOMId(getM_Product_ID()).getRepoId();
}
@Override
public void setC_UOM_ID(final int uomId)
{
throw new UnsupportedOperationException();
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
throw new UnsupportedOperationException();
}
@Override
public int getC_BPartner_ID()
{
final KeyNamePair bpartnerKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_C_BPartner_ID);
return bpartnerKNP != null ? bpartnerKNP.getKey() : -1;
}
@Override
public boolean isInDispute()
{
// there is no InDispute flag to be considered
return false;
}
@Override
public void setInDispute(final boolean inDispute)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareInfoWindowAdapter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<UserId> retrieveUserInChargeOrNull(@NonNull final OrgId orgId)
{
final org.compiere.model.I_AD_User user = retrieveUserInChargeOrNull(Env.getCtx(), orgId.getRepoId(), ITrx.TRXNAME_None);
if (user != null)
{
return Optional.of(UserId.ofRepoId(user.getAD_User_ID()));
}
return Optional.empty();
}
@Override
@Deprecated
public org.compiere.model.I_AD_User retrieveUserInChargeOrNull(final Properties ctx, final int orgId, final String trxName)
{
final IBPartnerDAO bPartnerPA = Services.get(IBPartnerDAO.class);
org.compiere.model.I_AD_User defaultContact;
try
{
final I_C_BPartner orgBPartner = bPartnerPA.retrieveOrgBPartner(ctx, orgId, I_C_BPartner.class, trxName);
defaultContact = bPartnerPA.retrieveDefaultContactOrNull(orgBPartner, I_AD_User.class);
}
catch (final OrgHasNoBPartnerLinkException e)
{
defaultContact = null;
}
return defaultContact;
}
@NonNull
@Override
public String getOrgLanguageOrLoggedInUserLanguage(@NonNull final OrgId orgId)
{
|
final OrgInfo orgInfo = orgDAO.getOrgInfoById(orgId);
final BPartnerId orgBpartnerId = orgInfo.getOrgBPartnerLocationId().getBpartnerId();
final Language language = Services.get(IBPartnerBL.class)
.getLanguage(orgBpartnerId)
.orElse(null);
if (language != null)
{
return language.getAD_Language();
}
else
{
return Env.getADLanguageOrBaseLanguage();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerOrgBL.java
| 2
|
请完成以下Java代码
|
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public boolean isDeleted() {
return deleted;
}
public boolean isNotDeleted() {
return notDeleted;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isWithException() {
return withJobException;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
|
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public HistoricProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) {
if (involvedGroups == null || involvedGroups.isEmpty()) {
throw new ActivitiIllegalArgumentException("Involved groups list is null or empty.");
}
if (inOrStatement) {
this.currentOrQueryObject.involvedGroups = involvedGroups;
} else {
this.involvedGroups = involvedGroups;
}
return this;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public static BufferedImage signImageAdaptBasedOnImage(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = createFontToFit(new Font("Arial", Font.BOLD, 80), text, image);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = (image.getWidth() - metrics.stringWidth(text));
int positionY = (image.getHeight() - metrics.getHeight()) + metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
public static Font createFontToFit(Font baseFont, String text, BufferedImage image) throws IOException
{
Font newFont = baseFont;
FontMetrics ruler = image.getGraphics().getFontMetrics(baseFont);
|
GlyphVector vector = baseFont.createGlyphVector(ruler.getFontRenderContext(), text);
Shape outline = vector.getOutline(0, 0);
double expectedWidth = outline.getBounds().getWidth();
double expectedHeight = outline.getBounds().getHeight();
boolean textFits = image.getWidth() >= expectedWidth && image.getHeight() >= expectedHeight;
if(!textFits) {
double widthBasedFontSize = (baseFont.getSize2D()*image.getWidth())/expectedWidth;
double heightBasedFontSize = (baseFont.getSize2D()*image.getHeight())/expectedHeight;
double newFontSize = widthBasedFontSize < heightBasedFontSize ? widthBasedFontSize : heightBasedFontSize;
newFont = baseFont.deriveFont(baseFont.getStyle(), (float)newFontSize);
}
return newFont;
}
}
|
repos\tutorials-master\image-processing\src\main\java\com\baeldung\imageprocessing\addingtext\AddText.java
| 1
|
请完成以下Java代码
|
public void setIsRepeat (boolean IsRepeat)
{
set_Value (COLUMNNAME_IsRepeat, Boolean.valueOf(IsRepeat));
}
/** Get Repeat.
@return Repeat */
@Override
public boolean isRepeat ()
{
Object oo = get_Value(COLUMNNAME_IsRepeat);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
|
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_NonBusinessDay.java
| 1
|
请完成以下Java代码
|
public void setKeepLogDays (int KeepLogDays)
{
set_Value (COLUMNNAME_KeepLogDays, Integer.valueOf(KeepLogDays));
}
/** Get Days to keep Log.
@return Number of days to keep the log entries
*/
public int getKeepLogDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_KeepLogDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
|
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_AD_User getSupervisor() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSupervisor_ID(), get_TrxName()); }
/** Set Supervisor.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Supervisor.
@return Supervisor for this user/organization - used for escalation and approval
*/
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static void validatePageLink(PageLink pageLink, Set<String> allowedSortProperties) {
if (pageLink == null) {
throw new IncorrectParameterException("Page link must be specified.");
} else if (pageLink.getPageSize() < 1) {
throw new IncorrectParameterException("Incorrect page link page size '" + pageLink.getPageSize() + "'. Page size must be greater than zero.");
} else if (pageLink.getPage() < 0) {
throw new IncorrectParameterException("Incorrect page link page '" + pageLink.getPage() + "'. Page must be positive integer.");
} else if (pageLink.getSortOrder() != null) {
String sortProperty = pageLink.getSortOrder().getProperty();
if (!isValidProperty(sortProperty)) {
throw new IncorrectParameterException("Invalid page link sort property");
}
if (allowedSortProperties != null && !allowedSortProperties.contains(sortProperty)) {
throw new IncorrectParameterException(
"Unsupported sort property '" + sortProperty + "'. Only '" + String.join("', '", allowedSortProperties) + "' are allowed."
);
}
}
}
public static void validateEntityDataPageLink(EntityDataPageLink pageLink) {
if (pageLink == null) {
throw new IncorrectParameterException("Entity Data Page link must be specified.");
} else if (pageLink.getPageSize() < 1) {
throw new IncorrectParameterException("Incorrect entity data page link page size '" + pageLink.getPageSize() + "'. Page size must be greater than zero.");
} else if (pageLink.getPage() < 0) {
|
throw new IncorrectParameterException("Incorrect entity data page link page '" + pageLink.getPage() + "'. Page must be positive integer.");
} else if (pageLink.getSortOrder() != null && pageLink.getSortOrder().getKey() != null) {
EntityKey sortKey = pageLink.getSortOrder().getKey();
if ((sortKey.getType() == EntityKeyType.ENTITY_FIELD || sortKey.getType() == EntityKeyType.ALARM_FIELD)
&& !isValidProperty(sortKey.getKey())) {
throw new IncorrectParameterException("Invalid entity data page link sort property");
}
}
}
public static boolean isValidProperty(String key) {
return StringUtils.isEmpty(key) || RegexUtils.matches(key, PROPERTY_PATTERN);
}
public static void checkNotNull(Object reference, String errorMessage) {
if (reference == null) {
throw new IncorrectParameterException(errorMessage);
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\Validator.java
| 2
|
请完成以下Java代码
|
private HULabelConfig getLabelConfig(final @NonNull HUToReport hu)
{
return cache.computeIfAbsent(toHULabelConfigQuery(hu), huLabelService::getFirstMatching)
.orElseThrow();
}
private static HULabelConfigQuery toHULabelConfigQuery(final @NonNull HUToReport hu)
{
return HULabelConfigQuery.builder()
.sourceDocType(HULabelSourceDocType.Manufacturing)
.huUnitType(hu.getHUUnitType())
.bpartnerId(hu.getBPartnerId())
.build();
}
}
private static class BatchToPrintCollector
{
private final HULabelConfigProvider labelConfigProvider;
@Getter
private final ArrayList<BatchToPrint> batches = new ArrayList<>();
private final HashSet<HuId> huIdsCollected = new HashSet<>();
private BatchToPrintCollector(final HULabelConfigProvider huLabelConfigProvider)
{
this.labelConfigProvider = huLabelConfigProvider;
}
public void addAllRecursive(@NonNull final List<HUToReport> hus)
{
for (final HUToReport hu : hus)
{
add(hu, labelConfigProvider.getLabelConfig(hu));
final HuUnitType huUnitType = hu.getHUUnitType();
if (huUnitType == HuUnitType.LU)
{
for (final HUToReport includedHU : hu.getIncludedHUs())
{
add(includedHU, labelConfigProvider.getLabelConfig(includedHU));
}
}
}
}
public void add(@NonNull final HUToReport hu, @NonNull final HULabelConfig labelConfig)
{
// Don't add it if we already considered it
if (!huIdsCollected.add(hu.getHUId()))
{
return;
}
final BatchToPrint lastBatch = !batches.isEmpty() ? batches.get(batches.size() - 1) : null;
final BatchToPrint batch;
if (lastBatch == null || !lastBatch.isMatching(labelConfig))
{
batch = new BatchToPrint(labelConfig.getPrintFormatProcessId());
batches.add(batch);
}
|
else
{
batch = lastBatch;
}
batch.addHU(hu);
}
public void forEach(@NonNull final Consumer<BatchToPrint> action)
{
batches.forEach(action);
}
}
@Getter
private static class BatchToPrint
{
@NonNull
private final AdProcessId printFormatProcessId;
@NonNull
private final ArrayList<HUToReport> hus = new ArrayList<>();
private BatchToPrint(final @NonNull AdProcessId printFormatProcessId)
{
this.printFormatProcessId = printFormatProcessId;
}
public boolean isMatching(@NonNull final HULabelConfig labelConfig)
{
return AdProcessId.equals(printFormatProcessId, labelConfig.getPrintFormatProcessId());
}
public void addHU(@NonNull final HUToReport hu)
{
this.hus.add(hu);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\printReceivedHUQRCodes\PrintReceivedHUQRCodesActivityHandler.java
| 1
|
请完成以下Java代码
|
public class JMXPOJOLookupMap implements JMXPOJOLookupMapMBean
{
private final WeakReference<POJOLookupMap> databaseRef;
private final String jmxName;
public JMXPOJOLookupMap(final POJOLookupMap database)
{
super();
Check.assumeNotNull(database, "database not null");
this.databaseRef = new WeakReference<POJOLookupMap>(database);
this.jmxName = POJOLookupMap.class.getName() + ":type=" + database.getDatabaseName();
}
private POJOLookupMap getDatabase()
{
final POJOLookupMap database = databaseRef.get();
if (database == null)
{
throw new AdempiereException("Database expired");
|
}
return database;
}
@Override
public void dump()
{
final POJOLookupMap database = getDatabase();
database.dumpStatus();
}
public String getJMXName()
{
return jmxName;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\jmx\JMXPOJOLookupMap.java
| 1
|
请完成以下Java代码
|
public void setPosted (boolean Posted)
{
set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted));
}
/** Get Posted.
@return Posting status
*/
public boolean isPosted ()
{
Object oo = get_Value(COLUMNNAME_Posted);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
|
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public org.eevolution.model.I_HR_Process getReversal() throws RuntimeException
{
return (org.eevolution.model.I_HR_Process)MTable.get(getCtx(), org.eevolution.model.I_HR_Process.Table_Name)
.getPO(getReversal_ID(), get_TrxName()); }
/** Set Reversal ID.
@param Reversal_ID
ID of document reversal
*/
public void setReversal_ID (int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID));
}
/** Get Reversal ID.
@return ID of document reversal
*/
public int getReversal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Process.java
| 1
|
请完成以下Java代码
|
public class DeleteUnmappedInstanceVisitor implements TreeVisitor<MigratingScopeInstance> {
protected Set<MigratingScopeInstance> visitedInstances = new HashSet<MigratingScopeInstance>();
protected boolean skipCustomListeners;
protected boolean skipIoMappings;
public DeleteUnmappedInstanceVisitor(boolean skipCustomListeners, boolean skipIoMappings) {
this.skipCustomListeners = skipCustomListeners;
this.skipIoMappings = skipIoMappings;
}
@Override
public void visit(MigratingScopeInstance currentInstance) {
visitedInstances.add(currentInstance);
if (!currentInstance.migrates()) {
Set<MigratingProcessElementInstance> children = new HashSet<MigratingProcessElementInstance>(currentInstance.getChildren());
MigratingScopeInstance parent = currentInstance.getParent();
// 1. detach children
|
currentInstance.detachChildren();
// 2. manipulate execution tree (i.e. remove this instance)
currentInstance.remove(skipCustomListeners, skipIoMappings);
// 3. reconnect parent and children
for (MigratingProcessElementInstance child : children) {
child.attachState(parent);
}
}
else {
currentInstance.removeUnmappedDependentInstances();
}
}
public boolean hasVisitedAll(Collection<MigratingScopeInstance> activityInstances) {
return visitedInstances.containsAll(activityInstances);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\DeleteUnmappedInstanceVisitor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<String> getMappingResources() {
return this.mappingResources;
}
public @Nullable String getDatabasePlatform() {
return this.databasePlatform;
}
public void setDatabasePlatform(@Nullable String databasePlatform) {
this.databasePlatform = databasePlatform;
}
public @Nullable Database getDatabase() {
return this.database;
}
public void setDatabase(@Nullable Database database) {
this.database = database;
}
public boolean isGenerateDdl() {
return this.generateDdl;
|
}
public void setGenerateDdl(boolean generateDdl) {
this.generateDdl = generateDdl;
}
public boolean isShowSql() {
return this.showSql;
}
public void setShowSql(boolean showSql) {
this.showSql = showSql;
}
public @Nullable Boolean getOpenInView() {
return this.openInView;
}
public void setOpenInView(@Nullable Boolean openInView) {
this.openInView = openInView;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jpa\src\main\java\org\springframework\boot\jpa\autoconfigure\JpaProperties.java
| 2
|
请完成以下Java代码
|
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
|
}
public void setPassword(String password) {
this.password = password;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
}
|
repos\springBoot-master\springboot-SpringSecurity0\src\main\java\com\us\example\domain\SysUser.java
| 1
|
请完成以下Java代码
|
public class POReferenceAsSequenceNoProvider implements CustomSequenceNoProvider
{
private static final Logger logger = LogManager.getLogger(POReferenceAsSequenceNoProvider.class);
private static final String PARAM_POReference = "POReference";
/** @return {@code true} if the given {@code context} has a non-null {@code POReference} value. */
@Override
public boolean isApplicable(@NonNull final Evaluatee context, @NonNull final DocumentSequenceInfo docSeqInfo)
{
final String poReference = getPOReferenceOrNull(context);
final boolean result = Check.isNotBlank(poReference);
logger.debug("isApplicable - Given evaluatee-context contains {}={}; -> returning {}; context={}", PARAM_POReference, poReference, result, context);
return result;
}
/** @return the given {@code context}'s {@code POReference} value. */
@Override
public String provideSequenceNo(@NonNull final Evaluatee context, @NonNull final DocumentSequenceInfo docSeqInfo, final String autoIncrementedSeqNumber)
{
final String poReference = getPOReferenceOrNull(context);
Check.assumeNotNull(poReference, "The given context needs to have a non-empty POreference value; context={}", context);
final String poReferenceResult;
if (Check.isNotBlank(autoIncrementedSeqNumber))
{
poReferenceResult = poReference + "-" + autoIncrementedSeqNumber;
}
|
else {
poReferenceResult = poReference;
}
logger.debug("provideSequenceNo - returning {};", poReferenceResult);
return poReferenceResult;
}
private static String getPOReferenceOrNull(@NonNull final Evaluatee context)
{
String poReference = context.get_ValueAsString(PARAM_POReference);
if (poReference == null)
{
return null;
}
poReference = poReference.trim();
return !poReference.isEmpty() ? poReference : null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequenceno\POReferenceAsSequenceNoProvider.java
| 1
|
请完成以下Java代码
|
public class DelegateFlowableEventListener extends BaseDelegateEventListener {
protected String className;
protected FlowableEventListener delegateInstance;
protected boolean failOnException;
public DelegateFlowableEventListener(String className, Class<?> entityClass) {
this.className = className;
setEntityClass(entityClass);
}
@Override
public void onEvent(FlowableEvent event) {
if (isValidEvent(event)) {
getDelegateInstance().onEvent(event);
}
}
@Override
public boolean isFailOnException() {
if (delegateInstance != null) {
return delegateInstance.isFailOnException();
}
return failOnException;
|
}
protected FlowableEventListener getDelegateInstance() {
if (delegateInstance == null) {
Object instance = ReflectUtil.instantiate(className);
if (instance instanceof FlowableEventListener) {
delegateInstance = (FlowableEventListener) instance;
} else {
// Force failing of the listener invocation, since the delegate
// cannot be created
failOnException = true;
throw new FlowableIllegalArgumentException("Class " + className + " does not implement " + FlowableEventListener.class.getName());
}
}
return delegateInstance;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\helper\DelegateFlowableEventListener.java
| 1
|
请完成以下Java代码
|
public boolean delete(boolean force) {
return po.delete(force); // delete
}
/**
* Delete Current Record
* @param force delete also processed records
* @param trxName transaction
*/
public boolean delete(boolean force, String trxName) {
return po.delete(force, trxName); // delete
}
/**************************************************************************
* Lock it.
* @return true if locked
*/
public boolean lock() {
return po.lock(); // lock
}
/**
* UnLock it
* @return true if unlocked (false only if unlock fails)
*/
public boolean unlock(String trxName) {
|
return po.unlock(trxName); // unlock
}
/**
* Set Trx
* @param trxName transaction
*/
public void set_TrxName(String trxName) {
po.set_TrxName(trxName); // setTrx
}
/**
* Get Trx
* @return transaction
*/
public String get_TrxName() {
return po.get_TrxName(); // getTrx
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: demo-consumer # Spring 应用名
cloud:
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
server:
port: 28080 # 服务器端口。默认为 8080
ribbon:
# Ribbon 饥饿加载配置项,对应 RibbonEagerLoadPropertie
|
s 配置类
eager-load:
enabled: true # 是否开启饥饿加载。默认为 false 不开启
clients: user-provider # 开启饥饿加载的 Ribbon 客户端名字。如果有多个,使用 , 逗号分隔。
|
repos\SpringBoot-Labs-master\labx-02-spring-cloud-netflix-ribbon\labx-02-scn-ribbon-demo04-consumer\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public class X_R_Resolution extends PO implements I_R_Resolution, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_R_Resolution (Properties ctx, int R_Resolution_ID, String trxName)
{
super (ctx, R_Resolution_ID, trxName);
/** if (R_Resolution_ID == 0)
{
setName (null);
setR_Resolution_ID (0);
} */
}
/** Load Constructor */
public X_R_Resolution (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_R_Resolution[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
|
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Resolution.
@param R_Resolution_ID
Request Resolution
*/
public void setR_Resolution_ID (int R_Resolution_ID)
{
if (R_Resolution_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Resolution_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Resolution_ID, Integer.valueOf(R_Resolution_ID));
}
/** Get Resolution.
@return Request Resolution
*/
public int getR_Resolution_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Resolution_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Resolution.java
| 1
|
请完成以下Java代码
|
private List<PropertySource<?>> getPropertySources() {
List<PropertySource<?>> propertySources = new ArrayList<>();
for (String fileName : FILE_NAMES) {
addPropertySource(propertySources, CONFIG_PATH + fileName, this::getPropertySourceName);
}
return propertySources;
}
private String getPropertySourceName(File file) {
return "devtools-local: [" + file.toURI() + "]";
}
private void addPropertySource(List<PropertySource<?>> propertySources, String fileName,
Function<File, String> propertySourceNamer) {
File home = getHomeDirectory();
File file = (home != null) ? new File(home, fileName) : null;
FileSystemResource resource = (file != null) ? new FileSystemResource(file) : null;
if (resource != null && resource.exists() && resource.isFile()) {
addPropertySource(propertySources, resource, propertySourceNamer);
}
}
private void addPropertySource(List<PropertySource<?>> propertySources, FileSystemResource resource,
Function<File, String> propertySourceNamer) {
try {
String name = propertySourceNamer.apply(resource.getFile());
for (PropertySourceLoader loader : PROPERTY_SOURCE_LOADERS) {
if (canLoadFileExtension(loader, resource.getFilename())) {
propertySources.addAll(loader.load(name, resource));
}
}
}
catch (IOException ex) {
throw new IllegalStateException("Unable to load " + resource.getFilename(), ex);
|
}
}
private boolean canLoadFileExtension(PropertySourceLoader loader, String name) {
return Arrays.stream(loader.getFileExtensions())
.anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension));
}
protected @Nullable File getHomeDirectory() {
return getHomeDirectory(() -> this.environmentVariables.get("SPRING_DEVTOOLS_HOME"),
() -> this.systemProperties.getProperty("spring.devtools.home"),
() -> this.systemProperties.getProperty("user.home"));
}
@SafeVarargs
private @Nullable File getHomeDirectory(Supplier<String>... pathSuppliers) {
for (Supplier<String> pathSupplier : pathSuppliers) {
String path = pathSupplier.get();
if (StringUtils.hasText(path)) {
return new File(path);
}
}
return null;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\env\DevToolsHomePropertiesPostProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
|
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
| 2
|
请完成以下Java代码
|
private static InvoiceQuery.InvoiceQueryBuilder createInvoiceQuery(@NonNull final IdentifierString identifierString)
{
final IdentifierString.Type type = identifierString.getType();
if (IdentifierString.Type.METASFRESH_ID.equals(type))
{
return InvoiceQuery.builder().invoiceId(MetasfreshId.toValue(identifierString.asMetasfreshId()));
}
else if (IdentifierString.Type.EXTERNAL_ID.equals(type))
{
return InvoiceQuery.builder().externalId(identifierString.asExternalId());
}
else if (IdentifierString.Type.DOC.equals(type))
{
return InvoiceQuery.builder().documentNo(identifierString.asDoc());
}
else
{
throw new AdempiereException("Invalid identifierString: " + identifierString);
}
}
private Optional<I_C_Order> getOrderIdFromIdentifier(final IdentifierString orderIdentifier, final OrgId orgId)
{
return orderDAO.retrieveByOrderCriteria(createOrderQuery(orderIdentifier, orgId));
}
private OrderQuery createOrderQuery(final IdentifierString identifierString, final OrgId orgId)
{
final IdentifierString.Type type = identifierString.getType();
final OrderQuery.OrderQueryBuilder builder = OrderQuery.builder().orgId(orgId);
if (IdentifierString.Type.METASFRESH_ID.equals(type))
{
|
return builder
.orderId(MetasfreshId.toValue(identifierString.asMetasfreshId()))
.build();
}
else if (IdentifierString.Type.EXTERNAL_ID.equals(type))
{
return builder
.externalId(identifierString.asExternalId())
.build();
}
else if (IdentifierString.Type.DOC.equals(type))
{
return builder
.documentNo(identifierString.asDoc())
.build();
}
else
{
throw new AdempiereException("Invalid identifierString: " + identifierString);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\payment\JsonPaymentService.java
| 1
|
请完成以下Java代码
|
public class CamundaBpmVersion implements Supplier<String> {
private static final String VERSION_FORMAT = "(v%s)";
public static final String VERSION = "version";
public static final String IS_ENTERPRISE = "is-enterprise";
public static final String FORMATTED_VERSION = "formatted-version";
public static String key(String name) {
return PREFIX + "." + name;
}
private final String version;
private final boolean isEnterprise;
private final String formattedVersion;
public CamundaBpmVersion() {
this(ProcessEngine.class.getPackage());
}
CamundaBpmVersion(final Package pkg) {
this.version = Optional.ofNullable(pkg.getImplementationVersion())
.map(String::trim)
.orElse("");
|
this.isEnterprise = version.endsWith("-ee");
this.formattedVersion = String.format(VERSION_FORMAT, version);
}
@Override
public String get() {
return version;
}
public boolean isEnterprise() {
return isEnterprise;
}
public PropertiesPropertySource getPropertiesPropertySource() {
final Properties props = new Properties();
props.put(key(VERSION), version);
props.put(key(IS_ENTERPRISE), isEnterprise);
props.put(key(FORMATTED_VERSION), formattedVersion);
return new PropertiesPropertySource(this.getClass().getSimpleName(), props);
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\CamundaBpmVersion.java
| 1
|
请完成以下Java代码
|
public class PvmAtomicOperationActivityExecute implements PvmAtomicOperation {
private final static PvmLogger LOG = PvmLogger.PVM_LOGGER;
public boolean isAsync(PvmExecutionImpl execution) {
return false;
}
public void execute(PvmExecutionImpl execution) {
execution.activityInstanceStarted();
execution.continueIfExecutionDoesNotAffectNextOperation(new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
if (execution.getActivity().isScope()) {
execution.dispatchEvent(null);
}
return null;
}
}, new Callback<PvmExecutionImpl, Void>() {
@Override
public Void callback(PvmExecutionImpl execution) {
ActivityBehavior activityBehavior = getActivityBehavior(execution);
|
ActivityImpl activity = execution.getActivity();
LOG.debugExecutesActivity(execution, activity, activityBehavior.getClass().getName());
try {
activityBehavior.execute(execution);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PvmException("couldn't execute activity <" + activity.getProperty("type") + " id=\"" + activity.getId() + "\" ...>: " + e.getMessage(), e);
}
return null;
}
}, execution);
}
public String getCanonicalName() {
return "activity-execute";
}
public boolean isAsyncCapable() {
return false;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityExecute.java
| 1
|
请完成以下Java代码
|
public Boolean isFmlyMdclInsrncInd() {
return fmlyMdclInsrncInd;
}
/**
* Sets the value of the fmlyMdclInsrncInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFmlyMdclInsrncInd(Boolean value) {
this.fmlyMdclInsrncInd = value;
}
/**
* Gets the value of the mplyeeTermntnInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isMplyeeTermntnInd() {
|
return mplyeeTermntnInd;
}
/**
* Sets the value of the mplyeeTermntnInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setMplyeeTermntnInd(Boolean value) {
this.mplyeeTermntnInd = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\Garnishment1.java
| 1
|
请完成以下Java代码
|
protected ExecutionEntity fetchExecutionEntity(String executionId) {
return Context.getCommandContext()
.getExecutionManager()
.findExecutionById(executionId);
}
public FailedJobRetryConfiguration getFailedJobRetryConfiguration(JobEntity job, ActivityImpl activity) {
FailedJobRetryConfiguration retryConfiguration = activity.getProperties().get(DefaultFailedJobParseListener.FAILED_JOB_CONFIGURATION);
while (retryConfiguration != null && retryConfiguration.getExpression() != null) {
String retryIntervals = getFailedJobRetryTimeCycle(job, retryConfiguration.getExpression());
retryConfiguration = ParseUtil.parseRetryIntervals(retryIntervals);
}
return retryConfiguration;
}
protected String getFailedJobRetryTimeCycle(JobEntity job, Expression expression) {
String executionId = job.getExecutionId();
ExecutionEntity execution = null;
if (executionId != null) {
execution = fetchExecutionEntity(executionId);
}
Object value = null;
if (expression == null) {
return null;
}
try {
value = expression.getValue(execution, execution);
}
catch (Exception e) {
LOG.exceptionWhileParsingExpression(jobId, e.getCause().getMessage());
}
if (value instanceof String) {
return (String) value;
}
else
|
{
// default behavior
return null;
}
}
protected DurationHelper getDurationHelper(String failedJobRetryTimeCycle) throws Exception {
return new DurationHelper(failedJobRetryTimeCycle);
}
protected boolean isFirstJobExecution(JobEntity job) {
// check if this is jobs' first execution (recognize
// this because no exception is set. Only the first
// execution can be without exception - because if
// no exception occurred the job would have been completed)
// see https://app.camunda.com/jira/browse/CAM-1039
return job.getExceptionByteArrayId() == null && job.getExceptionMessage() == null;
}
protected void initializeRetries(JobEntity job, int retries) {
LOG.debugInitiallyAppyingRetryCycleForJob(job.getId(), retries);
job.setRetries(retries);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DefaultJobRetryCmd.java
| 1
|
请完成以下Java代码
|
private static class TypedConsumerAsEventListener<T> implements IEventListener
{
@NonNull
private final Consumer<T> eventConsumer;
@NonNull
private final JSONObjectMapper<T> jsonDeserializer;
@NonNull
private final Class<T> eventBodyType;
public TypedConsumerAsEventListener(
@NonNull final Class<T> eventBodyType,
@NonNull final Consumer<T> eventConsumer)
{
this.eventBodyType = eventBodyType;
this.jsonDeserializer = JSONObjectMapper.forClass(eventBodyType);
this.eventConsumer = eventConsumer;
}
@Override
public void onEvent(final IEventBus eventBus, final Event event)
{
try (final MDCCloseable ignored = EventMDC.putEvent(event))
{
logger.debug("TypedConsumerAsEventListener.onEvent - eventBodyType={}", eventBodyType.getName());
final String json = event.getBody();
final T obj = jsonDeserializer.readValue(json);
eventConsumer.accept(obj);
}
}
}
@AllArgsConstructor
@ToString
private class GuavaEventListenerAdapter
{
@NonNull
private final IEventListener eventListener;
@Subscribe
public void onEvent(@NonNull final Event event)
{
micrometerEventBusStatsCollector.incrementEventsDequeued();
micrometerEventBusStatsCollector
.getEventProcessingTimer()
.record(() ->
{
try (final MDCCloseable ignored = EventMDC.putEvent(event))
{
logger.debug("GuavaEventListenerAdapter.onEvent - eventListener to invoke={}", eventListener);
invokeEventListener(this.eventListener, event);
}
});
}
}
private void invokeEventListener(
@NonNull final IEventListener eventListener,
@NonNull final Event event)
{
if (event.isWasLogged())
{
invokeEventListenerWithLogging(eventListener, event);
|
}
else
{
eventListener.onEvent(this, event);
}
}
private void invokeEventListenerWithLogging(
@NonNull final IEventListener eventListener,
@NonNull final Event event)
{
try (final EventLogEntryCollector ignored = EventLogEntryCollector.createThreadLocalForEvent(event))
{
try
{
eventListener.onEvent(this, event);
}
catch (final RuntimeException ex)
{
if (!Adempiere.isUnitTestMode())
{
final EventLogUserService eventLogUserService = SpringContextHolder.instance.getBean(EventLogUserService.class);
eventLogUserService
.newErrorLogEntry(eventListener.getClass(), ex)
.createAndStore();
}
else
{
logger.warn("Got exception while invoking eventListener={} with event={}", eventListener, event, ex);
}
}
}
}
@Override
public EventBusStats getStats()
{
return micrometerEventBusStatsCollector.snapshot();
}
private void enqueueEvent0(final Event event)
{
if (Type.LOCAL == topic.getType())
{
eventEnqueuer.enqueueLocalEvent(event, topic);
}
else
{
eventEnqueuer.enqueueDistributedEvent(event, topic);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBus.java
| 1
|
请完成以下Java代码
|
public void setLabelFor (Component c)
{
//reset old if any
if (getLabelFor() != null && getLabelFor() instanceof JTextComponent)
{
((JTextComponent)getLabelFor()).setFocusAccelerator('\0');
}
super.setLabelFor(c);
if (c.getName() == null)
c.setName(getName());
//workaround for focus accelerator issue
if (c instanceof JTextComponent)
{
if (m_savedMnemonic > 0)
{
((JTextComponent)c).setFocusAccelerator(m_savedMnemonic);
}
}
} // setLabelFor
/**
* @return Returns the savedMnemonic.
|
*/
public char getSavedMnemonic ()
{
return m_savedMnemonic;
} // getSavedMnemonic
/**
* @param savedMnemonic The savedMnemonic to set.
*/
public void setSavedMnemonic (char savedMnemonic)
{
m_savedMnemonic = savedMnemonic;
} // getSavedMnemonic
} // CLabel
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CLabel.java
| 1
|
请完成以下Java代码
|
static class HousekeeperStats {
private final HousekeeperTaskType taskType;
private final List<StatsCounter> counters = new ArrayList<>();
private final StatsCounter processedCounter;
private final StatsCounter failedProcessingCounter;
private final StatsCounter reprocessedCounter;
private final StatsCounter failedReprocessingCounter;
private final StatsTimer processingTimer;
public HousekeeperStats(HousekeeperTaskType taskType, StatsFactory statsFactory) {
this.taskType = taskType;
this.processedCounter = register("processed", statsFactory);
this.failedProcessingCounter = register("failedProcessing", statsFactory);
this.reprocessedCounter = register("reprocessed", statsFactory);
this.failedReprocessingCounter = register("failedReprocessing", statsFactory);
this.processingTimer = statsFactory.createStatsTimer(StatsType.HOUSEKEEPER.getName(), "processingTime", "taskType", taskType.name());
}
|
private StatsCounter register(String statsName, StatsFactory statsFactory) {
StatsCounter counter = statsFactory.createStatsCounter(StatsType.HOUSEKEEPER.getName(), statsName, "taskType", taskType.name());
counters.add(counter);
return counter;
}
public void reset() {
counters.forEach(DefaultCounter::clear);
processingTimer.reset();
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\housekeeper\stats\HousekeeperStatsService.java
| 1
|
请完成以下Java代码
|
public void addBook(Book book) {
this.books.add(book);
book.setPublisher(this);
}
public void removeBook(Book book) {
book.setPublisher(null);
this.books.remove(book);
}
public void removeBooks() {
Iterator<Book> iterator = this.books.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
book.setPublisher(null);
iterator.remove();
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
|
this.company = company;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Publisher{" + "id=" + id + ", company=" + company + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedSubgraph\src\main\java\com\bookstore\entity\Publisher.java
| 1
|
请完成以下Java代码
|
public class AccountId implements Serializable {
private static final long serialVersionUID = 1L;
private String accountNumber;
private String accountType;
public AccountId() {
}
public AccountId(String accountNumber, String accountType) {
this.accountNumber = accountNumber;
this.accountType = accountType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode());
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
return result;
}
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccountId other = (AccountId) obj;
if (accountNumber == null) {
if (other.accountNumber != null)
return false;
} else if (!accountNumber.equals(other.accountNumber))
return false;
if (accountType == null) {
if (other.accountType != null)
return false;
} else if (!accountType.equals(other.accountType))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\primarykeys\AccountId.java
| 1
|
请完成以下Java代码
|
public class NoXssValidator implements ConstraintValidator<NoXss, Object> {
private static final Pattern JS_TEMPLATE_PATTERN = Pattern.compile("\\{\\{.*}}", Pattern.DOTALL);
private static final AntiSamy xssChecker = new AntiSamy();
private static final Policy xssPolicy;
static {
xssPolicy = Optional.ofNullable(NoXssValidator.class.getClassLoader().getResourceAsStream("xss-policy.xml"))
.map(inputStream -> {
try {
return Policy.getInstance(inputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.orElseThrow(() -> new IllegalStateException("XSS policy file not found"));
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
String stringValue;
if (value instanceof CharSequence || value instanceof JsonNode) {
stringValue = value.toString();
} else {
return true;
}
return isValid(stringValue);
|
}
public static boolean isValid(String stringValue) {
if (stringValue.isEmpty()) {
return true;
}
if (JS_TEMPLATE_PATTERN.matcher(stringValue).find()) {
return false;
}
try {
return xssChecker.scan(stringValue, xssPolicy).getNumberOfErrors() == 0;
} catch (ScanException | PolicyException e) {
return false;
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\NoXssValidator.java
| 1
|
请完成以下Java代码
|
public void setIsPluFileExportAuditEnabled (final boolean IsPluFileExportAuditEnabled)
{
set_Value (COLUMNNAME_IsPluFileExportAuditEnabled, IsPluFileExportAuditEnabled);
}
@Override
public boolean isPluFileExportAuditEnabled()
{
return get_ValueAsBoolean(COLUMNNAME_IsPluFileExportAuditEnabled);
}
/**
* PluFileDestination AD_Reference_ID=541911
* Reference name: PluFileDestination
*/
public static final int PLUFILEDESTINATION_AD_Reference_ID=541911;
/** Disk = 2DSK */
public static final String PLUFILEDESTINATION_Disk = "2DSK";
/** TCP = 1TCP */
public static final String PLUFILEDESTINATION_TCP = "1TCP";
@Override
public void setPluFileDestination (final java.lang.String PluFileDestination)
{
set_Value (COLUMNNAME_PluFileDestination, PluFileDestination);
}
@Override
public java.lang.String getPluFileDestination()
{
return get_ValueAsString(COLUMNNAME_PluFileDestination);
}
@Override
public void setPluFileLocalFolder (final @Nullable java.lang.String PluFileLocalFolder)
{
set_Value (COLUMNNAME_PluFileLocalFolder, PluFileLocalFolder);
}
@Override
public java.lang.String getPluFileLocalFolder()
{
return get_ValueAsString(COLUMNNAME_PluFileLocalFolder);
}
@Override
public void setProduct_BaseFolderName (final String Product_BaseFolderName)
{
set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName);
}
@Override
public String getProduct_BaseFolderName()
{
|
return get_ValueAsString(COLUMNNAME_Product_BaseFolderName);
}
@Override
public void setTCP_Host (final String TCP_Host)
{
set_Value (COLUMNNAME_TCP_Host, TCP_Host);
}
@Override
public String getTCP_Host()
{
return get_ValueAsString(COLUMNNAME_TCP_Host);
}
@Override
public void setTCP_PortNumber (final int TCP_PortNumber)
{
set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber);
}
@Override
public int getTCP_PortNumber()
{
return get_ValueAsInt(COLUMNNAME_TCP_PortNumber);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//此处可以修改为您的表前缀
strategy.setTablePrefix(new String[] { "tb_"});
|
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 需要生成的表
strategy.setInclude(new String[] { "tb_employee" });
// 排除生成的表
//strategy.setExclude(new String[]{"test"});
strategy.setEntityLombokModel( true );
mpg.setStrategy(strategy);
// 执行生成
mpg.execute();
}
}
|
repos\SpringBootLearning-master (1)\springboot-cache\src\main\java\com\gf\config\CodeGenerator.java
| 2
|
请完成以下Java代码
|
class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
void insert(String word) {
TrieNode current = root;
for (char l : word.toCharArray()) {
current = current.getChildren().computeIfAbsent(l, c -> new TrieNode());
}
current.setEndOfWord(true);
}
boolean delete(String word) {
return delete(root, word, 0);
}
boolean containsNode(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.getChildren().get(ch);
if (node == null) {
return false;
}
current = node;
}
return current.isEndOfWord();
}
boolean isEmpty() {
return root == null;
}
private boolean delete(TrieNode current, String word, int index) {
if (index == word.length()) {
|
if (!current.isEndOfWord()) {
return false;
}
current.setEndOfWord(false);
return current.getChildren().isEmpty();
}
char ch = word.charAt(index);
TrieNode node = current.getChildren().get(ch);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord();
if (shouldDeleteCurrentNode) {
current.getChildren().remove(ch);
return current.getChildren().isEmpty();
}
return false;
}
}
|
repos\tutorials-master\data-structures\src\main\java\com\baeldung\trie\Trie.java
| 1
|
请完成以下Java代码
|
private Banner getBanner(Environment environment) {
Banner textBanner = getTextBanner(environment);
if (textBanner != null) {
return textBanner;
}
if (this.fallbackBanner != null) {
return this.fallbackBanner;
}
return DEFAULT_BANNER;
}
private @Nullable Banner getTextBanner(Environment environment) {
String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION);
Resource resource = this.resourceLoader.getResource(location);
try {
if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) {
return new ResourceBanner(resource);
}
}
catch (IOException ex) {
// Ignore
}
return null;
}
private String createStringFromBanner(Banner banner, Environment environment,
@Nullable Class<?> mainApplicationClass) throws UnsupportedEncodingException {
String charset = environment.getProperty("spring.banner.charset", StandardCharsets.UTF_8.name());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(byteArrayOutputStream, false, charset)) {
banner.printBanner(environment, mainApplicationClass, out);
}
return byteArrayOutputStream.toString(charset);
}
/**
|
* Decorator that allows a {@link Banner} to be printed again without needing to
* specify the source class.
*/
private static class PrintedBanner implements Banner {
private final Banner banner;
private final @Nullable Class<?> sourceClass;
PrintedBanner(Banner banner, @Nullable Class<?> sourceClass) {
this.banner = banner;
this.sourceClass = sourceClass;
}
@Override
public void printBanner(Environment environment, @Nullable Class<?> sourceClass, PrintStream out) {
sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass;
this.banner.printBanner(environment, sourceClass, out);
}
}
static class SpringApplicationBannerPrinterRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern(DEFAULT_BANNER_LOCATION);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationBannerPrinter.java
| 1
|
请完成以下Java代码
|
public class DB_PostgreSQL_ConnectionCustomizer extends AbstractConnectionCustomizer
{
private static final String CLIENTINFO_ApplicationName = "ApplicationName";
private static final Logger log = LogManager.getLogger(DB_PostgreSQL_ConnectionCustomizer.class);
/**
* When a new connection is acquired from the underlying postgres JDBC driver, this method sets the connections log limit to "WARNING".
* That way, only warning messages (and above) will be send to
* the client to prevent an OutOfMemoryError due to too many messages being send from verbose and long-running DB functions.
* <p>
* Added for task 04006.
*/
@Override
public void onAcquire(final Connection c, final String parentDataSourceIdentityToken) throws Exception
{
log.debug("Attempting to set client_min_messages=WARNING for pooled connection: {} ", c);
c.prepareStatement("SET client_min_messages=WARNING").execute();
c.setClientInfo(CLIENTINFO_ApplicationName, "metasfresh");
}
@Override
|
public void onCheckIn(final Connection c, final String parentDataSourceIdentityToken) throws Exception
{
// NOTE: it's much more efficient to reset the ApplicationName here because this method is called in another thread
c.setClientInfo(CLIENTINFO_ApplicationName, "metasfresh/returned-to-pool"); // task 08353
}
@Override
public void onCheckOut(final Connection c, final String parentDataSourceIdentityToken) throws Exception
{
// NOTE: it's much more efficient to reset the ApplicationName here because this method is called in another thread
c.setClientInfo(CLIENTINFO_ApplicationName, "metasfresh/checked-out-from-pool"); // task 08353
final IConnectionCustomizerService connectionCustomizerService = Services.get(IConnectionCustomizerService.class);
connectionCustomizerService.fireRegisteredCustomizers(c);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\connection\impl\DB_PostgreSQL_ConnectionCustomizer.java
| 1
|
请完成以下Java代码
|
public static void writeValue_POBox(final I_C_Location toLocationRecord, final IDocumentFieldView fromField)
{
toLocationRecord.setPOBox(fromField.getValueAs(String.class));
}
public static void writeValue_C_City_ID(final I_C_Location toLocationRecord, final IDocumentFieldView fromField)
{
final IntegerLookupValue city = fromField.getValueAs(IntegerLookupValue.class);
if (city == null)
{
toLocationRecord.setC_City_ID(-1);
}
else if (city.getIdAsInt() <= 0)
{
toLocationRecord.setC_City_ID(-1);
toLocationRecord.setCity(city.getDisplayName());
}
else
{
toLocationRecord.setC_City_ID(city.getIdAsInt());
toLocationRecord.setCity(city.getDisplayName());
}
}
public static void writeValue_C_Region_ID(final I_C_Location toLocationRecord, final IDocumentFieldView fromField)
{
final IntegerLookupValue region = fromField.getValueAs(IntegerLookupValue.class);
if (region == null)
{
toLocationRecord.setC_Region_ID(-1);
}
else if (region.getIdAsInt() <= 0)
{
toLocationRecord.setC_Region_ID(-1);
toLocationRecord.setRegionName(region.getDisplayName());
}
else
{
toLocationRecord.setC_Region_ID(region.getIdAsInt());
toLocationRecord.setRegionName(region.getDisplayName());
}
}
public static void writeValue_C_Country_ID(final I_C_Location toLocationRecord, final IDocumentFieldView fromField)
{
final IntegerLookupValue country = fromField.getValueAs(IntegerLookupValue.class);
if (country == null)
{
toLocationRecord.setC_Country_ID(-1);
}
else if (country.getIdAsInt() <= 0)
{
toLocationRecord.setC_Country_ID(-1);
|
}
else
{
toLocationRecord.setC_Country_ID(country.getIdAsInt());
}
}
private static void writeValue_C_Postal_ID(final I_C_Location toLocationRecord, final IDocumentFieldView fromField)
{
final IntegerLookupValue postalLookupValue = fromField.getValueAs(IntegerLookupValue.class);
final int postalId = postalLookupValue != null ? postalLookupValue.getIdAsInt() : -1;
if (postalId <= 0)
{
toLocationRecord.setC_Postal_ID(-1);
toLocationRecord.setPostal(null);
toLocationRecord.setCity(null);
toLocationRecord.setC_City_ID(-1);
}
else
{
final I_C_Postal postalRecord = InterfaceWrapperHelper.load(postalId, I_C_Postal.class);
toLocationRecord.setC_Postal_ID(postalRecord.getC_Postal_ID());
toLocationRecord.setPostal(postalRecord.getPostal());
toLocationRecord.setPostal_Add(postalRecord.getPostal_Add());
toLocationRecord.setC_City_ID(postalRecord.getC_City_ID());
toLocationRecord.setCity(postalRecord.getCity());
toLocationRecord.setC_Country_ID(postalRecord.getC_Country_ID());
toLocationRecord.setC_Region_ID(postalRecord.getC_Region_ID());
toLocationRecord.setRegionName(postalRecord.getRegionName());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressDescriptorFactory.java
| 1
|
请完成以下Java代码
|
public class ExecuteFutureActionOperation<T> implements Runnable {
protected final CompletableFuture<T> future;
protected final BiConsumer<T, Throwable> action;
public ExecuteFutureActionOperation(CompletableFuture<T> future, BiConsumer<T, Throwable> action) {
this.future = future;
this.action = action;
}
@Override
public void run() {
try {
T value = future.get();
action.accept(value, null);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new FlowableException("Future was interrupted", e);
} catch (CancellationException e) {
action.accept(null, new FlowableException("Future was canceled", e));
} catch (ExecutionException e) {
|
action.accept(null, e.getCause());
}
}
public boolean isDone() {
return future.isDone();
}
public CompletableFuture<T> getFuture() {
return future;
}
public BiConsumer<T, Throwable> getAction() {
return action;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\agenda\ExecuteFutureActionOperation.java
| 1
|
请完成以下Java代码
|
protected final boolean isCalloutActive()
{
final ICalloutExecutor currentCalloutExecutor = this.currentCalloutExecutorHolder.get();
if (currentCalloutExecutor == null)
{
return false;
}
final int activeCalloutsCount = currentCalloutExecutor.getActiveCalloutInstancesCount();
// greater than 1 instead of 0 to discount this callout instance
if (activeCalloutsCount <= 1)
{
return false;
}
return true;
} // isCalloutActive
/**
* Set Account Date Value.
* org.compiere.model.CalloutEngine.dateAcct
*
* @return null or error message
*/
public String dateAcct(final ICalloutField field)
{
if (isCalloutActive())
{
return NO_ERROR;
}
final Object value = field.getValue();
if (!(value instanceof java.util.Date)/*this also covers value=null*/)
{
return NO_ERROR;
}
final java.util.Date valueDate = (java.util.Date)value;
final Object model = field.getModel(Object.class);
InterfaceWrapperHelper.setValue(model, "DateAcct", TimeUtil.asTimestamp(valueDate));
return NO_ERROR;
|
} // dateAcct
/**
* Rate - set Multiply Rate from Divide Rate and vice versa
* org.compiere.model.CalloutEngine.rate
*
* @return null or error message
*/
@Deprecated
public String rate(final ICalloutField field)
{
// NOTE: atm this method is used only by UOMConversions. When we will provide an implementation for that, we can get rid of this shit.
final Object value = field.getValue();
if (isCalloutActive() || value == null)
{
return NO_ERROR;
}
final BigDecimal rate1 = (BigDecimal)value;
BigDecimal rate2 = BigDecimal.ZERO;
final BigDecimal one = BigDecimal.ONE;
if (rate1.signum() != 0)
{
rate2 = one.divide(rate1, 12, BigDecimal.ROUND_HALF_UP);
}
//
final String columnName = field.getColumnName();
final Object model = field.getModel(Object.class);
if ("MultiplyRate".equals(columnName))
{
InterfaceWrapperHelper.setValue(model, "DivideRate", rate2);
}
else
{
InterfaceWrapperHelper.setValue(model, "MultiplyRate", rate2);
}
log.info("columnName={}; value={} => result={}", columnName, rate1, rate2);
return NO_ERROR;
} // rate
} // CalloutEngine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\CalloutEngine.java
| 1
|
请完成以下Java代码
|
public void close(final I_PP_Order_BOMLine line)
{
changeQuantities(line, OrderBOMLineQuantities::close);
line.setProcessed(true); // just to make sure (but it should be already set when the PP_Order was completed)
orderBOMsRepo.save(line);
}
@Override
public void unclose(final I_PP_Order_BOMLine line)
{
changeQuantities(line, OrderBOMLineQuantities::unclose);
orderBOMsRepo.save(line);
}
@Override
public boolean isSomethingReported(@NonNull final I_PP_Order ppOrder)
{
if (getQuantities(ppOrder).isSomethingReported())
{
return true;
}
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
return orderBOMsRepo.retrieveOrderBOMLines(ppOrderId)
.stream()
.map(this::getQuantities)
.anyMatch(OrderBOMLineQuantities::isSomethingReported);
}
@Override
public Optional<DocSequenceId> getSerialNoSequenceId(@NonNull final PPOrderId ppOrderId)
{
final I_PP_Order_BOM orderBOM = orderBOMsRepo.getByOrderIdOrNull(ppOrderId);
if (orderBOM == null)
{
throw new AdempiereException("@NotFound@ @PP_Order_BOM_ID@: " + ppOrderId);
}
return DocSequenceId.optionalOfRepoId(orderBOM.getSerialNo_Sequence_ID());
}
@Override
public QtyCalculationsBOM getQtyCalculationsBOM(@NonNull final I_PP_Order order)
{
final ImmutableList<QtyCalculationsBOMLine> lines = orderBOMsRepo.retrieveOrderBOMLines(order)
.stream()
.map(orderBOMLineRecord -> toQtyCalculationsBOMLine(order, orderBOMLineRecord))
|
.collect(ImmutableList.toImmutableList());
return QtyCalculationsBOM.builder()
.lines(lines)
.orderId(PPOrderId.ofRepoIdOrNull(order.getPP_Order_ID()))
.build();
}
@Override
public void save(final I_PP_Order_BOMLine orderBOMLine)
{
orderBOMsRepo.save(orderBOMLine);
}
@Override
public Set<ProductId> getProductIdsToIssue(final PPOrderId ppOrderId)
{
return getOrderBOMLines(ppOrderId, I_PP_Order_BOMLine.class)
.stream()
.filter(bomLine -> BOMComponentType.ofNullableCodeOrComponent(bomLine.getComponentType()).isIssue())
.map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID()))
.collect(ImmutableSet.toImmutableSet());
}
@Override
public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(@NonNull final I_PP_Order ppOrder)
{
final WarehouseId warehouseId = WarehouseId.ofRepoId(ppOrder.getM_Warehouse_ID());
return getIssueFromWarehouseIds(warehouseId);
}
@Override
public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(final WarehouseId ppOrderWarehouseId)
{
return warehouseDAO.getWarehouseIdsOfSameGroup(ppOrderWarehouseId, WarehouseGroupAssignmentType.MANUFACTURING);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMBL.java
| 1
|
请完成以下Java代码
|
public static void exceptionHandlingCompare() {
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
// Task that may throw an exception
throw new RuntimeException("Exception occurred in asynchronous task");
});
try {
runAsyncFuture.get();
// Exception will be thrown here
} catch (ExecutionException ex) {
Throwable cause = ex.getCause();
System.out.println("Exception caught: " + cause.getMessage());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
CompletableFuture<Object> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
// Task that may throw an exception
throw new RuntimeException("Exception occurred in asynchronous task");
})
.exceptionally(ex -> {
// Exception handling logic
return "Default value";
});
Object result = supplyAsyncFuture.join();
// Get the result or default value
System.out.println("Result: " + result);
}
|
public static void chainingOperationCompare() {
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
// Perform non-result producing task
System.out.println("Task executed asynchronously");
});
runAsyncFuture.thenRun(() -> {
// Execute another task after the completion of runAsync()
System.out.println("Another task executed after runAsync() completes");
});
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
// Perform result-producing task
return "Result of the asynchronous computation";
});
supplyAsyncFuture.thenApply(result -> {
// Transform the result
return result.toUpperCase();
})
.thenAccept(transformedResult -> {
// Consume the transformed result
System.out.println("Transformed Result: " + transformedResult);
});
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-2\src\main\java\com\baeldung\runvssupply\RunAndSupplyCompare.java
| 1
|
请完成以下Java代码
|
protected ProcessEngine getProcessEngineForArchive(ServiceName serviceName, ServiceRegistry serviceRegistry) {
ServiceController<ProcessEngine> processEngineServiceController = (ServiceController<ProcessEngine>) serviceRegistry.getRequiredService(serviceName);
return processEngineServiceController.getValue();
}
protected ServiceName getProcessEngineServiceName(ProcessArchiveXml processArchive) {
ServiceName serviceName = null;
if(processArchive.getProcessEngineName() == null || processArchive.getProcessEngineName().length() == 0) {
serviceName = ServiceNames.forDefaultProcessEngine();
} else {
serviceName = ServiceNames.forManagedProcessEngine(processArchive.getProcessEngineName());
}
return serviceName;
}
protected Map<String, byte[]> getDeploymentResources(ProcessArchiveXml processArchive, DeploymentUnit deploymentUnit, VirtualFile processesXmlFile) {
final Module module = deploymentUnit.getAttachment(MODULE);
Map<String, byte[]> resources = new HashMap<String, byte[]>();
// first, add all resources listed in the processe.xml
List<String> process = processArchive.getProcessResourceNames();
ModuleClassLoader classLoader = module.getClassLoader();
for (String resource : process) {
InputStream inputStream = null;
try {
inputStream = classLoader.getResourceAsStream(resource);
resources.put(resource, IoUtil.readInputStream(inputStream, resource));
|
} finally {
IoUtil.closeSilently(inputStream);
}
}
// scan for process definitions
if(PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, process.isEmpty())) {
//always use VFS scanner on JBoss
final VfsProcessApplicationScanner scanner = new VfsProcessApplicationScanner();
String resourceRootPath = processArchive.getProperties().get(ProcessArchiveXml.PROP_RESOURCE_ROOT_PATH);
String[] additionalResourceSuffixes = StringUtil.split(processArchive.getProperties().get(ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES), ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR);
URL processesXmlUrl = vfsFileAsUrl(processesXmlFile);
resources.putAll(scanner.findResources(classLoader, resourceRootPath, processesXmlUrl, additionalResourceSuffixes));
}
return resources;
}
protected URL vfsFileAsUrl(VirtualFile processesXmlFile) {
try {
return processesXmlFile.toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessApplicationDeploymentProcessor.java
| 1
|
请完成以下Java代码
|
public void onStartup(ServletContext servletContext) throws ServletException {
if (this.session.getTrackingModes() != null) {
servletContext.setSessionTrackingModes(unwrap(this.session.getTrackingModes()));
}
configureSessionCookie(servletContext.getSessionCookieConfig());
}
private void configureSessionCookie(SessionCookieConfig config) {
Cookie cookie = this.session.getCookie();
PropertyMapper map = PropertyMapper.get();
map.from(cookie::getName).to(config::setName);
map.from(cookie::getDomain).to(config::setDomain);
map.from(cookie::getPath).to(config::setPath);
map.from(cookie::getHttpOnly).to(config::setHttpOnly);
map.from(cookie::getSecure).to(config::setSecure);
map.from(cookie::getMaxAge).asInt(Duration::getSeconds).to(config::setMaxAge);
map.from(cookie::getPartitioned)
.as(Object::toString)
|
.to((partitioned) -> config.setAttribute("Partitioned", partitioned));
}
@Contract("!null -> !null")
private @Nullable Set<jakarta.servlet.SessionTrackingMode> unwrap(
@Nullable Set<Session.SessionTrackingMode> modes) {
if (modes == null) {
return null;
}
Set<jakarta.servlet.SessionTrackingMode> result = new LinkedHashSet<>();
for (Session.SessionTrackingMode mode : modes) {
result.add(jakarta.servlet.SessionTrackingMode.valueOf(mode.name()));
}
return result;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletContextInitializers.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public TaskRecord getTaskById(String id) {
return tasksRepository.findById(id)
.orElseThrow(() -> new UnknownTaskException(id));
}
@Transactional
public void deleteTaskById(String id) {
var task = tasksRepository.findById(id)
.orElseThrow(() -> new UnknownTaskException(id));
tasksRepository.delete(task);
}
public List<TaskRecord> search(Optional<String> createdBy, Optional<String> status) {
if (createdBy.isPresent() && status.isPresent()) {
return tasksRepository.findByStatusAndCreatedBy(status.get(), createdBy.get());
} else if (createdBy.isPresent()) {
return tasksRepository.findByCreatedBy(createdBy.get());
} else if (status.isPresent()) {
return tasksRepository.findByStatus(status.get());
} else {
return tasksRepository.findAll();
|
}
}
@Transactional
public TaskRecord updateTask(String id, Optional<String> newStatus, Optional<String> newAssignedTo) {
var task = tasksRepository.findById(id)
.orElseThrow(() -> new UnknownTaskException(id));
newStatus.ifPresent(task::setStatus);
newAssignedTo.ifPresent(task::setAssignedTo);
return task;
}
public TaskRecord createTask(String title, String createdBy) {
var task = new TaskRecord(UUID.randomUUID()
.toString(), title, Instant.now(), createdBy, null, "PENDING");
tasksRepository.save(task);
return task;
}
}
|
repos\tutorials-master\lightrun\lightrun-tasks-service\src\main\java\com\baeldung\tasksservice\service\TasksService.java
| 2
|
请完成以下Java代码
|
public class QuickInputConstants
{
private static final String SYSCONFIG_EnablePackingInstructionsField = "webui.quickinput.EnablePackingInstructionsField";
private static final String SYSCONFIG_EnableLUFields = "webui.quickinput.EnableLUFields";
private static final String SYSCONFIG_EnableBestBeforePolicy = "webui.quickinput.EnableBestBeforePolicy";
private static final String SYSCONFIG_EnableVatCodeField = "webui.quickinput.EnableVatCodeField";
private static final String SYSCONFIG_EnableContractConditionsField = "webui.quickinput.EnableContractConditionsField";
private static final String SYSCONFIG_IsContractConditionsFieldMandatory = "webui.quickinput.IsContractConditionsFieldMandatory";
/**
* Created for https://github.com/metasfresh/metasfresh/issues/14009 where we want batch entry dropdown to contain "ALL" potential matches,
* not just the first 10 (see de.metas.ui.web.window.model.lookup.LookupDataSource#DEFAULT_PageLength).
* Because "ALL" is a recipe for OOMs and stalled requests, we're using this constant instead as pageLength.
*/
public static final Integer BIG_ENOUGH_PAGE_LENGTH = 200;
public static boolean isEnablePackingInstructionsField()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnablePackingInstructionsField, true);
}
public static boolean isLUFieldsEnabled(@NonNull final SOTrx soTrx)
{
return soTrx.isPurchase() && Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableLUFields, false);
}
public static boolean isEnableBestBeforePolicy()
{
|
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableBestBeforePolicy, true);
}
public static boolean isEnableVatCodeField()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableVatCodeField, false);
}
public static boolean isEnableContractConditionsField()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_EnableContractConditionsField, false);
}
public static boolean isContractConditionsFieldMandatory()
{
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_IsContractConditionsFieldMandatory, false);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputConstants.java
| 1
|
请完成以下Java代码
|
protected void addSignalEventSubscriptions(
CommandContext commandContext,
ProcessDefinitionEntity processDefinition,
Process process,
BpmnModel bpmnModel
) {
if (process != null && CollectionUtil.isNotEmpty(process.getFlowElements())) {
for (FlowElement element : process.getFlowElements()) {
if (element instanceof StartEvent) {
StartEvent startEvent = (StartEvent) element;
if (CollectionUtil.isNotEmpty(startEvent.getEventDefinitions())) {
EventDefinition eventDefinition = startEvent.getEventDefinitions().get(0);
if (eventDefinition instanceof SignalEventDefinition) {
SignalEventDefinition signalEventDefinition = (SignalEventDefinition) eventDefinition;
SignalEventSubscriptionEntity subscriptionEntity = commandContext
.getEventSubscriptionEntityManager()
.createSignalEventSubscription();
Signal signal = bpmnModel.getSignal(signalEventDefinition.getSignalRef());
if (signal != null) {
subscriptionEntity.setEventName(signal.getName());
} else {
subscriptionEntity.setEventName(signalEventDefinition.getSignalRef());
|
}
subscriptionEntity.setActivityId(startEvent.getId());
subscriptionEntity.setProcessDefinitionId(processDefinition.getId());
if (processDefinition.getTenantId() != null) {
subscriptionEntity.setTenantId(processDefinition.getTenantId());
}
Context.getCommandContext().getEventSubscriptionEntityManager().insert(subscriptionEntity);
}
}
}
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\EventSubscriptionManager.java
| 1
|
请完成以下Java代码
|
public void setSwiftCode (final @Nullable java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
@Override
public java.lang.String getSwiftCode()
{
return get_ValueAsString(COLUMNNAME_SwiftCode);
}
@Override
public void setTaxID (final @Nullable java.lang.String TaxID)
{
set_Value (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
@Override
|
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
@Override
public void setURL3 (final @Nullable java.lang.String URL3)
{
set_Value (COLUMNNAME_URL3, URL3);
}
@Override
public java.lang.String getURL3()
{
return get_ValueAsString(COLUMNNAME_URL3);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner.java
| 1
|
请完成以下Java代码
|
public String getWebParam1 ()
{
return (String)get_Value(COLUMNNAME_WebParam1);
}
/** Set Web Parameter 2.
@param WebParam2
Web Site Parameter 2 (default index page)
*/
public void setWebParam2 (String WebParam2)
{
set_Value (COLUMNNAME_WebParam2, WebParam2);
}
/** Get Web Parameter 2.
@return Web Site Parameter 2 (default index page)
*/
public String getWebParam2 ()
{
return (String)get_Value(COLUMNNAME_WebParam2);
}
/** Set Web Parameter 3.
@param WebParam3
Web Site Parameter 3 (default left - menu)
*/
public void setWebParam3 (String WebParam3)
{
set_Value (COLUMNNAME_WebParam3, WebParam3);
}
/** Get Web Parameter 3.
@return Web Site Parameter 3 (default left - menu)
*/
public String getWebParam3 ()
{
|
return (String)get_Value(COLUMNNAME_WebParam3);
}
/** Set Web Parameter 4.
@param WebParam4
Web Site Parameter 4 (default footer left)
*/
public void setWebParam4 (String WebParam4)
{
set_Value (COLUMNNAME_WebParam4, WebParam4);
}
/** Get Web Parameter 4.
@return Web Site Parameter 4 (default footer left)
*/
public String getWebParam4 ()
{
return (String)get_Value(COLUMNNAME_WebParam4);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Advertisement.java
| 1
|
请完成以下Java代码
|
public FetchAndLockBuilderImpl workerId(String workerId) {
this.workerId = workerId;
return this;
}
public FetchAndLockBuilderImpl maxTasks(int maxTasks) {
this.maxTasks = maxTasks;
return this;
}
public FetchAndLockBuilderImpl usePriority(boolean usePriority) {
this.usePriority = usePriority;
return this;
}
public FetchAndLockBuilderImpl orderByCreateTime() {
orderingProperties.add(new QueryOrderingProperty(CREATE_TIME, null));
return this;
}
public FetchAndLockBuilderImpl asc() throws NotValidException {
configureLastOrderingPropertyDirection(ASCENDING);
return this;
}
public FetchAndLockBuilderImpl desc() throws NotValidException {
configureLastOrderingPropertyDirection(DESCENDING);
return this;
}
@Override
public ExternalTaskQueryTopicBuilder subscribe() {
checkQueryOk();
return new ExternalTaskQueryTopicBuilderImpl(commandExecutor, workerId, maxTasks, usePriority, orderingProperties);
}
|
protected void configureLastOrderingPropertyDirection(Direction direction) {
QueryOrderingProperty lastProperty = !orderingProperties.isEmpty() ? getLastElement(orderingProperties) : null;
ensureNotNull(NotValidException.class, "You should call any of the orderBy methods first before specifying a direction", "currentOrderingProperty", lastProperty);
if (lastProperty.getDirection() != null) {
ensureNull(NotValidException.class, "Invalid query: can specify only one direction desc() or asc() for an ordering constraint", "direction", direction);
}
lastProperty.setDirection(direction);
}
protected void checkQueryOk() {
for (QueryOrderingProperty orderingProperty : orderingProperties) {
ensureNotNull(NotValidException.class, "Invalid query: call asc() or desc() after using orderByXX()", "direction", orderingProperty.getDirection());
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\FetchAndLockBuilderImpl.java
| 1
|
请完成以下Java代码
|
protected static boolean valuesAreNumbers(Object variableValue, Object actualValue) {
return actualValue instanceof Number && variableValue instanceof Number;
}
@Override
public Collection<String> getFunctionNames() {
Collection<String> functionNames = new LinkedHashSet<>();
for (String functionPrefix : prefixes()) {
for (String functionNameOption : localNames()) {
functionNames.add(functionPrefix + ":" + functionNameOption);
}
}
return functionNames;
}
@Override
public AstFunction createFunction(String name, int index, AstParameters parameters, boolean varargs, FlowableExpressionParser parser) {
Method method = functionMethod();
int parametersCardinality = parameters.getCardinality();
int methodParameterCount = method.getParameterCount();
if (method.isVarArgs() || parametersCardinality < methodParameterCount) {
// If the method is a varargs or the number of parameters is less than the defined in the method
// then create an identifier for the variableContainer
// and analyze the parameters
List<AstNode> newParameters = new ArrayList<>(parametersCardinality + 1);
newParameters.add(parser.createIdentifier(variableScopeName));
|
if (methodParameterCount >= 1) {
// If the first parameter is an identifier we have to convert it to a text node
// We want to allow writing variables:get(varName) where varName is without quotes
newParameters.add(createVariableNameNode(parameters.getChild(0)));
for (int i = 1; i < parametersCardinality; i++) {
// the rest of the parameters should be treated as is
newParameters.add(parameters.getChild(i));
}
}
return new AstFunction(name, index, new AstParameters(newParameters), varargs);
} else {
// If the resolved parameters are of the same size as the current method then nothing to do
return new AstFunction(name, index, parameters, varargs);
}
}
protected AstNode createVariableNameNode(AstNode variableNode) {
if (variableNode instanceof AstIdentifier) {
return new AstText(((AstIdentifier) variableNode).getName());
} else {
return variableNode;
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\function\AbstractFlowableVariableExpressionFunction.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("name", _name)
.add("contentType", _mimeType)
.add("data bytes", (_data == null ? 0 : _data.length))
.toString();
}
/**
* @return file name
*/
@Override
public String getName()
{
return _name;
}
@Override
public InputStream getInputStream() throws IOException
{
if (_data == null)
{
throw new IOException("no data");
}
|
// a new stream must be returned each time.
return new ByteArrayInputStream(_data);
}
/**
* Throws exception
*/
@Override
public OutputStream getOutputStream() throws IOException
{
throw new IOException("cannot do this");
}
/**
* Get Content Type
*
* @return MIME type e.g. text/html
*/
@Override
public String getContentType()
{
return _mimeType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\ByteArrayBackedDataSource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected Pair<Boolean, Boolean> saveOrUpdateEntityView(TenantId tenantId, EntityViewId entityViewId, EntityViewUpdateMsg entityViewUpdateMsg) {
boolean created = false;
boolean entityViewNameUpdated = false;
EntityView entityView = JacksonUtil.fromString(entityViewUpdateMsg.getEntity(), EntityView.class, true);
if (entityView == null) {
throw new RuntimeException("[{" + tenantId + "}] entityViewUpdateMsg {" + entityViewUpdateMsg + "} cannot be converted to entity view");
}
EntityView entityViewById = edgeCtx.getEntityViewService().findEntityViewById(tenantId, entityViewId);
if (entityViewById == null) {
created = true;
entityView.setId(null);
} else {
entityView.setId(entityViewId);
}
if (isSaveRequired(entityViewById, entityView)) {
entityViewNameUpdated = updateEntityViewNameIfDuplicateExists(tenantId, entityViewId, entityView);
setCustomerId(tenantId, created ? null : entityViewById.getCustomerId(), entityView, entityViewUpdateMsg);
entityViewValidator.validate(entityView, EntityView::getTenantId);
if (created) {
entityView.setId(entityViewId);
}
edgeCtx.getEntityViewService().saveEntityView(entityView, false);
}
return Pair.of(created, entityViewNameUpdated);
}
private boolean updateEntityViewNameIfDuplicateExists(TenantId tenantId, EntityViewId entityViewId, EntityView entityView) {
EntityView entityViewByName = edgeCtx.getEntityViewService().findEntityViewByTenantIdAndName(tenantId, entityView.getName());
|
return generateUniqueNameIfDuplicateExists(tenantId, entityViewId, entityView, entityViewByName).map(uniqueName -> {
entityView.setName(uniqueName);
return true;
}).orElse(false);
}
protected abstract void setCustomerId(TenantId tenantId, CustomerId customerId, EntityView entityView, EntityViewUpdateMsg entityViewUpdateMsg);
protected void deleteEntityView(TenantId tenantId, EntityViewId entityViewId) {
deleteEntityView(tenantId, null, entityViewId);
}
protected void deleteEntityView(TenantId tenantId, Edge edge, EntityViewId entityViewId) {
EntityView entityViewById = edgeCtx.getEntityViewService().findEntityViewById(tenantId, entityViewId);
if (entityViewById != null) {
edgeCtx.getEntityViewService().deleteEntityView(tenantId, entityViewId);
pushEntityEventToRuleEngine(tenantId, edge, entityViewById, TbMsgType.ENTITY_DELETED);
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\entityview\BaseEntityViewProcessor.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setCreatedAfter(Date createdAfter) {
this.createdAfter = createdAfter;
}
public String getStartUserId() {
return startUserId;
}
public void setStartUserId(String startUserId) {
this.startUserId = startUserId;
}
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public Boolean getIncludeEnded() {
return includeEnded;
}
public void setIncludeEnded(Boolean includeEnded) {
this.includeEnded = includeEnded;
}
public Boolean getIncludeLocalVariables() {
return includeLocalVariables;
|
}
public void setIncludeLocalVariables(boolean includeLocalVariables) {
this.includeLocalVariables = includeLocalVariables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public void setCaseInstanceIds(Set<String> caseInstanceIds) {
this.caseInstanceIds = caseInstanceIds;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceQueryRequest.java
| 2
|
请完成以下Java代码
|
public java.lang.String getRequestType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestType);
}
/** Set Ergebnis.
@param Result
Result of the action taken
*/
@Override
public void setResult (java.lang.String Result)
{
set_Value (COLUMNNAME_Result, Result);
}
/** Get Ergebnis.
@return Result of the action taken
*/
@Override
public java.lang.String getResult ()
{
return (java.lang.String)get_Value(COLUMNNAME_Result);
}
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
@Override
public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
|
}
/** Get Summary.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Request.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isFullMatch() {
for (ConditionAndOutcome conditionAndOutcomes : this) {
if (!conditionAndOutcomes.getOutcome().isMatch()) {
return false;
}
}
return true;
}
/**
* Return a {@link Stream} of the {@link ConditionAndOutcome} items.
* @return a stream of the {@link ConditionAndOutcome} items.
* @since 3.5.0
*/
public Stream<ConditionAndOutcome> stream() {
return StreamSupport.stream(spliterator(), false);
}
@Override
public Iterator<ConditionAndOutcome> iterator() {
return Collections.unmodifiableSet(this.outcomes).iterator();
}
}
/**
* Provides access to a single {@link Condition} and {@link ConditionOutcome}.
*/
public static class ConditionAndOutcome {
private final Condition condition;
private final ConditionOutcome outcome;
public ConditionAndOutcome(Condition condition, ConditionOutcome outcome) {
this.condition = condition;
this.outcome = outcome;
}
public Condition getCondition() {
return this.condition;
|
}
public ConditionOutcome getOutcome() {
return this.outcome;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConditionAndOutcome other = (ConditionAndOutcome) obj;
return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass())
&& ObjectUtils.nullSafeEquals(this.outcome, other.outcome));
}
@Override
public int hashCode() {
return this.condition.getClass().hashCode() * 31 + this.outcome.hashCode();
}
@Override
public String toString() {
return this.condition.getClass() + " " + this.outcome;
}
}
private static final class AncestorsMatchedCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
throw new UnsupportedOperationException();
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\ConditionEvaluationReport.java
| 2
|
请完成以下Java代码
|
public static String rewriteQuickly(String text)
{
return dictionary.rewriteQuickly(text);
}
public static String rewrite(String text)
{
return dictionary.rewrite(text);
}
/**
* 语义距离
* @param itemA
* @param itemB
* @return
*/
public static long distance(CommonSynonymDictionary.SynonymItem itemA, CommonSynonymDictionary.SynonymItem itemB)
{
return itemA.distance(itemB);
}
/**
* 判断两个单词之间的语义距离
* @param A
* @param B
* @return
*/
public static long distance(String A, String B)
{
CommonSynonymDictionary.SynonymItem itemA = get(A);
CommonSynonymDictionary.SynonymItem itemB = get(B);
if (itemA == null || itemB == null) return Long.MAX_VALUE;
return distance(itemA, itemB);
}
/**
* 计算两个单词之间的相似度,0表示不相似,1表示完全相似
* @param A
* @param B
* @return
*/
public static double similarity(String A, String B)
{
long distance = distance(A, B);
if (distance > dictionary.getMaxSynonymItemIdDistance()) return 0.0;
return (dictionary.getMaxSynonymItemIdDistance() - distance) / (double) dictionary.getMaxSynonymItemIdDistance();
}
/**
* 将分词结果转换为同义词列表
* @param sentence 句子
* @param withUndefinedItem 是否保留词典中没有的词语
* @return
*/
public static List<CommonSynonymDictionary.SynonymItem> createSynonymList(List<Term> sentence, boolean withUndefinedItem)
{
List<CommonSynonymDictionary.SynonymItem> synonymItemList = new ArrayList<CommonSynonymDictionary.SynonymItem>(sentence.size());
for (Term term : sentence)
{
CommonSynonymDictionary.SynonymItem item = get(term.word);
if (item == null)
{
if (withUndefinedItem)
|
{
item = CommonSynonymDictionary.SynonymItem.createUndefined(term.word);
synonymItemList.add(item);
}
}
else
{
synonymItemList.add(item);
}
}
return synonymItemList;
}
/**
* 获取语义标签
* @return
*/
public static long[] getLexemeArray(List<CommonSynonymDictionary.SynonymItem> synonymItemList)
{
long[] array = new long[synonymItemList.size()];
int i = 0;
for (CommonSynonymDictionary.SynonymItem item : synonymItemList)
{
array[i++] = item.entry.id;
}
return array;
}
public long distance(List<CommonSynonymDictionary.SynonymItem> synonymItemListA, List<CommonSynonymDictionary.SynonymItem> synonymItemListB)
{
return EditDistance.compute(synonymItemListA, synonymItemListB);
}
public long distance(long[] arrayA, long[] arrayB)
{
return EditDistance.compute(arrayA, arrayB);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreSynonymDictionary.java
| 1
|
请完成以下Java代码
|
public boolean hasNext()
{
if (isClosed())
{
return false;
}
// NOTE: we do this checking only to have last page optimizations
// e.g. consider having 100 records, page size=10, so last page will be fully loaded.
// If we are not doing this checking, the buffered iterator will try to load the next page (which is empty),
// in order to find out that there is nothing to be loaded.
if (rowsFetched >= rowsCount)
{
close();
return false;
}
try
{
while (peekingBufferedIterator.hasNext())
{
// Check the rowsFetched again, because in this while we are also navigating forward and we skip invalid values
if (rowsFetched >= rowsCount)
{
close();
return false;
}
final ET value = peekingBufferedIterator.peek();
if (isValidModel(value))
{
return true;
}
// not a valid model:
else
{
peekingBufferedIterator.next(); // skip this element because it's not valid
rowsFetched++; // increase the rowsFetched because we use it to compare with "rowsCount" in order to figure out when we reached the end of the selection.
}
}
close();
return false;
}
catch (final RuntimeException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
|
@Override
public ET next()
{
if (isClosed())
{
throw new AdempiereException("Iterator was already closed: " + this);
}
try
{
final ET value = peekingBufferedIterator.next();
rowsFetched++;
return value;
}
catch (final RuntimeException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
@Override
public void remove()
{
peekingBufferedIterator.remove();
}
/**
* Sets buffer/page size, i.e. the number of rows to be loaded by this iterator at a time.
*
* @see IQuery#OPTION_IteratorBufferSize
*/
public void setBufferSize(final int bufferSize)
{
bufferedIterator.setBufferSize(bufferSize);
}
@Override
public String toString()
{
return "GuaranteedPOBufferedIterator [clazz=" + clazz
+ ", querySelectionUUID=" + querySelectionUUID
+ ", rowsFetched=" + rowsFetched
+ ", rowsCount=" + rowsCount
+ ", query=" + query
+ ", bufferedIterator=" + bufferedIterator
+ "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\GuaranteedPOBufferedIterator.java
| 1
|
请完成以下Java代码
|
public String getCtrySubDvsn() {
return ctrySubDvsn;
}
/**
* Sets the value of the ctrySubDvsn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtrySubDvsn(String value) {
this.ctrySubDvsn = value;
}
/**
* Gets the value of the ctry property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCtry() {
return ctry;
}
/**
* Sets the value of the ctry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtry(String value) {
this.ctry = value;
}
/**
* Gets the value of the adrLine property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
|
* This is why there is not a <CODE>set</CODE> method for the adrLine property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdrLine().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAdrLine() {
if (adrLine == null) {
adrLine = new ArrayList<String>();
}
return this.adrLine;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PostalAddress6.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName().replace("Impl", "")).append("[")
.append("id=").append(id)
.append(", jobHandlerType=").append(jobHandlerType)
.append(", jobType=").append(jobType);
if (category != null) {
sb.append(", category=").append(category);
}
if (elementId != null) {
sb.append(", elementId=").append(elementId);
}
if (correlationId != null) {
sb.append(", correlationId=").append(correlationId);
}
if (executionId != null) {
|
sb.append(", processInstanceId=").append(processInstanceId)
.append(", executionId=").append(executionId);
} else if (scopeId != null) {
sb.append(", scopeId=").append(scopeId)
.append(", subScopeId=").append(subScopeId)
.append(", scopeType=").append(scopeType);
}
if (processDefinitionId != null) {
sb.append(", processDefinitionId=").append(processDefinitionId);
} else if (scopeDefinitionId != null) {
if (scopeId == null) {
sb.append(", scopeType=").append(scopeType);
}
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\AbstractJobEntityImpl.java
| 2
|
请完成以下Java代码
|
private String dashName(OperationParameter parameter) {
return "-" + parameter.getName();
}
private boolean getBlocking(OperationMethod method) {
return !REACTIVE_STREAMS_PRESENT || !Publisher.class.isAssignableFrom(method.getMethod().getReturnType());
}
@Override
public String getId() {
return this.id;
}
@Override
public boolean isBlocking() {
|
return this.blocking;
}
@Override
public WebOperationRequestPredicate getRequestPredicate() {
return this.requestPredicate;
}
@Override
protected void appendFields(ToStringCreator creator) {
creator.append("id", this.id)
.append("blocking", this.blocking)
.append("requestPredicate", this.requestPredicate);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\DiscoveredWebOperation.java
| 1
|
请完成以下Java代码
|
public boolean isWorkpackageProcessorBlacklisted(final int workpackageProcessorId)
{
return blacklist.isBlacklisted(workpackageProcessorId);
}
public WorkpackageProcessorBlackList getBlackList()
{
return blacklist;
}
private volatile WorkpackageProcessorFactoryJMX mbean = null;
@Override
public synchronized Object getMBean()
{
if (mbean == null)
{
mbean = new WorkpackageProcessorFactoryJMX(this);
}
return mbean;
}
|
@Override
public IMutableQueueProcessorStatistics getWorkpackageProcessorStatistics(@NonNull IWorkpackageProcessor workpackageProcessor)
{
// NOTE: keep in sync with getWorkpackageProcessorStatistics(I_C_Queue_PackageProcessor workpackage). Both methods shall build the name in the same way
final String workpackageProcessorName = workpackageProcessor.getClass().getName();
return new MonitorableQueueProcessorStatistics(workpackageProcessorName);
}
@Override
public IMutableQueueProcessorStatistics getWorkpackageProcessorStatistics(@NonNull final I_C_Queue_PackageProcessor workpackageProcessorDef)
{
// NOTE: keep in sync with getWorkpackageProcessorStatistics(IWorkpackageProcessor workpackageProcessor). Both methods shall build the name in the same way
final String workpackageProcessorName = workpackageProcessorDef.getClassname();
return new MonitorableQueueProcessorStatistics(workpackageProcessorName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageProcessorFactory.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty() {
return elements.isEmpty();
}
private boolean isRoot(int index) {
return index == 0;
}
private int smallerChildIndex(int index) {
int leftChildIndex = leftChildIndex(index);
int rightChildIndex = rightChildIndex(index);
if (!isValidIndex(rightChildIndex)) {
return leftChildIndex;
}
if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) {
return leftChildIndex;
}
return rightChildIndex;
}
private boolean isLeaf(int index) {
return !isValidIndex(leftChildIndex(index));
}
private boolean isCorrectParent(int index) {
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
}
private boolean isCorrectChild(int index) {
return isCorrect(parentIndex(index), index);
}
private boolean isCorrect(int parentIndex, int childIndex) {
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
return true;
}
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
}
private boolean isValidIndex(int index) {
|
return index < elements.size();
}
private void swap(int index1, int index2) {
E element1 = elementAt(index1);
E element2 = elementAt(index2);
elements.set(index1, element2);
elements.set(index2, element1);
}
private E elementAt(int index) {
return elements.get(index);
}
private int parentIndex(int index) {
return (index - 1) / 2;
}
private int leftChildIndex(int index) {
return 2 * index + 1;
}
private int rightChildIndex(int index) {
return 2 * index + 2;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\heapsort\Heap.java
| 1
|
请完成以下Java代码
|
public static Function<DefaultTenantProfileConfiguration, String> merge(
Function<DefaultTenantProfileConfiguration, String> configExtractor1,
Function<DefaultTenantProfileConfiguration, String> configExtractor2) {
return config -> {
String config1 = configExtractor1.apply(config);
String config2 = configExtractor2.apply(config);
return RateLimitUtil.mergeStrConfigs(config1, config2); // merges the configs
};
}
private static String mergeStrConfigs(String firstConfig, String secondConfig) {
List<RateLimitEntry> all = new ArrayList<>();
all.addAll(parseConfig(firstConfig));
all.addAll(parseConfig(secondConfig));
Map<Long, Long> merged = new HashMap<>();
for (RateLimitEntry entry : all) {
merged.merge(entry.durationSeconds(), entry.capacity(), Long::sum);
|
}
return merged.entrySet().stream()
.sorted(Map.Entry.comparingByKey()) // optional: sort by duration
.map(e -> e.getValue() + ":" + e.getKey())
.collect(Collectors.joining(","));
}
public static boolean isValid(String configStr) {
List<RateLimitEntry> limitedApiEntries = parseConfig(configStr);
Set<Long> distinctDurations = new HashSet<>();
for (RateLimitEntry entry : limitedApiEntries) {
if (!distinctDurations.add(entry.durationSeconds())) {
return false;
}
}
return true;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\limit\RateLimitUtil.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.