instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public DynamicUserTaskBuilder id(String id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DynamicUserTaskBuilder name(String name) {
this.name = name;
return this;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public DynamicUserTaskBuilder assignee(String assignee) {
this.assignee = assignee;
return this;
}
public DynamicUserTaskCallback getDynamicUserTaskCallback() {
return dynamicUserTaskCallback;
}
public void setDynamicUserTaskCallback(DynamicUserTaskCallback dynamicUserTaskCallback) {
this.dynamicUserTaskCallback = dynamicUserTaskCallback;
}
public DynamicUserTaskBuilder dynamicUserTaskCallback(DynamicUserTaskCallback dynamicUserTaskCallback) {
this.dynamicUserTaskCallback = dynamicUserTaskCallback;
return this;
}
public String getDynamicTaskId() {
return dynamicTaskId;
}
public void setDynamicTaskId(String dynamicTaskId) {
this.dynamicTaskId = dynamicTaskId; | }
public String nextSubProcessId(Map<String, FlowElement> flowElementMap) {
return nextId("dynamicSubProcess", flowElementMap);
}
public String nextTaskId(Map<String, FlowElement> flowElementMap) {
return nextId("dynamicTask", flowElementMap);
}
public String nextFlowId(Map<String, FlowElement> flowElementMap) {
return nextId("dynamicFlow", flowElementMap);
}
public String nextForkGatewayId(Map<String, FlowElement> flowElementMap) {
return nextId("dynamicForkGateway", flowElementMap);
}
public String nextJoinGatewayId(Map<String, FlowElement> flowElementMap) {
return nextId("dynamicJoinGateway", flowElementMap);
}
public String nextStartEventId(Map<String, FlowElement> flowElementMap) {
return nextId("startEvent", flowElementMap);
}
public String nextEndEventId(Map<String, FlowElement> flowElementMap) {
return nextId("endEvent", flowElementMap);
}
protected String nextId(String prefix, Map<String, FlowElement> flowElementMap) {
String nextId = null;
boolean nextIdNotFound = true;
while (nextIdNotFound) {
if (!flowElementMap.containsKey(prefix + counter)) {
nextId = prefix + counter;
nextIdNotFound = false;
}
counter++;
}
return nextId;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\DynamicUserTaskBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Output getOutput() {
return null;
}
@JsonIgnore
@Override
public boolean requiresScheduledReevaluation() {
return getAllRules().anyMatch(entry -> entry.getValue().requiresScheduledReevaluation());
}
@JsonIgnore
public Stream<Pair<AlarmSeverity, AlarmRule>> getAllRules() {
Stream<Pair<AlarmSeverity, AlarmRule>> rules = createRules.entrySet().stream()
.map(entry -> Pair.of(entry.getKey(), entry.getValue()));
if (clearRule != null) {
rules = Stream.concat(rules, Stream.of(Pair.of(null, clearRule)));
}
return rules.sorted(comparingByKey(Comparator.nullsLast(Comparator.naturalOrder())));
}
public boolean rulesEqual(AlarmCalculatedFieldConfiguration other, BiPredicate<AlarmRule, AlarmRule> equalityCheck) {
List<Pair<AlarmSeverity, AlarmRule>> thisRules = this.getAllRules().toList();
List<Pair<AlarmSeverity, AlarmRule>> otherRules = other.getAllRules().toList(); | return CollectionsUtil.elementsEqual(thisRules, otherRules, (thisRule, otherRule) -> {
if (!Objects.equals(thisRule.getKey(), otherRule.getKey())) {
return false;
}
return equalityCheck.test(thisRule.getValue(), otherRule.getValue());
});
}
public boolean propagationSettingsEqual(AlarmCalculatedFieldConfiguration other) {
return this.propagate == other.propagate &&
this.propagateToOwner == other.propagateToOwner &&
this.propagateToTenant == other.propagateToTenant &&
Objects.equals(this.propagateRelationTypes, other.propagateRelationTypes);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\AlarmCalculatedFieldConfiguration.java | 2 |
请完成以下Java代码 | public void setPOReference (final @Nullable java.lang.String POReference)
{
set_ValueNoCheck (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setPostingType (final @Nullable java.lang.String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
@Override
public java.lang.String getPostingType()
{
return get_ValueAsString(COLUMNNAME_PostingType);
}
@Override | public void setTaxAmtSource (final @Nullable BigDecimal TaxAmtSource)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtSource, TaxAmtSource);
}
@Override
public BigDecimal getTaxAmtSource()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtSource);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATCode (final @Nullable java.lang.String VATCode)
{
set_ValueNoCheck (COLUMNNAME_VATCode, VATCode);
}
@Override
public java.lang.String getVATCode()
{
return get_ValueAsString(COLUMNNAME_VATCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportLine.java | 1 |
请完成以下Java代码 | public boolean isUOMForTUs(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return isUOMForTUs(uom);
}
public static boolean isUOMForTUs(@NonNull final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355());
return X12DE355.COLI.equals(x12de355) || X12DE355.TU.equals(x12de355);
}
@Override
public @NonNull UOMType getUOMTypeById(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return UOMType.ofNullableCodeOrOther(uom.getUOMType());
} | @Override
public @NonNull Optional<I_C_UOM> getBySymbol(@NonNull final String uomSymbol)
{
return Optional.ofNullable(queryBL.createQueryBuilder(I_C_UOM.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_UOM.COLUMNNAME_UOMSymbol, uomSymbol)
.create()
.firstOnlyOrNull(I_C_UOM.class));
}
@Override
public ITranslatableString getUOMSymbolById(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return InterfaceWrapperHelper.getModelTranslationMap(uom).getColumnTrl(I_C_UOM.COLUMNNAME_UOMSymbol, uom.getUOMSymbol());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMDAO.java | 1 |
请完成以下Java代码 | public class TenantIdProviderHistoricDecisionInstanceContext {
protected DecisionDefinition decisionDefinition;
protected DelegateExecution execution;
protected DelegateCaseExecution caseExecution;
public TenantIdProviderHistoricDecisionInstanceContext(DecisionDefinition decisionDefinition) {
this.decisionDefinition = decisionDefinition;
}
public TenantIdProviderHistoricDecisionInstanceContext(DecisionDefinition decisionDefinition, DelegateExecution execution) {
this(decisionDefinition);
this.execution = execution;
}
public TenantIdProviderHistoricDecisionInstanceContext(DecisionDefinition decisionDefinition, DelegateCaseExecution caseExecution) {
this(decisionDefinition);
this.caseExecution = caseExecution;
}
/**
* @return the decision definition of the historic decision instance which is being evaluated
*/
public DecisionDefinition getDecisionDefinition() { | return decisionDefinition;
}
/**
* @return the execution. This method returns the execution of the process instance
* which evaluated the decision definition.
*/
public DelegateExecution getExecution() {
return execution;
}
/**
* @return the case execution. This method returns the case execution of the CMMN case task
* which evaluated the decision definition.
*/
public DelegateCaseExecution getCaseExecution() {
return caseExecution;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\multitenancy\TenantIdProviderHistoricDecisionInstanceContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConcurrencyControlConfigurer expiredSessionStrategy(
SessionInformationExpiredStrategy expiredSessionStrategy) {
SessionManagementConfigurer.this.expiredSessionStrategy = expiredSessionStrategy;
return this;
}
/**
* If true, prevents a user from authenticating when the
* {@link #maximumSessions(int)} has been reached. Otherwise (default), the user
* who authenticates is allowed access and an existing user's session is expired.
* The user's who's session is forcibly expired is sent to
* {@link #expiredUrl(String)}. The advantage of this approach is if a user
* accidentally does not log out, there is no need for an administrator to
* intervene or wait till their session expires.
* @param maxSessionsPreventsLogin true to have an error at time of
* authentication, else false (default)
* @return the {@link ConcurrencyControlConfigurer} for further customizations
*/ | public ConcurrencyControlConfigurer maxSessionsPreventsLogin(boolean maxSessionsPreventsLogin) {
SessionManagementConfigurer.this.maxSessionsPreventsLogin = maxSessionsPreventsLogin;
return this;
}
/**
* Controls the {@link SessionRegistry} implementation used. The default is
* {@link SessionRegistryImpl} which is an in memory implementation.
* @param sessionRegistry the {@link SessionRegistry} to use
* @return the {@link ConcurrencyControlConfigurer} for further customizations
*/
public ConcurrencyControlConfigurer sessionRegistry(SessionRegistry sessionRegistry) {
SessionManagementConfigurer.this.sessionRegistry = sessionRegistry;
return this;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\SessionManagementConfigurer.java | 2 |
请完成以下Java代码 | public String[] getActiveTrxNames()
{
return Services.get(ITrxManager.class)
.getActiveTransactionsList()
.stream()
.map((trx) -> trx.getTrxName())
.toArray((size) -> new String[size]);
}
@ManagedOperation
public String getStrackTrace(String trxName)
{
return Services.get(IOpenTrxBL.class).getCreationStackTrace(trxName);
}
@ManagedOperation
public String[] getServerContext()
{
final Properties ctx = Env.getCtx();
String[] context = Env.getEntireContext(ctx);
Arrays.sort(context);
return context;
}
@ManagedOperation
public void setLogLevel(String levelName)
{
LogManager.setLevel(levelName);
}
@ManagedOperation
public String getLogLevel()
{
final Level level = LogManager.getLevel();
return level == null ? null : level.toString();
} | @ManagedOperation
public void runFinalization()
{
System.runFinalization();
}
@ManagedOperation
public void resetLocalCache()
{
CacheMgt.get().reset();
}
@ManagedOperation
public void rotateMigrationScriptFile()
{
MigrationScriptFileLoggerHolder.closeMigrationScriptFiles();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\jmx\Metasfresh.java | 1 |
请完成以下Java代码 | protected void renderInvalidDateMessage(FormField formField, HtmlDocumentBuilder documentBuilder) {
String formFieldId = formField.getId();
HtmlElementWriter firstDivElement = new HtmlElementWriter(DIV_ELEMENT);
String firstExpression = String.format(REQUIRED_ERROR_EXPRESSION + " && !" + DATE_ERROR_EXPRESSION, formFieldId, formFieldId);
firstDivElement
.attribute(NG_SHOW_ATTRIBUTE, firstExpression)
.attribute(CLASS_ATTRIBUTE, HELP_BLOCK_CLASS)
.textContent(REQUIRED_FIELD_MESSAGE);
documentBuilder
.startElement(firstDivElement)
.endElement();
HtmlElementWriter secondDivElement = new HtmlElementWriter(DIV_ELEMENT);
String secondExpression = String.format(DATE_ERROR_EXPRESSION, formFieldId);
secondDivElement
.attribute(NG_SHOW_ATTRIBUTE, secondExpression)
.attribute(CLASS_ATTRIBUTE, HELP_BLOCK_CLASS)
.textContent(INVALID_DATE_FIELD_MESSAGE);
documentBuilder
.startElement(secondDivElement)
.endElement();
}
protected void addCommonFormFieldAttributes(FormField formField, HtmlElementWriter formControl) {
String typeName = formField.getTypeName();
if (isEnum(formField) || isDate(formField)) {
typeName = StringFormType.TYPE_NAME;
}
typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1);
String formFieldId = formField.getId();
formControl
.attribute(CLASS_ATTRIBUTE, FORM_CONTROL_CLASS)
.attribute(NAME_ATTRIBUTE, formFieldId)
.attribute(CAM_VARIABLE_TYPE_ATTRIBUTE, typeName) | .attribute(CAM_VARIABLE_NAME_ATTRIBUTE, formFieldId);
// add validation constraints
for (FormFieldValidationConstraint constraint : formField.getValidationConstraints()) {
String constraintName = constraint.getName();
String configuration = (String) constraint.getConfiguration();
formControl.attribute(constraintName, configuration);
}
}
// helper /////////////////////////////////////////////////////////////////////////////////////
protected boolean isEnum(FormField formField) {
return EnumFormType.TYPE_NAME.equals(formField.getTypeName());
}
protected boolean isDate(FormField formField) {
return DateFormType.TYPE_NAME.equals(formField.getTypeName());
}
protected boolean isBoolean(FormField formField) {
return BooleanFormType.TYPE_NAME.equals(formField.getTypeName());
}
protected boolean isReadOnly(FormField formField) {
List<FormFieldValidationConstraint> validationConstraints = formField.getValidationConstraints();
if(validationConstraints != null) {
for (FormFieldValidationConstraint validationConstraint : validationConstraints) {
if(HtmlFormEngine.CONSTRAINT_READONLY.equals(validationConstraint.getName())){
return true;
}
}
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\AbstractRenderFormDelegate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
this.nameChanged = true;
}
@ApiModelProperty(example = "Model key")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
this.keyChanged = true;
}
@ApiModelProperty(example = "Model category")
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
this.categoryChanged = true;
}
@ApiModelProperty(example = "2")
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
this.versionChanged = true;
}
@ApiModelProperty(example = "Model metainfo")
public String getMetaInfo() {
return metaInfo;
}
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
this.metaInfoChanged = true;
}
@ApiModelProperty(example = "7")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
this.deploymentChanged = true;
} | public void setTenantId(String tenantId) {
tenantChanged = true;
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
@JsonIgnore
public boolean isCategoryChanged() {
return categoryChanged;
}
@JsonIgnore
public boolean isKeyChanged() {
return keyChanged;
}
@JsonIgnore
public boolean isMetaInfoChanged() {
return metaInfoChanged;
}
@JsonIgnore
public boolean isNameChanged() {
return nameChanged;
}
@JsonIgnore
public boolean isVersionChanged() {
return versionChanged;
}
@JsonIgnore
public boolean isDeploymentChanged() {
return deploymentChanged;
}
@JsonIgnore
public boolean isTenantIdChanged() {
return tenantChanged;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ModelRequest.java | 2 |
请完成以下Java代码 | public void formParam(@Param String name, Response response) {
log.info("name: " + name);
response.text(name);
}
@GetRoute("/params/path/:uid")
public void restfulParam(@PathParam Integer uid, Response response) {
log.info("uid: " + uid);
response.text(String.valueOf(uid));
}
@PostRoute("/params-file") // DO NOT USE A SLASH WITHIN THE ROUTE OR IT WILL BREAK (?)
@JSON
public RestResponse<?> fileParam(@MultipartParam FileItem fileItem) throws Exception {
try {
byte[] fileContent = fileItem.getData();
log.debug("Saving the uploaded file");
java.nio.file.Path tempFile = Files.createTempFile("baeldung_tempfiles", ".tmp");
Files.write(tempFile, fileContent, StandardOpenOption.WRITE);
return RestResponse.ok();
} catch (Exception e) {
log.error(e.getMessage(), e);
return RestResponse.fail(e.getMessage()); | }
}
@GetRoute("/params/header")
public void headerParam(@HeaderParam String customheader, Response response) {
log.info("Custom header: " + customheader);
response.text(customheader);
}
@GetRoute("/params/cookie")
public void cookieParam(@CookieParam(defaultValue = "default value") String myCookie, Response response) {
log.info("myCookie: " + myCookie);
response.text(myCookie);
}
@PostRoute("/params/vo")
public void voParam(@Param User user, Response response) {
log.info("user as voParam: " + user.toString());
response.html(user.toString() + "<br/><br/><a href='/'>Back</a>");
}
} | repos\tutorials-master\web-modules\blade\src\main\java\com\baeldung\blade\sample\ParameterInjectionExampleController.java | 1 |
请完成以下Java代码 | public class C_Conversion_Rate
{
@Init
public void init()
{
final IProgramaticCalloutProvider programaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class);
programaticCalloutProvider.registerAnnotatedCallout(new de.metas.currency.callout.C_Conversion_Rate());
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void beforeSave(final I_C_Conversion_Rate conversionRate)
{
// From - To is the same
if (conversionRate.getC_Currency_ID() == conversionRate.getC_Currency_ID_To())
{
throw new AdempiereException("@C_Currency_ID@ = @C_Currency_ID@");
}
// Nothing to convert
if (conversionRate.getMultiplyRate().compareTo(BigDecimal.ZERO) <= 0)
{ | throw new AdempiereException("@MultiplyRate@ <= 0");
}
// Date Range Check
final Timestamp from = conversionRate.getValidFrom();
if (conversionRate.getValidTo() == null)
{
conversionRate.setValidTo(TimeUtil.getDay(2056, 12, 31));
}
final Timestamp to = conversionRate.getValidTo();
if (to.before(from))
{
final SimpleDateFormat df = DisplayType.getDateFormat(DisplayType.Date);
throw new AdempiereException(df.format(to) + " < " + df.format(from));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\model\interceptor\C_Conversion_Rate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<VariableInstance> findVariableInstancesByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectVariableInstanceByNativeQuery", parameterMap);
}
@Override
public long findVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectVariableInstanceCountByNativeQuery", parameterMap);
}
@Override
public void deleteVariablesByTaskId(String taskId) {
DbSqlSession dbSqlSession = getDbSqlSession();
if (isEntityInserted(dbSqlSession, "task", taskId)) {
deleteCachedEntities(dbSqlSession, variableInstanceByTaskIdMatcher, taskId);
} else {
bulkDelete("deleteVariableInstancesByTaskId", variableInstanceByTaskIdMatcher, taskId);
}
}
@Override
public void deleteVariablesByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
deleteCachedEntities(dbSqlSession, variableInstanceByExecutionIdMatcher, executionId);
} else {
bulkDelete("deleteVariableInstancesByExecutionId", variableInstanceByExecutionIdMatcher, executionId);
}
}
@Override
public void deleteByScopeIdAndScopeType(String scopeId, String scopeType) {
Map<String, Object> params = new HashMap<>(3);
params.put("scopeId", scopeId);
params.put("scopeType", scopeType);
bulkDelete("deleteVariablesByScopeIdAndScopeType", variableInstanceByScopeIdAndScopeTypeMatcher, params);
}
@Override
public void deleteByScopeIdAndScopeTypes(String scopeId, Collection<String> scopeTypes) {
if (scopeTypes.size() == 1) { | deleteByScopeIdAndScopeType(scopeId, scopeTypes.iterator().next());
return;
}
Map<String, Object> params = new HashMap<>(3);
params.put("scopeId", scopeId);
params.put("scopeTypes", scopeTypes);
bulkDelete("deleteVariablesByScopeIdAndScopeTypes", variableInstanceByScopeIdAndScopeTypesMatcher, params);
}
@Override
public void deleteBySubScopeIdAndScopeTypes(String subScopeId, Collection<String> scopeTypes) {
Map<String, Object> params = new HashMap<>(3);
params.put("subScopeId", subScopeId);
params.put("scopeTypes", scopeTypes);
bulkDelete("deleteVariablesBySubScopeIdAndScopeTypes", variableInstanceBySubScopeIdAndScopeTypesMatcher, params);
}
@Override
protected IdGenerator getIdGenerator() {
return variableServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\data\impl\MybatisVariableInstanceDataManager.java | 2 |
请完成以下Java代码 | public class CmmnDiLabelXmlConverter extends BaseCmmnXmlConverter {
@Override
public String getXMLElementName() {
return CmmnXmlConstants.ELEMENT_DI_LABEL;
}
@Override
public boolean hasChildElements() {
return false;
}
@Override
protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
GraphicInfo labelGraphicInfo = new GraphicInfo(); | if (xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_ROTATION) != null
&& !xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_ROTATION).isEmpty()) {
labelGraphicInfo.setRotation(Double.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_ROTATION)).intValue());
}
conversionHelper.setCurrentLabelGraphicInfo(labelGraphicInfo);
return labelGraphicInfo;
}
@Override
protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) {
conversionHelper.setCurrentLabelGraphicInfo(null);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CmmnDiLabelXmlConverter.java | 1 |
请完成以下Java代码 | public BigDecimal getRelativePeriod ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativePeriod);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else | set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element
*/
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_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_PA_ReportColumn.java | 1 |
请完成以下Java代码 | 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 Ratio.
@param PA_Ratio_ID
Performace Ratio
*/
public void setPA_Ratio_ID (int PA_Ratio_ID)
{
if (PA_Ratio_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Ratio_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Ratio_ID, Integer.valueOf(PA_Ratio_ID));
}
/** Get Ratio.
@return Performace Ratio
*/
public int getPA_Ratio_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Ratio_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_PA_Ratio.java | 1 |
请完成以下Java代码 | public void setOnBlur (String script)
{
addAttribute ("onblur", script);
}
/**
* The onclick event occurs when the pointing device button is clicked over
* an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnClick (String script)
{
addAttribute ("onclick", script);
}
/**
* The ondblclick event occurs when the pointing device button is double
* clicked over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnDblClick (String script)
{
addAttribute ("ondblclick", script);
}
/**
* The onmousedown event occurs when the pointing device button is pressed
* over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseDown (String script)
{
addAttribute ("onmousedown", script);
}
/**
* The onmouseup event occurs when the pointing device button is released
* over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseUp (String script)
{
addAttribute ("onmouseup", script);
}
/**
* The onmouseover event occurs when the pointing device is moved onto an
* element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseOver (String script)
{
addAttribute ("onmouseover", script);
}
/**
* The onmousemove event occurs when the pointing device is moved while it
* is over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseMove (String script)
{
addAttribute ("onmousemove", script); | }
/**
* The onmouseout event occurs when the pointing device is moved away from
* an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseOut (String script)
{
addAttribute ("onmouseout", script);
}
/**
* The onkeypress event occurs when a key is pressed and released over an
* element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyPress (String script)
{
addAttribute ("onkeypress", script);
}
/**
* The onkeydown event occurs when a key is pressed down over an element.
* This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyDown (String script)
{
addAttribute ("onkeydown", script);
}
/**
* The onkeyup event occurs when a key is released over an element. This
* attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyUp (String script)
{
addAttribute ("onkeyup", script);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\area.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class POSProductsService
{
@NonNull private final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class);
@NonNull private final IProductBL productBL = Services.get(IProductBL.class);
@NonNull private final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
@NonNull private final POSTerminalService posTerminalService;
public POSProductsSearchResult getProducts(
@NonNull final POSTerminalId posTerminalId,
@NonNull final Instant evalDate,
@Nullable final String queryString)
{
final POSTerminal posTerminal = posTerminalService.getPOSTerminalById(posTerminalId);
return POSProductsSearchCommand.builder()
.productBL(productBL)
.loader(newProductsLoader()
.priceListId(posTerminal.getPriceListId()) | .currency(posTerminal.getCurrency())
.build())
.evalDate(evalDate)
.queryString(queryString)
.build()
.execute();
}
private POSProductsLoaderBuilder newProductsLoader()
{
return POSProductsLoader.builder()
.priceListDAO(priceListDAO)
.productBL(productBL)
.uomDAO(uomDAO);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSProductsService.java | 2 |
请完成以下Java代码 | public String getStreetAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
@Override
public String toString() {
return "Address{" + "streetAddress='" + streetAddress + '\'' + ", city='" + city + '\'' + ", postalCode='" + postalCode + '\'' + '}';
} | @Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Address address = (Address) o;
return Objects.equals(streetAddress, address.streetAddress) && Objects.equals(city, address.city) && Objects.equals(postalCode, address.postalCode);
}
@Override
public int hashCode() {
return Objects.hash(streetAddress, city, postalCode);
}
} | repos\tutorials-master\core-java-modules\core-java-lang-6\src\main\java\com\baeldung\compareobjects\Address.java | 1 |
请完成以下Java代码 | public void writeStartDocument() throws XMLStreamException {
super.writeStartDocument();
super.writeCharacters("\n");
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
super.writeStartDocument(version);
super.writeCharacters("\n");
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
super.writeStartDocument(encoding, version);
super.writeCharacters("\n");
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
onStartElement();
super.writeStartElement(localName);
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
onStartElement();
super.writeStartElement(namespaceURI, localName);
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
onStartElement();
super.writeStartElement(prefix, localName, namespaceURI);
}
@Override
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(namespaceURI, localName);
}
@Override | public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(prefix, localName, namespaceURI);
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
onEmptyElement();
super.writeEmptyElement(localName);
}
@Override
public void writeEndElement() throws XMLStreamException {
onEndElement();
super.writeEndElement();
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
state = SEEN_DATA;
super.writeCharacters(text);
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
state = SEEN_DATA;
super.writeCharacters(text, start, len);
}
@Override
public void writeCData(String data) throws XMLStreamException {
state = SEEN_DATA;
super.writeCData(data);
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\IndentingXMLStreamWriter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void onFailure(Throwable e) {
ResponseEntity entity;
if (e instanceof ToErrorResponseEntity) {
entity = ((ToErrorResponseEntity) e).toErrorResponseEntity();
} else {
entity = new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
logRuleEngineCall(currentUser, entityId, requestBody, null, e);
response.setResult(entity);
}
}));
return response;
} catch (IllegalArgumentException iae) {
throw new ThingsboardException("Invalid request body", iae, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
}
private void reply(LocalRequestMetaData rpcRequest, TbMsg response) {
DeferredResult<ResponseEntity> responseWriter = rpcRequest.responseWriter();
if (response == null) {
logRuleEngineCall(rpcRequest, null, new TimeoutException("Processing timeout detected!"));
responseWriter.setResult(new ResponseEntity<>(HttpStatus.REQUEST_TIMEOUT));
} else {
String responseData = response.getData();
if (!StringUtils.isEmpty(responseData)) {
try {
logRuleEngineCall(rpcRequest, response, null);
responseWriter.setResult(new ResponseEntity<>(JacksonUtil.toJsonNode(responseData), HttpStatus.OK));
} catch (IllegalArgumentException e) {
log.debug("Failed to decode device response: {}", responseData, e);
logRuleEngineCall(rpcRequest, response, e);
responseWriter.setResult(new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE));
}
} else {
logRuleEngineCall(rpcRequest, response, null);
responseWriter.setResult(new ResponseEntity<>(HttpStatus.OK));
} | }
}
private void logRuleEngineCall(LocalRequestMetaData rpcRequest, TbMsg response, Throwable e) {
logRuleEngineCall(rpcRequest.user(), rpcRequest.request().getOriginator(), rpcRequest.request().getData(), response, e);
}
private void logRuleEngineCall(SecurityUser user, EntityId entityId, String request, TbMsg response, Throwable e) {
auditLogService.logEntityAction(
user.getTenantId(),
user.getCustomerId(),
user.getId(),
user.getName(),
entityId,
null,
ActionType.REST_API_RULE_ENGINE_CALL,
BaseController.toException(e),
request,
response != null ? response.getData() : "");
}
private record LocalRequestMetaData(TbMsg request, SecurityUser user, DeferredResult<ResponseEntity> responseWriter) {}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\RuleEngineController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected ValidationResult validateSignature(Assertion token, ValidationContext context) {
return ValidationResult.VALID;
}
};
}
/**
* A tuple containing an OpenSAML {@link Response} and its associated authentication
* token.
*
* @since 5.4
*/
static class ResponseToken {
private final Saml2AuthenticationToken token;
private final Response response;
ResponseToken(Response response, Saml2AuthenticationToken token) {
this.token = token;
this.response = response;
}
Response getResponse() {
return this.response;
}
Saml2AuthenticationToken getToken() {
return this.token;
}
}
/**
* A tuple containing an OpenSAML {@link Assertion} and its associated authentication
* token.
*
* @since 5.4 | */
static class AssertionToken {
private final Saml2AuthenticationToken token;
private final Assertion assertion;
AssertionToken(Assertion assertion, Saml2AuthenticationToken token) {
this.token = token;
this.assertion = assertion;
}
Assertion getAssertion() {
return this.assertion;
}
Saml2AuthenticationToken getToken() {
return this.token;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\BaseOpenSamlAuthenticationProvider.java | 2 |
请完成以下Java代码 | public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getRecipientName() {
return recipientName;
}
public void setRecipientName(String recipientName) {
this.recipientName = recipientName;
}
public String getSenderName() { | return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getTemplateEngine() {
return templateEngine;
}
public void setTemplateEngine(String templateEngine) {
this.templateEngine = templateEngine;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\domain\MailObject.java | 1 |
请完成以下Java代码 | public class Cell
{
public static final Cell NULL = new Cell(null, true);
public static final String NULL_DISPLAY_STRING = "<null>";
@Nullable private final String valueStr;
private final boolean isNull;
private Cell(@Nullable final String valueStr, final boolean isNull)
{
this.valueStr = valueStr;
this.isNull = isNull;
}
@Deprecated
@Override
public String toString()
{
return getAsString();
}
public static Cell ofNullable(@Nullable final Object valueObj)
{
if (valueObj instanceof Cell)
{
return (Cell)valueObj;
}
final String valueStr = valueObj != null ? valueObj.toString() : null;
return valueStr != null
? new Cell(valueStr, false)
: NULL;
} | public String getAsString()
{
return isNull ? NULL_DISPLAY_STRING : valueStr;
}
public int getWidth()
{
return getAsString().length();
}
public boolean isBlank()
{
return isNull || Check.isBlank(valueStr);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Cell.java | 1 |
请完成以下Java代码 | public Batch execute(CommandContext commandContext) {
Collection<String> collectedInstanceIds = collectProcessInstanceIds();
List<AbstractProcessInstanceModificationCommand> instructions = builder.getInstructions();
ensureNotEmpty(BadUserRequestException.class, "Restart instructions cannot be empty",
"instructions", instructions);
ensureNotEmpty(BadUserRequestException.class, "Process instance ids cannot be empty",
"processInstanceIds", collectedInstanceIds);
ensureNotContainsNull(BadUserRequestException.class, "Process instance ids cannot be null",
"processInstanceIds", collectedInstanceIds);
String processDefinitionId = builder.getProcessDefinitionId();
ProcessDefinitionEntity processDefinition =
getProcessDefinition(commandContext, processDefinitionId);
ensureNotNull(BadUserRequestException.class,
"Process definition cannot be null", processDefinition);
ensureTenantAuthorized(commandContext, processDefinition);
String tenantId = processDefinition.getTenantId();
return new BatchBuilder(commandContext)
.type(Batch.TYPE_PROCESS_INSTANCE_RESTART)
.config(getConfiguration(collectedInstanceIds, processDefinition.getDeploymentId()))
.permission(BatchPermissions.CREATE_BATCH_RESTART_PROCESS_INSTANCES)
.tenantId(tenantId) | .operationLogHandler((ctx, instanceCount) ->
writeUserOperationLog(ctx, processDefinition, instanceCount, true))
.build();
}
protected void ensureTenantAuthorized(CommandContext commandContext, ProcessDefinitionEntity processDefinition) {
if (!commandContext.getTenantManager().isAuthenticatedTenant(processDefinition.getTenantId())) {
throw LOG.exceptionCommandWithUnauthorizedTenant("restart process instances of process definition '" + processDefinition.getId() + "'");
}
}
public BatchConfiguration getConfiguration(Collection<String> instanceIds, String deploymentId) {
return new RestartProcessInstancesBatchConfiguration(
new ArrayList<>(instanceIds),
DeploymentMappings.of(new DeploymentMapping(deploymentId, instanceIds.size())),
builder.getInstructions(),
builder.getProcessDefinitionId(),
builder.isInitialVariables(),
builder.isSkipCustomListeners(),
builder.isSkipIoMappings(),
builder.isWithoutBusinessKey());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\RestartProcessInstancesBatchCmd.java | 1 |
请完成以下Java代码 | public void setId(Long id) {
this.id = id;
}
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 Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@PreRemove
private void bookRemove() {
deleted = true;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} | if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootSoftDeletes\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public Date getLastDisabledTime() {
return lastDisabledTime;
}
@Override
public Date getLastStartedTime() {
return lastStartedTime;
}
@Override
public Date getLastSuspendedTime() {
return lastSuspendedTime;
}
@Override
public Date getCompletedTime() {
return completedTime;
}
@Override
public Date getOccurredTime() {
return occurredTime;
}
@Override
public Date getTerminatedTime() {
return terminatedTime;
}
@Override
public Date getExitTime() {
return exitTime;
}
@Override
public Date getEndedTime() {
return endedTime;
}
@Override
public String getStartUserId() {
return startUserId;
}
@Override
public String getAssignee() {
return assignee;
}
@Override
public String getCompletedBy() {
return completedBy;
}
@Override
public String getReferenceId() {
return referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
@Override
public boolean isCompletable() {
return completable;
}
@Override
public String getEntryCriterionId() {
return entryCriterionId; | }
@Override
public String getExitCriterionId() {
return exitCriterionId;
}
@Override
public String getFormKey() {
return formKey;
}
@Override
public String getExtraValue() {
return extraValue;
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
return localVariables;
}
@Override
public PlanItem getPlanItem() {
return planItem;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("planItemDefinitionId='" + planItemDefinitionId + "'")
.add("elementId='" + elementId + "'")
.add("caseInstanceId='" + caseInstanceId + "'")
.add("caseDefinitionId='" + caseDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\ReadOnlyDelegatePlanItemInstanceImpl.java | 1 |
请完成以下Java代码 | public class News {
private Long newsId;
private String newsTitle;
private Long newsCategoryId;
private String newsCoverImage;
private String newsContent;
private Byte newsStatus;
private Long newsViews;
private Byte isDeleted;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private Date updateTime;
public Long getNewsId() {
return newsId;
}
public void setNewsId(Long newsId) {
this.newsId = newsId;
}
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle == null ? null : newsTitle.trim();
}
public Long getNewsCategoryId() {
return newsCategoryId;
}
public void setNewsCategoryId(Long newsCategoryId) {
this.newsCategoryId = newsCategoryId;
}
public String getNewsCoverImage() {
return newsCoverImage;
}
public void setNewsCoverImage(String newsCoverImage) {
this.newsCoverImage = newsCoverImage == null ? null : newsCoverImage.trim();
}
public Byte getNewsStatus() {
return newsStatus;
}
public void setNewsStatus(Byte newsStatus) {
this.newsStatus = newsStatus;
}
public Long getNewsViews() {
return newsViews; | }
public void setNewsViews(Long newsViews) {
this.newsViews = newsViews;
}
public Byte getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", newsId=").append(newsId);
sb.append(", newsTitle=").append(newsTitle);
sb.append(", newsCategoryId=").append(newsCategoryId);
sb.append(", newsCoverImage=").append(newsCoverImage);
sb.append(", newsStatus=").append(newsStatus);
sb.append(", newsViews=").append(newsViews);
sb.append(", isDeleted=").append(isDeleted);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\News.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RetrieveProductsProcessor implements Processor
{
@Override
public void process(@NonNull final Exchange exchange) throws Exception
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
exchange.getIn().setHeader(GetPatientsRouteConstants.HEADER_ORG_CODE, request.getOrgCode());
if (request.getAdPInstanceId() != null)
{
exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue());
}
final String apiKey = request.getParameters().get(ExternalSystemConstants.PARAM_API_KEY);
final String tenant = request.getParameters().get(ExternalSystemConstants.PARAM_TENANT);
final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH);
final AlbertaConnectionDetails albertaConnectionDetails = AlbertaConnectionDetails.builder()
.apiKey(apiKey)
.tenant(tenant)
.basePath(basePath)
.build();
final AlbertaProductApi albertaProductApi = AlbertaProductApi.of(albertaConnectionDetails);
exchange.setProperty(ROUTE_PROPERTY_ALBERTA_PRODUCT_API, albertaProductApi); | exchange.getIn().setBody(buildGetProductsCamelRequest(request));
}
private GetProductsCamelRequest buildGetProductsCamelRequest(@NonNull final JsonExternalSystemRequest request)
{
final String updatedAfter = CoalesceUtil.coalesce(
request.getParameters().get(PARAM_UPDATED_AFTER),
Instant.ofEpochSecond(0).toString());
return GetProductsCamelRequest.builder()
.pInstanceId(request.getAdPInstanceId())
.externalSystemType(ALBERTA_EXTERNAL_SYSTEM_CONFIG_TYPE)
.externalSystemChildConfigValue(request.getParameters().get(ExternalSystemConstants.PARAM_CHILD_CONFIG_VALUE))
.since(updatedAfter)
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\product\processor\RetrieveProductsProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Tracer openTracer(Tracing tracing) {
return BraveTracer.create(tracing);
}
/**
* Allows someone to add tags to a span if a trace is in progress
*/
@Bean
public SpanCustomizer spanCustomizer(Tracing tracing) {
return CurrentSpanCustomizer.create(tracing);
}
// ==================== HTTP 相关 ====================
/**
* Decides how to name and tag spans. By default they are named the same as the http method
*/
@Bean
public HttpTracing httpTracing(Tracing tracing) {
return HttpTracing.create(tracing);
}
/**
* Creates server spans for http requests
*/
@Bean
public Filter tracingFilter(HttpTracing httpTracing) {
return TracingFilter.create(httpTracing);
}
// ==================== SpringMVC 相关 ====================
// @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class)
// ==================== Elasticsearch 相关 ====================
@Bean | public TransportClient elasticsearchClient(Tracer tracer, ElasticsearchProperties elasticsearchProperties) throws Exception {
// 创建 TracingTransportClientFactoryBean 对象
TracingTransportClientFactoryBean factory = new TracingTransportClientFactoryBean(tracer);
// 设置其属性
factory.setClusterNodes(elasticsearchProperties.getClusterNodes());
factory.setProperties(this.createElasticsearch(elasticsearchProperties));
// 创建 TransportClient 对象,并返回
factory.afterPropertiesSet();
return factory.getObject();
}
private Properties createElasticsearch(ElasticsearchProperties elasticsearchProperties) {
Properties properties = new Properties();
properties.put("cluster.name", elasticsearchProperties.getClusterName());
properties.putAll(elasticsearchProperties.getProperties());
return properties;
}
} | repos\SpringBoot-Labs-master\lab-40\lab-40-elasticsearch\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java | 2 |
请完成以下Java代码 | public ProcessEngineException jobExecutorPriorityRangeException(String reason) {
return new ProcessEngineException(exceptionMessage("031", "Invalid configuration for job executor priority range. Reason: {}", reason));
}
public void failedAcquisitionLocks(String processEngine, AcquiredJobs acquiredJobs) {
logDebug("033", "Jobs failed to Lock during Acquisition of jobs for the process engine '{}' : {}", processEngine,
acquiredJobs.getNumberOfJobsFailedToLock());
}
public void jobsToAcquire(String processEngine, int numJobsToAcquire) {
logDebug("034", "Attempting to acquire {} jobs for the process engine '{}'", numJobsToAcquire, processEngine);
}
public void rejectedJobExecutions(String processEngine, int numJobsRejected) {
logDebug("035", "Jobs execution rejections for the process engine '{}' : {}", processEngine, numJobsRejected);
}
public void availableJobExecutionThreads(String processEngine, int numAvailableThreads) {
logDebug("036", "Available job execution threads for the process engine '{}' : {}", processEngine,
numAvailableThreads);
}
public void currentJobExecutions(String processEngine, int numExecutions) {
logDebug("037", "Jobs currently in execution for the process engine '{}' : {}", processEngine, numExecutions);
} | public void numJobsInQueue(String processEngine, int numJobsInQueue, int maxQueueSize) {
logDebug("038",
"Jobs currently in queue to be executed for the process engine '{}' : {} (out of the max queue size : {})",
processEngine, numJobsInQueue, maxQueueSize);
}
public void availableThreadsCalculationError() {
logDebug("039", "Arithmetic exception occurred while computing remaining available thread count for logging.");
}
public void totalQueueCapacityCalculationError() {
logDebug("040", "Arithmetic exception occurred while computing total queue capacity for logging.");
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutorLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDefaultMethod(@Nullable Method defaultMethod) {
this.defaultMethod = defaultMethod;
}
/**
* Set a payload validator.
* @param validator the validator.
* @since 2.5.11
*/
public void setValidator(Validator validator) {
this.validator = validator;
}
@Override
protected HandlerAdapter configureListenerAdapter(MessagingMessageListenerAdapter<K, V> messageListener) {
List<InvocableHandlerMethod> invocableHandlerMethods = new ArrayList<>();
InvocableHandlerMethod defaultHandler = null;
for (Method method : this.methods) { | MessageHandlerMethodFactory messageHandlerMethodFactory = getMessageHandlerMethodFactory();
if (messageHandlerMethodFactory != null) {
InvocableHandlerMethod handler = messageHandlerMethodFactory
.createInvocableHandlerMethod(getBean(), method);
invocableHandlerMethods.add(handler);
if (method.equals(this.defaultMethod)) {
defaultHandler = handler;
}
}
}
DelegatingInvocableHandler delegatingHandler = new DelegatingInvocableHandler(invocableHandlerMethods,
defaultHandler, getBean(), getResolver(), getBeanExpressionContext(), getBeanFactory(), this.validator);
return new HandlerAdapter(delegatingHandler);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\MultiMethodKafkaListenerEndpoint.java | 2 |
请完成以下Java代码 | public Integer getEnabled() {
return enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() { | return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
} | repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\model\UserInfo.java | 1 |
请完成以下Java代码 | private POSProductsSearchResult searchByUPCorValue()
{
if (queryString == null)
{
return null;
}
final ProductId productId = productBL.getProductIdByBarcode(queryString, ClientId.METASFRESH).orElse(null);
final POSProduct product = getPOSProduct(productId);
if (product == null)
{
return null;
}
return POSProductsSearchResult.ofBarcodeMatchedProduct(product);
}
@Nullable
private POSProduct getPOSProduct(@Nullable final ProductId productId)
{
if (productId == null)
{
return null;
}
final List<POSProduct> products = loader.load(evalDate, InSetPredicate.only(productId));
if (products.size() != 1)
{
return null;
}
return products.get(0);
}
@Nullable
private POSProductsSearchResult searchByValueName() | {
if (queryString == null)
{
return null;
}
final Set<ProductId> productIds = productBL.getProductIdsMatchingQueryString(queryString, ClientId.METASFRESH, QueryLimit.ONE_HUNDRED);
return POSProductsSearchResult.ofList(loader.load(evalDate, InSetPredicate.only(productIds)));
}
@NonNull
private POSProductsSearchResult allProducts()
{
return POSProductsSearchResult.ofList(loader.load(evalDate, InSetPredicate.any()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSProductsSearchCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected RuleChain saveOrUpdate(EntitiesImportCtx ctx, RuleChain ruleChain, RuleChainExportData exportData, IdProvider idProvider, CompareResult compareResult) {
ruleChain = ruleChainService.saveRuleChain(ruleChain);
if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) {
exportData.getMetaData().setRuleChainId(ruleChain.getId());
ruleChainService.saveRuleChainMetaData(ctx.getTenantId(), exportData.getMetaData(), tbRuleChainService::updateRuleNodeConfiguration);
return ruleChainService.findRuleChainById(ctx.getTenantId(), ruleChain.getId());
} else {
return ruleChain;
}
}
@Override
protected boolean isUpdateNeeded(EntitiesImportCtx ctx, RuleChainExportData exportData, RuleChain prepared, RuleChain existing) {
boolean updateNeeded = super.isUpdateNeeded(ctx, exportData, prepared, existing);
if (!updateNeeded) {
RuleChainMetaData newMD = exportData.getMetaData();
RuleChainMetaData existingMD = ruleChainService.loadRuleChainMetaData(ctx.getTenantId(), prepared.getId());
existingMD.setRuleChainId(null);
updateNeeded = !newMD.equals(existingMD);
} | return updateNeeded;
}
@Override
protected void onEntitySaved(User user, RuleChain savedRuleChain, RuleChain oldRuleChain) {
entityActionService.logEntityAction(user, savedRuleChain.getId(), savedRuleChain, null,
oldRuleChain == null ? ActionType.ADDED : ActionType.UPDATED, null);
}
@Override
protected RuleChain deepCopy(RuleChain ruleChain) {
return new RuleChain(ruleChain);
}
@Override
public EntityType getEntityType() {
return EntityType.RULE_CHAIN;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\RuleChainImportService.java | 2 |
请完成以下Java代码 | public String getCaseDefinitionName() {
return caseDefinitionName;
}
public Date getCreateTime() {
return createTime;
}
public Date getCloseTime() {
return closeTime;
}
public Long getDurationInMillis() {
return durationInMillis;
}
public String getCreateUserId() {
return createUserId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getTenantId() {
return tenantId;
}
public Boolean getActive() {
return active;
}
public Boolean getCompleted() {
return completed;
}
public Boolean getTerminated() {
return terminated; | }
public Boolean getClosed() {
return closed;
}
public static HistoricCaseInstanceDto fromHistoricCaseInstance(HistoricCaseInstance historicCaseInstance) {
HistoricCaseInstanceDto dto = new HistoricCaseInstanceDto();
dto.id = historicCaseInstance.getId();
dto.businessKey = historicCaseInstance.getBusinessKey();
dto.caseDefinitionId = historicCaseInstance.getCaseDefinitionId();
dto.caseDefinitionKey = historicCaseInstance.getCaseDefinitionKey();
dto.caseDefinitionName = historicCaseInstance.getCaseDefinitionName();
dto.createTime = historicCaseInstance.getCreateTime();
dto.closeTime = historicCaseInstance.getCloseTime();
dto.durationInMillis = historicCaseInstance.getDurationInMillis();
dto.createUserId = historicCaseInstance.getCreateUserId();
dto.superCaseInstanceId = historicCaseInstance.getSuperCaseInstanceId();
dto.superProcessInstanceId = historicCaseInstance.getSuperProcessInstanceId();
dto.tenantId = historicCaseInstance.getTenantId();
dto.active = historicCaseInstance.isActive();
dto.completed = historicCaseInstance.isCompleted();
dto.terminated = historicCaseInstance.isTerminated();
dto.closed = historicCaseInstance.isClosed();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseInstanceDto.java | 1 |
请完成以下Java代码 | public static User createWithLoggedInstantiationTime(String name, String email, String country) {
LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
return new User(name, email, country);
}
public static User getSingletonInstance(String name, String email, String country) {
if (instance == null) {
synchronized (User.class) {
if (instance == null) {
instance = new User(name, email, country);
}
}
}
return instance;
}
private User(String name, String email, String country) {
this.name = name; | this.email = email;
this.country = country;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
} | repos\tutorials-master\patterns-modules\design-patterns-creational-2\src\main\java\com\baeldung\constructorsstaticfactorymethods\entities\User.java | 1 |
请完成以下Java代码 | public String toString() {
return "Dispense{" +
"id=" + id +
", productName='" + productName + '\'' +
", price=" + price +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product dispense = (Product) o;
return Objects.equals(id, dispense.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) { | this.productName = productName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public CustomerOrder getCustomerOrder() {
return customerOrder;
}
public void setCustomerOrder(CustomerOrder co) {
this.customerOrder = co;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="customerorder_id", nullable = false)
private CustomerOrder customerOrder;
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Product.java | 1 |
请完成以下Java代码 | private static InvoiceAcctRule toRule(final I_C_Invoice_Acct record)
{
return InvoiceAcctRule.builder()
.matcher(toRuleMatcher(record))
.elementValueId(ElementValueId.ofRepoId(record.getC_ElementValue_ID()))
.build();
}
private static InvoiceAcctRuleMatcher toRuleMatcher(final I_C_Invoice_Acct record)
{
return InvoiceAcctRuleMatcher.builder()
.invoiceAndLineId(InvoiceAndLineId.ofRepoIdOrNull(record.getC_Invoice_ID(), record.getC_InvoiceLine_ID()))
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.accountConceptualName(AccountConceptualName.ofNullableString(record.getAccountName()))
.build();
}
public void save(@NonNull final InvoiceAcct invoiceAcct)
{
//
// Delete previous records
queryBL.createQueryBuilder(I_C_Invoice_Acct.class)
.addEqualsFilter(I_C_Invoice_Acct.COLUMNNAME_C_Invoice_ID, invoiceAcct.getInvoiceId())
.create()
.delete(); | //
// Save new
for (final InvoiceAcctRule rule : invoiceAcct.getRulesOrdered())
{
final I_C_Invoice_Acct record = InterfaceWrapperHelper.newInstance(I_C_Invoice_Acct.class);
record.setC_Invoice_ID(invoiceAcct.getInvoiceId().getRepoId());
record.setAD_Org_ID(invoiceAcct.getOrgId().getRepoId());
updateRecordFromRule(record, rule);
InterfaceWrapperHelper.save(record);
}
}
private void updateRecordFromRule(@NonNull final I_C_Invoice_Acct record, @NonNull final InvoiceAcctRule from)
{
updateRecordFromRuleMatcher(record, from.getMatcher());
record.setC_ElementValue_ID(from.getElementValueId().getRepoId());
}
private void updateRecordFromRuleMatcher(@NonNull final I_C_Invoice_Acct record, @NonNull final InvoiceAcctRuleMatcher from)
{
record.setC_AcctSchema_ID(from.getAcctSchemaId().getRepoId());
record.setC_InvoiceLine_ID(InvoiceAndLineId.toRepoId(from.getInvoiceAndLineId()));
record.setAccountName(from.getAccountConceptualName() != null ? from.getAccountConceptualName().getAsString() : null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\acct\InvoiceAcctRepository.java | 1 |
请完成以下Java代码 | public void parseConfiguration(Element activityElement, DeploymentEntity deployment, ProcessDefinitionEntity processDefinition, BpmnParse bpmnParse) {
// should not be called!
}
protected <T> T performContextSwitch(final Callable<T> callable) {
ProcessApplicationReference targetProcessApplication = ProcessApplicationContextUtil.getTargetProcessApplication(deploymentId);
if(targetProcessApplication != null) {
return Context.executeWithinProcessApplication(new Callable<T>() {
public T call() throws Exception {
return doCall(callable);
}
}, targetProcessApplication);
} else {
return doCall(callable);
}
}
protected <T> T doCall(Callable<T> callable) {
try {
return callable.call();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ProcessEngineException(e); | }
}
public void submitFormVariables(final VariableMap properties, final VariableScope variableScope) {
performContextSwitch(new Callable<Void> () {
public Void call() throws Exception {
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new SubmitFormVariablesInvocation(formHandler, properties, variableScope));
return null;
}
});
}
public abstract FormHandler getFormHandler();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\DelegateFormHandler.java | 1 |
请完成以下Java代码 | public Mono<Void> save(Mono<RouteDefinition> route) {
return route.flatMap(routeDefinition -> {
Objects.requireNonNull(routeDefinition.getId(), "id may not be null");
return routeDefinitionReactiveValueOperations.set(createKey(routeDefinition.getId()), routeDefinition)
.flatMap(success -> {
if (success) {
return Mono.empty();
}
return Mono.defer(() -> Mono.error(new RuntimeException(
String.format("Could not add route to redis repository: %s", routeDefinition))));
});
});
}
@Override | public Mono<Void> delete(Mono<String> routeId) {
return routeId.flatMap(id -> routeDefinitionReactiveValueOperations.delete(createKey(id)).flatMap(success -> {
if (success) {
return Mono.empty();
}
return Mono.defer(() -> Mono.error(new NotFoundException(
String.format("Could not remove route from redis repository with id: %s", routeId))));
}));
}
private String createKey(String routeId) {
return ROUTEDEFINITION_REDIS_KEY_PREFIX_QUERY + routeId;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RedisRouteDefinitionRepository.java | 1 |
请完成以下Java代码 | private final Constructor<?> findIDConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{
return modelClass.getDeclaredConstructor(new Class[] { Properties.class, int.class, String.class });
}
public Constructor<?> getIDConstructor(final Class<?> modelClass)
{
try
{
return class2idConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ID constructor for " + modelClass, e);
}
}
private final Constructor<?> findResultSetConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{ | return modelClass.getDeclaredConstructor(new Class[] { Properties.class, ResultSet.class, String.class });
}
public Constructor<?> getResultSetConstructor(final Class<?> modelClass)
{
try
{
return class2resultSetConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ResultSet constructor for " + modelClass, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\TableModelClassLoader.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
} | public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\entitygraph\model\Post.java | 1 |
请完成以下Java代码 | private static void appendPdfPages(@NonNull final PdfCopy copyDestination, @NonNull final PdfDataProvider pdfData) throws IOException, BadPdfFormatException
{
final Resource data = pdfData.getPdfData();
final PdfReader pdfReader = new PdfReader(data.getInputStream());
for (int page = 0; page < pdfReader.getNumberOfPages(); )
{
copyDestination.addPage(copyDestination.getImportedPage(pdfReader, ++page));
}
copyDestination.freeReader(pdfReader);
pdfReader.close();
}
@Value | public static class PdfDataProvider
{
public static PdfDataProvider forData(@NonNull final Resource pdfData)
{
return new PdfDataProvider(pdfData);
}
Resource pdfData;
private PdfDataProvider(@NonNull final Resource pdfData)
{
this.pdfData = pdfData;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ExecuteReportStrategyUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addQueueTask(String url) {
blockingQueue.add(url);
}
@Override
public String takeQueueTask() throws InterruptedException {
return blockingQueue.take();
}
@SuppressWarnings("unchecked")
private Map<String, Integer> getPdfImageCaches() {
Map<String, Integer> map = new HashMap<>();
try {
map = (Map<String, Integer>) toObject(db.get(FILE_PREVIEW_PDF_IMGS_KEY.getBytes()));
} catch (RocksDBException | IOException | ClassNotFoundException e) {
LOGGER.error("Get from RocksDB Exception" + e);
}
return map;
}
private byte[] toByteArray(Object obj) throws IOException {
byte[] bytes;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
return bytes;
}
private Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close(); | return obj;
}
private void cleanPdfCache() throws IOException, RocksDBException {
Map<String, String> initPDFCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache));
}
private void cleanImgCache() throws IOException, RocksDBException {
Map<String, List<String>> initIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache));
}
private void cleanPdfImgCache() throws IOException, RocksDBException {
Map<String, Integer> initPDFIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache));
}
private void cleanMediaConvertCache() throws IOException, RocksDBException {
Map<String, String> initMediaConvertCache = new HashMap<>();
db.put(FILE_PREVIEW_MEDIA_CONVERT_KEY.getBytes(), toByteArray(initMediaConvertCache));
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRocksDBImpl.java | 2 |
请完成以下Java代码 | public int getDataEntry_ListValue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_ListValue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
} | /** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_ListValue.java | 1 |
请完成以下Java代码 | public Map<String, Object> defaults() {
Map<String, Object> defaults = new LinkedHashMap<>();
defaults.put("type", defaultId(this.types));
defaults.put("bootVersion", defaultId(this.bootVersions));
defaults.put("packaging", defaultId(this.packagings));
defaults.put("javaVersion", defaultId(this.javaVersions));
defaults.put("language", defaultId(this.languages));
defaults.put("configurationFileFormat", defaultId(this.configurationFileFormats));
defaults.put("groupId", this.groupId.getContent());
defaults.put("artifactId", this.artifactId.getContent());
defaults.put("version", this.version.getContent());
defaults.put("name", this.name.getContent());
defaults.put("description", this.description.getContent());
defaults.put("packageName", this.packageName.getContent());
return defaults;
}
private static String defaultId(Defaultable<? extends DefaultMetadataElement> element) {
DefaultMetadataElement defaultValue = element.getDefault();
return (defaultValue != null) ? defaultValue.getId() : null;
}
private static class ArtifactIdCapability extends TextCapability {
private final TextCapability nameCapability;
ArtifactIdCapability(TextCapability nameCapability) {
super("artifactId", "Artifact", "project coordinates (infer archive name)");
this.nameCapability = nameCapability;
}
@Override
public String getContent() {
String value = super.getContent();
return (value != null) ? value : this.nameCapability.getContent();
}
}
private static class PackageCapability extends TextCapability { | private final TextCapability groupId;
private final TextCapability artifactId;
PackageCapability(TextCapability groupId, TextCapability artifactId) {
super("packageName", "Package Name", "root package");
this.groupId = groupId;
this.artifactId = artifactId;
}
@Override
public String getContent() {
String value = super.getContent();
if (value != null) {
return value;
}
else if (this.groupId.getContent() != null && this.artifactId.getContent() != null) {
return InitializrConfiguration
.cleanPackageName(this.groupId.getContent() + "." + this.artifactId.getContent());
}
return null;
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrMetadata.java | 1 |
请完成以下Java代码 | public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
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;
}
@Override
public org.compiere.model.I_M_RMA getRef_RMA() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Ref_RMA_ID, org.compiere.model.I_M_RMA.class);
}
@Override
public void setRef_RMA(org.compiere.model.I_M_RMA Ref_RMA)
{
set_ValueFromPO(COLUMNNAME_Ref_RMA_ID, org.compiere.model.I_M_RMA.class, Ref_RMA);
}
/** Set Referenced RMA.
@param Ref_RMA_ID Referenced RMA */
@Override
public void setRef_RMA_ID (int Ref_RMA_ID)
{
if (Ref_RMA_ID < 1)
set_Value (COLUMNNAME_Ref_RMA_ID, null);
else
set_Value (COLUMNNAME_Ref_RMA_ID, Integer.valueOf(Ref_RMA_ID));
}
/** Get Referenced RMA.
@return Referenced RMA */
@Override
public int getRef_RMA_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_RMA_ID); | if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Vertriebsbeauftragter.
@param SalesRep_ID
Sales Representative or Company Agent
*/
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Vertriebsbeauftragter.
@return Sales Representative or Company Agent
*/
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_M_RMA.java | 1 |
请完成以下Java代码 | private void createAndFireEventWithStatus(
@NonNull final I_C_Queue_WorkPackage workPackage,
@NonNull final Status status)
{
final UUID correlationId = extractCorrelationIdOrNull();
if (correlationId == null)
{
return; // nothing to do
}
final WorkpackageProcessedEvent processingDoneEvent = WorkpackageProcessedEvent.builder()
.correlationId(correlationId)
.workPackageId(QueueWorkPackageId.ofRepoId(workPackage.getC_Queue_WorkPackage_ID()))
.status(status)
.build();
eventBusFactory.getEventBus(Async_Constants.WORKPACKAGE_LIFECYCLE_TOPIC).enqueueObject(processingDoneEvent);
}
private void notifyErrorAfterCommit(final I_C_Queue_WorkPackage workpackage, final AdempiereException ex)
{
final UserId userInChargeId = workpackage.getAD_User_InCharge_ID() > 0 ? UserId.ofRepoId(workpackage.getAD_User_InCharge_ID()) : null;
if (userInChargeId == null)
{
return;
}
if (ex.isUserNotified())
{
return;
}
ex.markUserNotified();
final String errorMsg = ex.getLocalizedMessage();
final int workpackageId = workpackage.getC_Queue_WorkPackage_ID();
final INotificationBL notificationBL = Services.get(INotificationBL.class);
notificationBL.sendAfterCommit(UserNotificationRequest.builder()
.topic(Async_Constants.WORKPACKAGE_ERROR_USER_NOTIFICATIONS_TOPIC)
.recipientUserId(userInChargeId)
.contentADMessage(MSG_PROCESSING_ERROR_NOTIFICATION_TEXT)
.contentADMessageParam(workpackageId)
.contentADMessageParam(errorMsg)
.targetAction(TargetRecordAction.of(I_C_Queue_WorkPackage.Table_Name, workpackageId))
.build());
} | /**
* Extracts the {@link IWorkpackageSkipRequest} from given exception
*
* @return {@link IWorkpackageSkipRequest} or null
*/
@Nullable
private static IWorkpackageSkipRequest getWorkpackageSkipRequest(final Throwable ex)
{
if (ex instanceof IWorkpackageSkipRequest)
{
final IWorkpackageSkipRequest skipRequest = (IWorkpackageSkipRequest)ex;
if (!skipRequest.isSkip())
{
return null;
}
return skipRequest;
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageProcessorTask.java | 1 |
请完成以下Java代码 | public static void givenStack_whenUsingDirectForEach_thenPrintStack() {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.forEach(element -> System.out.println(element));
}
public static void givenStack_whenUsingStreamReverse_thenPrintStack() {
Stack<Integer> stack = new Stack<>();
stack.push(20);
stack.push(10);
stack.push(30);
Collections.reverse(stack);
stack.forEach(System.out::println);
}
public static void givenStack_whenUsingIterator_thenPrintStack() {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
Iterator<Integer> iterator = stack.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
public static void givenStack_whenUsingListIteratorReverseOrder_thenPrintStack() {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30); | ListIterator<Integer> iterator = stack.listIterator(stack.size());
while (iterator.hasPrevious()) {
System.out.print(iterator.previous() + " ");
}
}
public static void givenStack_whenUsingDeque_thenPrintStack() {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.forEach(e -> System.out.print(e + " "));
}
} | repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\PrintStack.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static Map<String, Map<String, Object>> toMap() {
WeiXinTradeTypeEnum[] ary = WeiXinTradeTypeEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = ary[num].name();
map.put("desc", ary[num].getDesc());
enumMap.put(key, map);
}
return enumMap;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList() {
WeiXinTradeTypeEnum[] ary = WeiXinTradeTypeEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
list.add(map);
}
return list; | }
public static WeiXinTradeTypeEnum getEnum(String name) {
WeiXinTradeTypeEnum[] arry = WeiXinTradeTypeEnum.values();
for (int i = 0; i < arry.length; i++) {
if (arry[i].name().equalsIgnoreCase(name)) {
return arry[i];
}
}
return null;
}
/**
* 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
WeiXinTradeTypeEnum[] enums = WeiXinTradeTypeEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (WeiXinTradeTypeEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\enums\weixinpay\WeiXinTradeTypeEnum.java | 2 |
请完成以下Java代码 | protected void logCaseDefinitionRegistrations(StringBuilder builder, List<CaseDefinition> caseDefinitions) {
if(caseDefinitions.isEmpty()) {
builder.append("Deployment does not provide any case definitions.");
} else {
builder.append("\n");
builder.append("Will execute case definitions ");
builder.append("\n");
for (CaseDefinition caseDefinition : caseDefinitions) {
builder.append("\n");
builder.append(" ");
builder.append(caseDefinition.getKey());
builder.append("[version: ");
builder.append(caseDefinition.getVersion());
builder.append(", id: ");
builder.append(caseDefinition.getId());
builder.append("]");
}
builder.append("\n");
}
} | public String getRegistrationSummary() {
StringBuilder builder = new StringBuilder();
for (Entry<String, DefaultProcessApplicationRegistration> entry : registrationsByDeploymentId.entrySet()) {
if(builder.length()>0) {
builder.append(", ");
}
builder.append(entry.getKey());
builder.append("->");
builder.append(entry.getValue().getReference().getName());
}
return builder.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\application\ProcessApplicationManager.java | 1 |
请完成以下Java代码 | public void processEvent(EdqsEvent event) {
if (event.getEventType() == EdqsEventType.DELETED && event.getObjectType() == ObjectType.TENANT) {
log.info("Tenant {} deleted", event.getTenantId());
repos.remove(event.getTenantId());
statsService.reportRemoved(ObjectType.TENANT);
} else {
get(event.getTenantId()).processEvent(event);
}
}
@Override
public long countEntitiesByQuery(TenantId tenantId, CustomerId customerId, EntityCountQuery query, boolean ignorePermissionCheck) {
long startNs = System.nanoTime();
long result = get(tenantId).countEntitiesByQuery(customerId, query, ignorePermissionCheck);
statsService.reportEdqsCountQuery(tenantId, query, System.nanoTime() - startNs);
return result;
}
@Override | public PageData<QueryResult> findEntityDataByQuery(TenantId tenantId, CustomerId customerId,
EntityDataQuery query, boolean ignorePermissionCheck) {
long startNs = System.nanoTime();
var result = get(tenantId).findEntityDataByQuery(customerId, query, ignorePermissionCheck);
statsService.reportEdqsDataQuery(tenantId, query, System.nanoTime() - startNs);
return result;
}
@Override
public void clearIf(Predicate<TenantId> predicate) {
repos.keySet().removeIf(predicate);
}
@Override
public void clear() {
repos.clear();
}
} | repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\repo\DefaultEdqsRepository.java | 1 |
请完成以下Java代码 | public String getActiveConsole() {
return activeConsole;
}
public Date getLastFetch() {
return lastFetch;
}
public void setLastFetch(Date lastFetch) {
this.lastFetch = lastFetch;
}
public void setActiveConsole(String activeConsole) {
this.activeConsole = activeConsole;
}
public AppInfo toAppInfo() { | return new AppInfo(app, appType);
}
@Override
public String toString() {
return "ApplicationEntity{" +
"id=" + id +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", activeConsole='" + activeConsole + '\'' +
", lastFetch=" + lastFetch +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\ApplicationEntity.java | 1 |
请完成以下Java代码 | public void setAD_BoilerPlate(I_C_Letter letter, I_AD_BoilerPlate textTemplate)
{
letter.setAD_BoilerPlate(textTemplate);
if (textTemplate != null)
{
letter.setLetterSubject(textTemplate.getSubject());
letter.setLetterBody(textTemplate.getTextSnippet());
}
}
@Override
public boolean canUpdate(final I_AD_BoilerPlate textTemplate)
{
if (textTemplate == null)
{
return false;
}
final Properties ctx = InterfaceWrapperHelper.getCtx(textTemplate);
final ClientId adClientId = ClientId.ofRepoId(textTemplate.getAD_Client_ID());
final OrgId adOrgId = OrgId.ofRepoId(textTemplate.getAD_Org_ID());
final int tableId = InterfaceWrapperHelper.getTableId(I_AD_BoilerPlate.class);
final int recordId = textTemplate.getAD_BoilerPlate_ID();
final boolean createError = false;
final boolean rw = Env.getUserRolePermissions(ctx).canUpdate(adClientId, adOrgId, tableId, recordId, createError);
return rw;
}
@Override
public <T> void createLetters(Iterator<T> source, ILetterProducer<T> producer)
{
while (source.hasNext())
{
final T item = source.next();
createLetter(item, producer);
}
}
@Override
public <T> I_C_Letter createLetter(final T item, final ILetterProducer<T> producer)
{
DB.saveConstraints();
DB.getConstraints().addAllowedTrxNamePrefix("POSave");
try
{
final Properties ctx = InterfaceWrapperHelper.getCtx(item);
// NOTE: we are working out of trx because we want to produce the letters one by one and build a huge transaction
final String trxName = ITrx.TRXNAME_None;
final I_C_Letter letter = InterfaceWrapperHelper.create(ctx, I_C_Letter.class, trxName);
if (!producer.createLetter(letter, item))
{
return null;
}
setLocationContactAndOrg(letter);
final int boilerPlateID = producer.getBoilerplateID(item);
if (boilerPlateID <= 0)
{
logger.warn("No default text template for org {}", letter.getAD_Org_ID());
return null;
} | final I_AD_BoilerPlate textTemplate = InterfaceWrapperHelper.create(ctx, boilerPlateID, I_AD_BoilerPlate.class, trxName);
setAD_BoilerPlate(letter, textTemplate);
final BoilerPlateContext attributes = producer.createAttributes(item);
setLetterBodyParsed(letter, attributes);
// 04238 : We need to flag the letter for enqueue.
letter.setIsMembershipBadgeToPrint(true);
// mo73_05916 : Add record and table ID
letter.setAD_Table_ID(InterfaceWrapperHelper.getModelTableId(item));
letter.setRecord_ID(InterfaceWrapperHelper.getId(item));
InterfaceWrapperHelper.save(letter);
return letter;
}
finally
{
DB.restoreConstraints();
}
}
@Override
public I_AD_BoilerPlate getById(int boilerPlateId)
{
return loadOutOfTrx(boilerPlateId, I_AD_BoilerPlate.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\api\impl\TextTemplateBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ApiWebSecurityConfigurationAdapter {
@Bean
@Order(99)
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
PathPatternRequestMatcher.Builder pathMatcherBuilder = PathPatternRequestMatcher.withDefaults().basePath("/process-api");
http
.securityMatcher(pathMatcherBuilder.matcher("/**"))
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
.requestMatchers(pathMatcherBuilder.matcher("/repository/**")).hasAnyAuthority("repository-privilege")
.requestMatchers(pathMatcherBuilder.matcher("/management/**")).hasAnyAuthority("management-privilege")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
} | }
@Bean
@ConditionalOnBean(InMemoryDirectoryServer.class)
public CommandLineRunner initializePrivileges(IdmIdentityService idmIdentityService) {
return args -> {
Privilege repositoryPrivilege = idmIdentityService.createPrivilege("repository-privilege");
Privilege managementPrivilege = idmIdentityService.createPrivilege("management-privilege");
idmIdentityService.addGroupPrivilegeMapping(repositoryPrivilege.getId(), "user");
idmIdentityService.addGroupPrivilegeMapping(managementPrivilege.getId(), "admin");
idmIdentityService.addUserPrivilegeMapping(managementPrivilege.getId(), "fozzie");
};
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-ldap\src\main\java\flowable\SampleLdapApplication.java | 2 |
请完成以下Java代码 | public void setCode (java.lang.String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validierungscode.
@return Validierungscode
*/
@Override
public java.lang.String getCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_Code);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** 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);
}
/**
* Type AD_Reference_ID=540533
* Reference name: C_Aggregation_Attribute_Type
*/
public static final int TYPE_AD_Reference_ID=540533;
/** Attribute = A */
public static final String TYPE_Attribute = "A";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_Aggregation_Attribute.java | 1 |
请完成以下Java代码 | public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
// compare
public static int compareByNameThenAge(final Human lhs, final Human rhs) {
if (lhs.name.equals(rhs.name)) {
return Integer.compare(lhs.age, rhs.age);
} else {
return lhs.name.compareTo(rhs.name);
}
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
} | if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Human other = (Human) obj;
if (age != other.age) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Human [name=").append(name).append(", age=").append(age).append("]");
return builder.toString();
}
} | repos\tutorials-master\core-java-modules\core-java-lambdas\src\main\java\com\baeldung\java8\entity\Human.java | 1 |
请完成以下Java代码 | public ReactiveAuthenticationManager employeesAuthenticationManager() {
return authentication -> employee(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication
.getPrincipal()
.toString())))
.map(
b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
)
);
}
public Mono<String> customer(Authentication authentication) {
return Mono.justOrEmpty(authentication
.getPrincipal() | .toString()
.startsWith("customer") ? authentication
.getPrincipal()
.toString() : null);
}
public Mono<String> employee(Authentication authentication) {
return Mono.justOrEmpty(authentication
.getPrincipal()
.toString()
.startsWith("employee") ? authentication
.getPrincipal()
.toString() : null);
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-security\src\main\java\com\baeldung\reactive\authresolver\CustomWebSecurityConfig.java | 1 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Preis.
@param Price
Preis
*/
@Override
public void setPrice (java.math.BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
/** Get Preis.
@return Preis
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
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 Produktschlüssel.
@param ProductValue
Schlüssel des Produktes
*/
@Override
public void setProductValue (java.lang.String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
/** Get Produktschlüssel.
@return Schlüssel des Produktes
*/
@Override
public java.lang.String getProductValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Menge.
@param Qty | Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Anfangsdatum.
@param StartDate
First effective day (inclusive)
*/
@Override
public void setStartDate (java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Anfangsdatum.
@return First effective day (inclusive)
*/
@Override
public java.sql.Timestamp getStartDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_I_Flatrate_Term.java | 1 |
请完成以下Java代码 | public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
AcquirableJobEntity other = (AcquirableJobEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", duedate=" + duedate
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AcquirableJobEntity.java | 1 |
请完成以下Java代码 | public Float getSurfacearea() {
return surfacearea;
}
public void setSurfacearea(Float surfacearea) {
this.surfacearea = surfacearea;
}
public Short getIndepyear() {
return indepyear;
}
public void setIndepyear(Short indepyear) {
this.indepyear = indepyear;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public Float getLifeexpectancy() {
return lifeexpectancy;
}
public void setLifeexpectancy(Float lifeexpectancy) {
this.lifeexpectancy = lifeexpectancy;
}
public Float getGnp() {
return gnp;
}
public void setGnp(Float gnp) {
this.gnp = gnp;
}
public Float getGnpold() {
return gnpold;
}
public void setGnpold(Float gnpold) {
this.gnpold = gnpold;
}
public String getLocalname() {
return localname;
}
public void setLocalname(String localname) {
this.localname = localname == null ? null : localname.trim();
} | public String getGovernmentform() {
return governmentform;
}
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform == null ? null : governmentform.trim();
}
public String getHeadofstate() {
return headofstate;
}
public void setHeadofstate(String headofstate) {
this.headofstate = headofstate == null ? null : headofstate.trim();
}
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2 == null ? null : code2.trim();
}
} | repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java | 1 |
请完成以下Java代码 | public long executeCount(CommandContext commandContext) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getVariableInstanceManager()
.findVariableInstanceCountByQueryCriteria(this);
}
@Override
public List<VariableInstance> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
List<VariableInstance> result = commandContext
.getVariableInstanceManager()
.findVariableInstanceByQueryCriteria(this, page);
if (result == null) {
return result;
}
// iterate over the result array to initialize the value and serialized value of the variable
for (VariableInstance variableInstance : result) {
VariableInstanceEntity variableInstanceEntity = (VariableInstanceEntity) variableInstance;
if (shouldFetchValue(variableInstanceEntity)) {
try {
variableInstanceEntity.getTypedValue(isCustomObjectDeserializationEnabled);
} catch(Exception t) {
// do not fail if one of the variables fails to load
LOG.exceptionWhileGettingValueForVariable(t);
}
}
}
return result;
}
protected boolean shouldFetchValue(VariableInstanceEntity entity) {
// do not fetch values for byte arrays eagerly (unless requested by the user)
return isByteArrayFetchingEnabled
|| !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entity.getSerializer().getType().getName());
}
// getters ////////////////////////////////////////////////////
public String getVariableId() {
return variableId;
}
public String getVariableName() {
return variableName;
}
public String[] getVariableNames() {
return variableNames;
} | public String getVariableNameLike() {
return variableNameLike;
}
public String[] getExecutionIds() {
return executionIds;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public String[] getCaseExecutionIds() {
return caseExecutionIds;
}
public String[] getCaseInstanceIds() {
return caseInstanceIds;
}
public String[] getTaskIds() {
return taskIds;
}
public String[] getBatchIds() {
return batchIds;
}
public String[] getVariableScopeIds() {
return variableScopeIds;
}
public String[] getActivityInstanceIds() {
return activityInstanceIds;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\VariableInstanceQueryImpl.java | 1 |
请完成以下Java代码 | Properties getCtx()
{
return ctx;
}
public ClientId getClientId()
{
return Env.getClientId(getCtx());
}
public OrgId getOrgId()
{
return Env.getOrgId(getCtx());
}
public String getOrgName()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_Org_Name);
}
public UserId getLoggedUserId()
{
return Env.getLoggedUserId(getCtx());
}
public Optional<UserId> getLoggedUserIdIfExists()
{
return Env.getLoggedUserIdIfExists(getCtx());
}
public RoleId getLoggedRoleId()
{
return Env.getLoggedRoleId(getCtx());
}
public String getUserName()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_User_Name);
}
public String getRoleName()
{ | return Env.getContext(getCtx(), Env.CTXNAME_AD_Role_Name);
}
String getAdLanguage()
{
return Env.getContext(getCtx(), Env.CTXNAME_AD_Language);
}
Language getLanguage()
{
return Env.getLanguage(getCtx());
}
/**
* @return previous language
*/
String verifyLanguageAndSet(final Language lang)
{
final Properties ctx = getCtx();
final String adLanguageOld = Env.getContext(ctx, Env.CTXNAME_AD_Language);
//
// Check the language (and update it if needed)
final Language validLang = Env.verifyLanguageFallbackToBase(lang);
//
// Actual update
final String adLanguageNew = validLang.getAD_Language();
Env.setContext(ctx, Env.CTXNAME_AD_Language, adLanguageNew);
this.locale = validLang.getLocale();
UserSession.logger.debug("Changed AD_Language: {} -> {}, {}", adLanguageOld, adLanguageNew, validLang);
return adLanguageOld;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\InternalUserSessionData.java | 1 |
请完成以下Java代码 | public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
qrCodeSettingsDao.removeByTenantId(tenantId);
}
@TransactionalEventListener(classes = QrCodeSettingsEvictEvent.class)
@Override
public void handleEvictEvent(QrCodeSettingsEvictEvent event) {
cache.evict(event.getTenantId());
}
private QrCodeSettings constructMobileAppSettings(QrCodeSettings qrCodeSettings) {
if (qrCodeSettings == null) {
qrCodeSettings = new QrCodeSettings();
qrCodeSettings.setUseDefaultApp(true);
qrCodeSettings.setAndroidEnabled(true);
qrCodeSettings.setIosEnabled(true);
QRCodeConfig qrCodeConfig = QRCodeConfig.builder()
.showOnHomePage(true)
.qrCodeLabelEnabled(true)
.qrCodeLabel(DEFAULT_QR_CODE_LABEL)
.badgeEnabled(true) | .badgePosition(BadgePosition.RIGHT)
.badgeEnabled(true)
.build();
qrCodeSettings.setQrCodeConfig(qrCodeConfig);
qrCodeSettings.setMobileAppBundleId(qrCodeSettings.getMobileAppBundleId());
}
if (qrCodeSettings.isUseDefaultApp() || qrCodeSettings.getMobileAppBundleId() == null) {
qrCodeSettings.setGooglePlayLink(googlePlayLink);
qrCodeSettings.setAppStoreLink(appStoreLink);
} else {
MobileApp androidApp = mobileAppService.findByBundleIdAndPlatformType(qrCodeSettings.getTenantId(), qrCodeSettings.getMobileAppBundleId(), ANDROID);
MobileApp iosApp = mobileAppService.findByBundleIdAndPlatformType(qrCodeSettings.getTenantId(), qrCodeSettings.getMobileAppBundleId(), IOS);
if (androidApp != null && androidApp.getStoreInfo() != null) {
qrCodeSettings.setGooglePlayLink(androidApp.getStoreInfo().getStoreLink());
}
if (iosApp != null && iosApp.getStoreInfo() != null) {
qrCodeSettings.setAppStoreLink(iosApp.getStoreInfo().getStoreLink());
}
}
return qrCodeSettings;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\QrCodeSettingServiceImpl.java | 1 |
请完成以下Java代码 | protected @NonNull String convertObjectToJson(@NonNull Object source) throws JsonProcessingException {
Assert.notNull(source, "Source object to convert must not be null");
return newObjectMapper(source).writeValueAsString(source);
}
/**
* Constructs a new instance of the Jackson {@link ObjectMapper} class.
*
* @return a new instance of the Jackson {@link ObjectMapper} class.
* @see com.fasterxml.jackson.databind.ObjectMapper
*/
protected @NonNull ObjectMapper newObjectMapper(@NonNull Object target) {
Assert.notNull(target, "Target object must not be null");
return newObjectMapper()
.addMixIn(target.getClass(), ObjectTypeMetadataMixin.class)
.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
.configure(SerializationFeature.INDENT_OUTPUT, true)
.findAndRegisterModules();
} | /**
* Constructs a new instance of Jackson's {@link ObjectMapper}.
*
* @return a new instance of Jackson's {@link ObjectMapper}; never {@literal null}.
* @see com.fasterxml.jackson.databind.ObjectMapper
*/
@NonNull ObjectMapper newObjectMapper() {
return new ObjectMapper();
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = AT_TYPE_METADATA_PROPERTY_NAME
)
@SuppressWarnings("all")
interface ObjectTypeMetadataMixin { }
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonObjectToJsonConverter.java | 1 |
请完成以下Java代码 | public static int usingPermutation(int num) {
Set<Integer> hs = new TreeSet<>();
StringBuilder sb = new StringBuilder(String.valueOf(num));
findPermutations(num, 0, sb, hs);
for (int n : hs) {
if (n > num) {
return n;
}
}
return -1;
}
public static int usingSorting(int num) {
String numStr = String.valueOf(num);
char[] numChars = numStr.toCharArray();
int pivotIndex;
for (pivotIndex = numChars.length - 1; pivotIndex > 0; pivotIndex--) {
if (numChars[pivotIndex] > numChars[pivotIndex - 1]) {
break;
}
}
if (pivotIndex == 0) {
return -1;
}
int pivot = numChars[pivotIndex - 1];
int minIndex = pivotIndex;
for (int j = pivotIndex + 1; j < numChars.length; j++) {
if (numChars[j] > pivot && numChars[j] < numChars[minIndex]) {
minIndex = j;
}
}
// Swap the pivot with the smallest digit found
swap(numChars, pivotIndex - 1, minIndex);
// Sort the digits to the right of the pivot in ascending order
Arrays.sort(numChars, pivotIndex, numChars.length);
return Integer.parseInt(new String(numChars));
}
public static int usingTwoPointer(int num) {
char[] numChars = Integer.toString(num)
.toCharArray();
int pivotIndex = numChars.length - 2;
while (pivotIndex >= 0 && numChars[pivotIndex] >= numChars[pivotIndex + 1]) {
pivotIndex--;
}
if (pivotIndex == -1) | return -1;
int minIndex = numChars.length - 1;
while (numChars[minIndex] <= numChars[pivotIndex]) {
minIndex--;
}
swap(numChars, pivotIndex, minIndex);
reverse(numChars, pivotIndex + 1, numChars.length - 1);
return Integer.parseInt(new String(numChars));
}
private static void swap(char[] numChars, int i, int j) {
char temp = numChars[i];
numChars[i] = numChars[j];
numChars[j] = temp;
}
private static void reverse(char[] numChars, int i, int j) {
while (i < j) {
swap(numChars, i, j);
i++;
j--;
}
}
public static void main(String[] args) {
int result = usingTwoPointer(536479);
System.out.println(result);
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\nexthighestnumbersamedigit\NextHighestNumber.java | 1 |
请完成以下Java代码 | public DocumentId getId()
{
return rowId.getDocumentId();
}
@Override
public boolean isProcessed()
{
return false;
}
@Nullable
@Override
public DocumentPath getDocumentPath()
{
// TODO Auto-generated method stub
return null;
}
@Override
public ImmutableSet<String> getFieldNames()
{
return values.getFieldNames();
}
@Override | public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
public boolean isLocked()
{
return lockedByUser != null;
}
public boolean isNotLocked()
{
return !isLocked();
}
public boolean isLockedBy(@NonNull final UserId userId)
{
return lockedByUser != null
&& UserId.equals(userId, lockedByUser.getIdAs(UserId::ofRepoId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\PackageableRow.java | 1 |
请完成以下Java代码 | public void setSO_CreditUsed (java.math.BigDecimal SO_CreditUsed)
{
set_Value (COLUMNNAME_SO_CreditUsed, SO_CreditUsed);
}
/** Get Kredit gewährt.
@return Gegenwärtiger Aussenstand
*/
@Override
public java.math.BigDecimal getSO_CreditUsed ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SO_CreditUsed);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/**
* SOCreditStatus AD_Reference_ID=289
* Reference name: C_BPartner SOCreditStatus
*/
public static final int SOCREDITSTATUS_AD_Reference_ID=289;
/** CreditStop = S */
public static final String SOCREDITSTATUS_CreditStop = "S";
/** CreditHold = H */
public static final String SOCREDITSTATUS_CreditHold = "H";
/** CreditWatch = W */
public static final String SOCREDITSTATUS_CreditWatch = "W";
/** NoCreditCheck = X */
public static final String SOCREDITSTATUS_NoCreditCheck = "X";
/** CreditOK = O */
public static final String SOCREDITSTATUS_CreditOK = "O";
/** NurEineRechnung = I */
public static final String SOCREDITSTATUS_NurEineRechnung = "I";
/** Set Kreditstatus. | @param SOCreditStatus
Kreditstatus des Geschäftspartners
*/
@Override
public void setSOCreditStatus (java.lang.String SOCreditStatus)
{
set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus);
}
/** Get Kreditstatus.
@return Kreditstatus des Geschäftspartners
*/
@Override
public java.lang.String getSOCreditStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_SOCreditStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Stats.java | 1 |
请完成以下Java代码 | public static POSPaymentProcessingStatus toResponseStatus(final @NonNull SumUpTransactionStatus status, final boolean isRefunded)
{
if (SumUpTransactionStatus.SUCCESSFUL.equals(status))
{
return isRefunded
? POSPaymentProcessingStatus.DELETED
: POSPaymentProcessingStatus.SUCCESSFUL;
}
else if (SumUpTransactionStatus.CANCELLED.equals(status))
{
return POSPaymentProcessingStatus.CANCELLED;
}
else if (SumUpTransactionStatus.FAILED.equals(status))
{
return POSPaymentProcessingStatus.FAILED;
}
else if (SumUpTransactionStatus.PENDING.equals(status))
{
return POSPaymentProcessingStatus.PENDING;
}
else
{
throw new AdempiereException("Unknown SumUp status: " + status);
}
} | public static SumUpPOSRef toPOSRef(@NonNull final POSOrderAndPaymentId posOrderAndPaymentId)
{
return SumUpPOSRef.builder()
.posOrderId(posOrderAndPaymentId.getOrderId().getRepoId())
.posPaymentId(posOrderAndPaymentId.getPaymentId().getRepoId())
.build();
}
@Nullable
public static POSOrderAndPaymentId toPOSOrderAndPaymentId(@NonNull final SumUpPOSRef posRef)
{
return POSOrderAndPaymentId.ofRepoIdsOrNull(posRef.getPosOrderId(), posRef.getPosPaymentId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\payment_gateway\sumup\SumUpUtils.java | 1 |
请完成以下Java代码 | public class GenreAndAgeDto implements Serializable {
private static final long serialVersionUID = 1L;
private String genre;
private int age;
public GenreAndAgeDto() {
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre; | }
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "AuthorDto{" + "genre=" + genre + ", age=" + age + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootCallStoredProcedureJdbcTemplateBeanPropertyRowMapper\src\main\java\com\bookstore\dto\GenreAndAgeDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getComponentSuite() {
return componentSuite;
}
public void setComponentSuite(String componentSuite) {
this.componentSuite = componentSuite;
}
public List<Technology> getTechnologies() {
return technologies;
}
public void setTechnologies(List<Technology> technologies) {
this.technologies = technologies;
}
public String getInputText() {
return inputText;
}
public void setInputText(String inputText) {
this.inputText = inputText;
}
public String getOutputText() {
return outputText;
}
public void setOutputText(String outputText) {
this.outputText = outputText;
} | public class Technology {
private String name;
private String currentVersion;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCurrentVersion() {
return currentVersion;
}
public void setCurrentVersion(String currentVersion) {
this.currentVersion = currentVersion;
}
}
} | repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\HelloPFBean.java | 2 |
请完成以下Java代码 | public List<QueryOrderingProperty> fromOrderByString(String orderByString) {
List<QueryOrderingProperty> properties = new ArrayList<QueryOrderingProperty>();
String[] orderByClauses = orderByString.split(ORDER_BY_DELIMITER);
for (String orderByClause : orderByClauses) {
orderByClause = orderByClause.trim();
String[] clauseParts = orderByClause.split(" ");
if (clauseParts.length == 0) {
continue;
} else if (clauseParts.length > 2) {
throw new ProcessEngineException("Invalid order by clause: " + orderByClause);
}
String function = null;
String propertyPart = clauseParts[0];
int functionArgumentBegin = propertyPart.indexOf("(");
if (functionArgumentBegin >= 0) {
function = propertyPart.substring(0, functionArgumentBegin);
int functionArgumentEnd = propertyPart.indexOf(")");
propertyPart = propertyPart.substring(functionArgumentBegin + 1, functionArgumentEnd);
}
String[] propertyParts = propertyPart.split("\\.");
String property = null; | if (propertyParts.length == 1) {
property = propertyParts[0];
} else if (propertyParts.length == 2) {
property = propertyParts[1];
} else {
throw new ProcessEngineException("Invalid order by property part: " + clauseParts[0]);
}
QueryProperty queryProperty = new QueryPropertyImpl(property, function);
Direction direction = null;
if (clauseParts.length == 2) {
String directionPart = clauseParts[1];
direction = Direction.findByName(directionPart);
}
QueryOrderingProperty orderingProperty = new QueryOrderingProperty(null, queryProperty);
orderingProperty.setDirection(direction);
properties.add(orderingProperty);
}
return properties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\json\JsonLegacyQueryOrderingPropertyConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean matchesClearRule(AlarmTrigger trigger, AlarmNotificationRuleTriggerConfig triggerConfig) {
AlarmApiCallResult alarmUpdate = trigger.getAlarmUpdate();
Alarm alarm = alarmUpdate.getAlarm();
if (!typeMatches(alarm, triggerConfig)) {
return false;
}
if (alarmUpdate.isDeleted()) {
return true;
}
ClearRule clearRule = triggerConfig.getClearRule();
if (clearRule != null) {
if (isNotEmpty(clearRule.getAlarmStatuses())) {
return AlarmStatusFilter.from(clearRule.getAlarmStatuses()).matches(alarm);
}
}
return false;
}
private boolean severityMatches(Alarm alarm, AlarmNotificationRuleTriggerConfig triggerConfig) {
return emptyOrContains(triggerConfig.getAlarmSeverities(), alarm.getSeverity());
}
private boolean typeMatches(Alarm alarm, AlarmNotificationRuleTriggerConfig triggerConfig) {
return emptyOrContains(triggerConfig.getAlarmTypes(), alarm.getType());
}
@Override
public RuleOriginatedNotificationInfo constructNotificationInfo(AlarmTrigger trigger) {
AlarmApiCallResult alarmUpdate = trigger.getAlarmUpdate();
AlarmInfo alarmInfo = alarmUpdate.getAlarm();
return AlarmNotificationInfo.builder()
.alarmId(alarmInfo.getUuidId())
.alarmType(alarmInfo.getType())
.action(alarmUpdate.isCreated() ? "created" :
alarmUpdate.isSeverityChanged() ? "severity changed" :
alarmUpdate.isAcknowledged() ? "acknowledged" :
alarmUpdate.isCleared() ? "cleared" :
alarmUpdate.isDeleted() ? "deleted" : null)
.alarmOriginator(alarmInfo.getOriginator()) | .alarmOriginatorName(alarmInfo.getOriginatorName())
.alarmOriginatorLabel(alarmInfo.getOriginatorLabel())
.alarmSeverity(alarmInfo.getSeverity())
.alarmStatus(alarmInfo.getStatus())
.acknowledged(alarmInfo.isAcknowledged())
.cleared(alarmInfo.isCleared())
.alarmCustomerId(alarmInfo.getCustomerId())
.dashboardId(alarmInfo.getDashboardId())
.details(toDetailsTemplateMap(alarmInfo.getDetails()))
.build();
}
private Map<String, String> toDetailsTemplateMap(JsonNode details) {
Map<String, String> infoMap = JacksonUtil.toFlatMap(details);
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> entry : infoMap.entrySet()) {
String key = "details." + entry.getKey();
result.put(key, entry.getValue());
}
return result;
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.ALARM;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\AlarmTriggerProcessor.java | 2 |
请完成以下Java代码 | public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer,
MessageListenerContainer container, Runnable invokeListener) {
CommonErrorHandler handler = findDelegate(thrownException);
if (handler != null) {
handler.handleBatch(thrownException, data, consumer, container, invokeListener);
}
else {
this.defaultErrorHandler.handleBatch(thrownException, data, consumer, container, invokeListener);
}
}
@Override
public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer,
MessageListenerContainer container, boolean batchListener) {
CommonErrorHandler handler = findDelegate(thrownException);
if (handler != null) {
handler.handleOtherException(thrownException, consumer, container, batchListener);
}
else {
this.defaultErrorHandler.handleOtherException(thrownException, consumer, container, batchListener);
}
}
@Override
public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer,
MessageListenerContainer container) {
CommonErrorHandler handler = findDelegate(thrownException);
if (handler != null) {
return handler.handleOne(thrownException, record, consumer, container);
}
else {
return this.defaultErrorHandler.handleOne(thrownException, record, consumer, container);
}
}
@Nullable
private CommonErrorHandler findDelegate(Throwable thrownException) {
Throwable cause = findCause(thrownException);
if (cause != null) {
Class<? extends Throwable> causeClass = cause.getClass();
for (Entry<Class<? extends Throwable>, CommonErrorHandler> entry : this.delegates.entrySet()) {
if (entry.getKey().isAssignableFrom(causeClass)) {
return entry.getValue();
}
}
}
return null;
}
@Nullable
private Throwable findCause(Throwable thrownException) {
if (this.causeChainTraversing) { | return traverseCauseChain(thrownException);
}
return shallowTraverseCauseChain(thrownException);
}
@Nullable
private Throwable shallowTraverseCauseChain(Throwable thrownException) {
Throwable cause = thrownException;
if (cause instanceof ListenerExecutionFailedException) {
cause = thrownException.getCause();
}
return cause;
}
@Nullable
private Throwable traverseCauseChain(Throwable thrownException) {
Throwable cause = thrownException;
while (cause != null && cause.getCause() != null) {
if (this.exceptionMatcher.match(cause)) {
return cause;
}
cause = cause.getCause();
}
return cause;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonDelegatingErrorHandler.java | 1 |
请完成以下Java代码 | public class StartWorkflowProcessor extends AbstractElementTagProcessor {
private static final String TAG_NAME = "startworkflow";
private static final String DEFAULT_FRAGMENT_NAME = "~{temporalwebdialect :: startworkflow}";
private static final int PRECEDENCE = 10000;
private final ApplicationContext ctx;
private WorkflowClient workflowClient;
public StartWorkflowProcessor(final String dialectPrefix, ApplicationContext ctx,
WorkflowClient workflowClient) {
super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PRECEDENCE);
this.ctx = ctx;
this.workflowClient = workflowClient;
}
@Override
protected void doProcess(ITemplateContext templateContext, IProcessableElementTag processInstancesTag,
IElementTagStructureHandler structureHandler) {
final IEngineConfiguration configuration = templateContext.getConfiguration();
IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
DialectUtils dialectUtils = new DialectUtils(workflowClient);
structureHandler.setLocalVariable("defaultce",
"{\n" +
" \"specversion\" : \"1.0\",\n" +
" \"type\" : \"com.demo.customerevent\",\n" +
" \"source\" : \"/mydemo/9\",\n" + | " \"id\" : \"C234-1234-1234\",\n" +
" \"datacontenttype\" : \"application/json\",\n" +
" \"data\" : {\n" +
" }\n" +
" }");
final IModelFactory modelFactory = templateContext.getModelFactory();
final IModel model = modelFactory.createModel();
model.add(modelFactory.createOpenElementTag("div", "th:replace", dialectUtils.getFragmentName(
processInstancesTag.getAttributeValue("fragment"), DEFAULT_FRAGMENT_NAME, parser, templateContext)));
model.add(modelFactory.createCloseElementTag("div"));
structureHandler.replaceWith(model, true);
}
} | repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\processor\StartWorkflowProcessor.java | 1 |
请完成以下Java代码 | public class TaskMeterLogEntity implements DbEntity, HasDbReferences, Serializable {
private static final long serialVersionUID = 1L;
protected String id;
protected Date timestamp;
protected long assigneeHash;
public TaskMeterLogEntity(String assignee, Date timestamp) {
this.assigneeHash = createHashAsLong(assignee);
this.timestamp = timestamp;
}
protected long createHashAsLong(String assignee) {
String algorithm = "MD5";
try {
// create a 64 bit (8 byte) hash from an MD5 hash (128 bit) and convert to a long (8 byte)
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(assignee.getBytes(StandardCharsets.UTF_8));
return ByteBuffer.wrap(digest.digest(), 0, 8).getLong();
} catch (NoSuchAlgorithmException e) {
throw new ProcessEngineException("Cannot lookup hash algorithm '" + algorithm + "'");
}
}
public TaskMeterLogEntity() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public long getAssigneeHash() { | return assigneeHash;
}
public void setAssigneeHash(long assigneeHash) {
this.assigneeHash = assigneeHash;
}
public Object getPersistentState() {
// immutable
return TaskMeterLogEntity.class;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
return referenceIdAndClass;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskMeterLogEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ListenerErrorHandlerAmqpConfiguration {
@Bean
public ErrorHandler errorHandler() {
return new CustomErrorHandler();
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory,
SimpleRabbitListenerContainerFactoryConfigurer configurer) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
factory.setErrorHandler(errorHandler());
return factory;
} | @Bean
Queue messagesQueue() {
return QueueBuilder.durable(QUEUE_MESSAGES)
.build();
}
@Bean
DirectExchange messagesExchange() {
return new DirectExchange(EXCHANGE_MESSAGES);
}
@Bean
Binding bindingMessages() {
return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES);
}
} | repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\errorhandling\configuration\ListenerErrorHandlerAmqpConfiguration.java | 2 |
请完成以下Java代码 | public boolean put(@NonNull final InOutLineId shipmentLineId, @NonNull final Integer lineNo)
{
if (lineNo <= 0)
{
logger.debug("Ignoring lineNo={} is associated with shipmentLineId={}; -> ignore, i.e. no collission; return true", lineNo, shipmentLineId);
return true;
}
shipmentLineIdToLineNo.put(shipmentLineId, lineNo);
lineNoToShipmentLineId.put(lineNo, shipmentLineId);
if (lineNoToShipmentLineId.get(lineNo).size() > 1)
{
logger.debug("LineNo={} is associated with multiple shipmentLineIds={}; -> collision detected; return false", lineNo, lineNoToShipmentLineId.get(lineNo));
return false;
}
logger.debug("LineNo={} is associated only with shipmentLineId={} so far; -> no collision; return true", lineNo, shipmentLineId);
return true;
}
public int getLineNoFor(@NonNull final InOutLineId shipmentLineId)
{
return coalesce(shipmentLineIdToLineNo.get(shipmentLineId), 0);
} | public ImmutableList<InOutLineId> getShipmentLineIdsWithLineNoCollisions()
{
final ImmutableList.Builder<InOutLineId> result = ImmutableList.builder();
for (final Entry<Integer, Collection<InOutLineId>> entry : lineNoToShipmentLineId.asMap().entrySet())
{
final Collection<InOutLineId> shipmentLineIds = entry.getValue();
if (shipmentLineIds.size() > 1)
{
result.addAll(shipmentLineIds);
}
}
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\spi\impl\ShipmentLineNoInfo.java | 1 |
请完成以下Java代码 | public class SignalThrowIconType extends IconType {
@Override
public Integer getWidth() {
return 17;
}
@Override
public Integer getHeight() {
return 15;
}
@Override
public String getAnchorValue() {
return null;
}
@Override
public String getFillValue() {
return "#585858";
}
@Override
public String getStyleValue() {
return "stroke-width:1.4;stroke-miterlimit:4;stroke-dasharray:none";
}
@Override
public String getDValue() {
return " M7.7124971 20.247342 L22.333334 20.247342 L15.022915000000001 7.575951200000001 L7.7124971 20.247342 z";
} | @Override
public void drawIcon(int imageX, int imageY, int iconPadding, ProcessDiagramSVGGraphics2D svgGenerator) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 7) + "," + (imageY - 7) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "style", this.getStyleValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue());
gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getStrokeValue() {
return "#585858";
}
@Override
public String getStrokeWidth() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\SignalThrowIconType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserDashboardDataService
{
private final UserDashboardRepository userDashboardRepository;
private final KPIDataProvider kpiDataProvider;
private final CCache<UserDashboardId, UserDashboardDataProvider> providers = CCache.<UserDashboardId, UserDashboardDataProvider>builder()
.expireMinutes(CCache.EXPIREMINUTES_Never)
.build();
public UserDashboardDataService(
@NonNull final KPIRepository kpiRepository,
@NonNull final UserDashboardRepository userDashboardRepository)
{
this.userDashboardRepository = userDashboardRepository;
this.kpiDataProvider = KPIDataProvider.builder()
.kpiRepository(kpiRepository)
.esSystem(Services.get(IESSystem.class))
.sysConfigBL(Services.get(ISysConfigBL.class))
.kpiPermissionsProvider(new KPIPermissionsProvider(Services.get(IUserRolePermissionsDAO.class)))
.build();
}
@PostConstruct
void postConstruct()
{
CacheMgt.get().addCacheResetListener(this::onCacheResetRequest);
}
private long onCacheResetRequest(final CacheInvalidateMultiRequest multiRequest)
{
if (multiRequest.isResetAll())
{
kpiDataProvider.cacheReset();
}
return 1;
}
public Optional<UserDashboardId> getUserDashboardId(@NonNull final UserDashboardKey userDashboardKey)
{
return userDashboardRepository.getUserDashboardId(userDashboardKey);
} | public Optional<UserDashboardDataProvider> getData(@NonNull final UserDashboardKey userDashboardKey)
{
return userDashboardRepository.getUserDashboardId(userDashboardKey)
.map(this::getData);
}
public UserDashboardDataProvider getData(@NonNull final UserDashboardId dashboardId)
{
return providers.getOrLoad(dashboardId, this::createDashboardDataProvider);
}
private UserDashboardDataProvider createDashboardDataProvider(@NonNull final UserDashboardId dashboardId)
{
return UserDashboardDataProvider.builder()
.userDashboardRepository(userDashboardRepository)
.kpiDataProvider(kpiDataProvider)
.dashboardId(dashboardId)
.build();
}
public KPIDataResult getKPIData(@NonNull final KPIId kpiId, @NonNull final KPIDataContext kpiDataContext)
{
return kpiDataProvider.getKPIData(KPIDataRequest.builder()
.kpiId(kpiId)
.timeRangeDefaults(KPITimeRangeDefaults.DEFAULT)
.context(kpiDataContext)
.maxStaleAccepted(Duration.ofDays(100))
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboardDataService.java | 2 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-lo | cations=classpath*:mybatis/*Mapper.xml
mybatis.type-aliases-package=com.forezp.entity | repos\SpringBootLearning-master\springboot-mybatis-tx\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public Step cantonStep1(StepBuilderFactory stepBuilderFactory,
@Qualifier("cantonReader") ItemReader<Canton> reader,
@Qualifier("cantonWriter") ItemWriter<Canton> writer,
@Qualifier("cantonProcessor") ItemProcessor<Canton, Canton> processor) {
return stepBuilderFactory
.get("cantonStep1")
.<Canton, Canton>chunk(5000)//批处理每次提交5000条数据
.reader(reader)//给step绑定reader
.processor(processor)//给step绑定processor
.writer(writer)//给step绑定writer
.faultTolerant()
.retry(Exception.class) // 重试
.noRetry(ParseException.class)
.retryLimit(1) //每条记录重试一次
.skip(Exception.class) | .skipLimit(200) //一共允许跳过200次异常
// .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好
// .throttleLimit(10) //并发任务数为 10,默认为4
.build();
}
@Bean
public Validator<Canton> csvBeanValidator() {
return new MyBeanValidator<>();
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\CantonConfig.java | 2 |
请完成以下Java代码 | public class GoldenCustomerRoutePredicateFactory extends AbstractRoutePredicateFactory<GoldenCustomerRoutePredicateFactory.Config> {
private final GoldenCustomerService goldenCustomerService;
public GoldenCustomerRoutePredicateFactory(GoldenCustomerService goldenCustomerService ) {
super(Config.class);
this.goldenCustomerService = goldenCustomerService;
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("isGolden","customerIdCookie");
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
return (ServerWebExchange t) -> {
List<HttpCookie> cookies = t.getRequest()
.getCookies()
.get(config.getCustomerIdCookie());
boolean isGolden;
if ( cookies == null || cookies.isEmpty()) {
isGolden = false;
}
else {
String customerId = cookies.get(0).getValue();
isGolden = goldenCustomerService.isGoldenCustomer(customerId);
}
return config.isGolden()?isGolden:!isGolden;
};
}
@Validated | public static class Config {
boolean isGolden = true;
@NotEmpty
String customerIdCookie = "customerId";
public Config() {}
public Config( boolean isGolden, String customerIdCookie) {
this.isGolden = isGolden;
this.customerIdCookie = customerIdCookie;
}
public boolean isGolden() {
return isGolden;
}
public void setGolden(boolean value) {
this.isGolden = value;
}
/**
* @return the customerIdCookie
*/
public String getCustomerIdCookie() {
return customerIdCookie;
}
/**
* @param customerIdCookie the customerIdCookie to set
*/
public void setCustomerIdCookie(String customerIdCookie) {
this.customerIdCookie = customerIdCookie;
}
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\spring-cloud-gateway-intro\src\main\java\com\baeldung\springcloudgateway\custompredicates\factories\GoldenCustomerRoutePredicateFactory.java | 1 |
请完成以下Java代码 | public Builder setDocumentSummaryElement(@Nullable final DocumentLayoutElementDescriptor documentSummaryElement)
{
this.documentSummaryElement = documentSummaryElement;
return this;
}
public Builder setDocActionElement(@Nullable final DocumentLayoutElementDescriptor docActionElement)
{
this.docActionElement = docActionElement;
return this;
}
public Builder setGridView(final ViewLayout.Builder gridView)
{
this._gridView = gridView;
return this;
}
public Builder setSingleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout)
{
this.singleRowLayout = singleRowLayout;
return this;
}
private DocumentLayoutSingleRow.Builder getSingleRowLayout()
{
return singleRowLayout;
}
private ViewLayout.Builder getGridView()
{
return _gridView;
}
public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail)
{
if (detail == null)
{
return this;
}
if (detail.isEmpty())
{
logger.trace("Skip adding detail to layout because it is empty; detail={}", detail);
return this;
}
details.add(detail);
return this;
} | public Builder setSideListView(final ViewLayout sideListViewLayout)
{
this._sideListView = sideListViewLayout;
return this;
}
private ViewLayout getSideList()
{
Preconditions.checkNotNull(_sideListView, "sideList");
return _sideListView;
}
public Builder putDebugProperty(final String name, final String value)
{
debugProperties.put(name, value);
return this;
}
public Builder setStopwatch(final Stopwatch stopwatch)
{
this.stopwatch = stopwatch;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java | 1 |
请完成以下Java代码 | public Object getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public Builder<?> toBuilder() {
return new Builder<>(this);
}
/**
* A builder of {@link TestingAuthenticationToken} instances
*
* @since 7.0
*/
public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> {
private Object principal;
private Object credentials;
protected Builder(TestingAuthenticationToken token) {
super(token);
this.principal = token.principal;
this.credentials = token.credentials;
}
@Override | public B principal(@Nullable Object principal) {
Assert.notNull(principal, "principal cannot be null");
this.principal = principal;
return (B) this;
}
@Override
public B credentials(@Nullable Object credentials) {
Assert.notNull(credentials, "credentials cannot be null");
this.credentials = credentials;
return (B) this;
}
@Override
public TestingAuthenticationToken build() {
return new TestingAuthenticationToken(this);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\TestingAuthenticationToken.java | 1 |
请完成以下Java代码 | public class NumberWordConverter {
public static final String INVALID_INPUT_GIVEN = "Invalid input given";
public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
public static final String[] tens = {
"", // 0
"", // 1
"twenty", // 2
"thirty", // 3
"forty", // 4
"fifty", // 5
"sixty", // 6
"seventy", // 7
"eighty", // 8
"ninety" // 9
};
public static String getMoneyIntoWords(String input) {
MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE;
return converter.asWords(new BigDecimal(input));
}
public static String getMoneyIntoWords(final double money) {
long dollar = (long) money;
long cents = Math.round((money - dollar) * 100);
if (money == 0D) {
return "";
}
if (money < 0) {
return INVALID_INPUT_GIVEN;
}
String dollarPart = "";
if (dollar > 0) {
dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s");
}
String centsPart = "";
if (cents > 0) {
if (dollarPart.length() > 0) {
centsPart = " and ";
}
centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s");
}
return dollarPart + centsPart; | }
private static String convert(final long n) {
if (n < 0) {
return INVALID_INPUT_GIVEN;
}
if (n < 20) {
return ones[(int) n];
}
if (n < 100) {
return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10];
}
if (n < 1000) {
return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
if (n < 1_000_000) {
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
}
if (n < 1_000_000_000) {
return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000);
}
return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000);
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\numberwordconverter\NumberWordConverter.java | 1 |
请完成以下Java代码 | public User userStatus(Integer userStatus) {
this.userStatus = userStatus;
return this;
}
/**
* User Status
* @return userStatus
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "User Status")
@JsonProperty(JSON_PROPERTY_USER_STATUS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(this.id, user.id) &&
Objects.equals(this.username, user.username) &&
Objects.equals(this.firstName, user.firstName) &&
Objects.equals(this.lastName, user.lastName) &&
Objects.equals(this.email, user.email) &&
Objects.equals(this.password, user.password) &&
Objects.equals(this.phone, user.phone) &&
Objects.equals(this.userStatus, user.userStatus);
}
@Override
public int hashCode() {
return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); | }
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\User.java | 1 |
请完成以下Java代码 | private ILock lockSelection(@NonNull final PInstanceId selectionId)
{
final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, I_AD_PInstance.COLUMN_AD_PInstance_ID + "=" + selectionId.getRepoId());
return lockManager.lock()
.setOwner(lockOwner)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_C_OLCand.class, selectionId)
.acquire();
}
private void setHeaderAggregationKey(@NonNull final C_OLCandToOrderEnqueuer.EnqueueWorkPackageRequest request)
{
final IOLCandBL olCandBL = Services.get(IOLCandBL.class);
final OLCandIterator olCandIterator = getOrderedOLCandIterator(request);
final OLCandProcessorDescriptor olCandProcessorDescriptor = request.getOlCandProcessorDescriptor();
while (olCandIterator.hasNext())
{
final OLCand candidate = olCandIterator.next();
final String headerAggregationKey = olCandProcessorDescriptor.getAggregationInfo().computeHeaderAggregationKey(candidate);
candidate.setHeaderAggregationKey(headerAggregationKey);
olCandBL.saveCandidate(candidate);
}
} | @Builder
@Value
private static class EnqueueWorkPackageRequest
{
@NonNull
ILock mainLock;
@NonNull
PInstanceId orderLineCandSelectionId;
@NonNull
OLCandProcessorDescriptor olCandProcessorDescriptor;
@Nullable
AsyncBatchId asyncBatchId;
boolean propagateAsyncBatchIdToOrderRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\async\C_OLCandToOrderEnqueuer.java | 1 |
请完成以下Java代码 | public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@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);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setT_Amount (final @Nullable BigDecimal T_Amount)
{
set_Value (COLUMNNAME_T_Amount, T_Amount);
}
@Override
public BigDecimal getT_Amount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Amount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Date (final @Nullable java.sql.Timestamp T_Date)
{
set_Value (COLUMNNAME_T_Date, T_Date);
}
@Override
public java.sql.Timestamp getT_Date()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Date);
}
@Override
public void setT_DateTime (final @Nullable java.sql.Timestamp T_DateTime)
{
set_Value (COLUMNNAME_T_DateTime, T_DateTime);
}
@Override
public java.sql.Timestamp getT_DateTime()
{
return get_ValueAsTimestamp(COLUMNNAME_T_DateTime);
}
@Override
public void setT_Integer (final int T_Integer) | {
set_Value (COLUMNNAME_T_Integer, T_Integer);
}
@Override
public int getT_Integer()
{
return get_ValueAsInt(COLUMNNAME_T_Integer);
}
@Override
public void setT_Number (final @Nullable BigDecimal T_Number)
{
set_Value (COLUMNNAME_T_Number, T_Number);
}
@Override
public BigDecimal getT_Number()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Number);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Qty (final @Nullable BigDecimal T_Qty)
{
set_Value (COLUMNNAME_T_Qty, T_Qty);
}
@Override
public BigDecimal getT_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Time (final @Nullable java.sql.Timestamp T_Time)
{
set_Value (COLUMNNAME_T_Time, T_Time);
}
@Override
public java.sql.Timestamp getT_Time()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Time);
}
@Override
public void setTest_ID (final int Test_ID)
{
if (Test_ID < 1)
set_ValueNoCheck (COLUMNNAME_Test_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID);
}
@Override
public int getTest_ID()
{
return get_ValueAsInt(COLUMNNAME_Test_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public PeerSecurityProperties getPeer() {
return this.peer;
}
public SecurityPostProcessorProperties getPostProcessor() {
return this.securityPostProcessorProperties;
}
public String getPropertiesFile() {
return this.propertiesFile;
}
public void setPropertiesFile(String propertiesFile) {
this.propertiesFile = propertiesFile;
}
public ApacheShiroProperties getShiro() {
return this.apacheShiroProperties;
}
public SslProperties getSsl() {
return this.ssl;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public static class ApacheShiroProperties {
private String iniResourcePath;
public String getIniResourcePath() {
return this.iniResourcePath;
}
public void setIniResourcePath(String iniResourcePath) {
this.iniResourcePath = iniResourcePath;
}
}
public static class SecurityLogProperties {
private static final String DEFAULT_SECURITY_LOG_LEVEL = "config";
private String file;
private String level = DEFAULT_SECURITY_LOG_LEVEL;
public String getFile() {
return this.file;
} | public void setFile(String file) {
this.file = file;
}
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
}
public static class SecurityManagerProperties {
private String className;
public String getClassName() {
return this.className;
}
public void setClassName(String className) {
this.className = className;
}
}
public static class SecurityPostProcessorProperties {
private String className;
public String getClassName() {
return this.className;
}
public void setClassName(String className) {
this.className = className;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SecurityProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean isCoerceInputValues() {
return this.coerceInputValues;
}
public void setCoerceInputValues(boolean coerceInputValues) {
this.coerceInputValues = coerceInputValues;
}
public boolean isAllowStructuredMapKeys() {
return this.allowStructuredMapKeys;
}
public void setAllowStructuredMapKeys(boolean allowStructuredMapKeys) {
this.allowStructuredMapKeys = allowStructuredMapKeys;
}
public boolean isAllowSpecialFloatingPointValues() {
return this.allowSpecialFloatingPointValues;
}
public void setAllowSpecialFloatingPointValues(boolean allowSpecialFloatingPointValues) {
this.allowSpecialFloatingPointValues = allowSpecialFloatingPointValues;
}
public String getClassDiscriminator() {
return this.classDiscriminator;
}
public void setClassDiscriminator(String classDiscriminator) {
this.classDiscriminator = classDiscriminator;
}
public ClassDiscriminatorMode getClassDiscriminatorMode() {
return this.classDiscriminatorMode;
}
public void setClassDiscriminatorMode(ClassDiscriminatorMode classDiscriminatorMode) {
this.classDiscriminatorMode = classDiscriminatorMode;
}
public boolean isDecodeEnumsCaseInsensitive() {
return this.decodeEnumsCaseInsensitive;
}
public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) {
this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive;
}
public boolean isUseAlternativeNames() {
return this.useAlternativeNames;
}
public void setUseAlternativeNames(boolean useAlternativeNames) {
this.useAlternativeNames = useAlternativeNames;
} | public boolean isAllowTrailingComma() {
return this.allowTrailingComma;
}
public void setAllowTrailingComma(boolean allowTrailingComma) {
this.allowTrailingComma = allowTrailingComma;
}
public boolean isAllowComments() {
return this.allowComments;
}
public void setAllowComments(boolean allowComments) {
this.allowComments = allowComments;
}
/**
* Enum representing strategies for JSON property naming. The values correspond to
* {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot
* be directly referenced.
*/
public enum JsonNamingStrategy {
/**
* Snake case strategy.
*/
SNAKE_CASE,
/**
* Kebab case strategy.
*/
KEBAB_CASE
}
} | repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java | 2 |
请完成以下Java代码 | public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
return other.name == null;
} else
return name.equals(other.name);
}
@Override
public String toString() {
return "Bar [name=" + name + "]";
}
@PrePersist
public void onPrePersist() {
LOGGER.info("@PrePersist");
audit(OPERATION.INSERT);
} | @PreUpdate
public void onPreUpdate() {
LOGGER.info("@PreUpdate");
audit(OPERATION.UPDATE);
}
@PreRemove
public void onPreRemove() {
LOGGER.info("@PreRemove");
audit(OPERATION.DELETE);
}
private void audit(final OPERATION operation) {
setOperation(operation);
setTimestamp((new Date()).getTime());
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\model\Bar.java | 1 |
请完成以下Java代码 | public TransformsType2 getTransforms() {
return transforms;
}
/**
* Sets the value of the transforms property.
*
* @param value
* allowed object is
* {@link TransformsType2 }
*
*/
public void setTransforms(TransformsType2 value) {
this.transforms = value;
}
/**
* Gets the value of the digestMethod property.
*
* @return
* possible object is
* {@link DigestMethodType }
*
*/
public DigestMethodType getDigestMethod() {
return digestMethod;
}
/**
* Sets the value of the digestMethod property.
*
* @param value
* allowed object is
* {@link DigestMethodType }
*
*/
public void setDigestMethod(DigestMethodType value) {
this.digestMethod = value;
}
/**
* Gets the value of the digestValue property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getDigestValue() {
return digestValue;
}
/**
* Sets the value of the digestValue property.
*
* @param value
* allowed object is
* byte[]
*/
public void setDigestValue(byte[] value) {
this.digestValue = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the uri property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getURI() {
return uri;
}
/**
* Sets the value of the uri property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setURI(String value) {
this.uri = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ReferenceType2.java | 1 |
请完成以下Java代码 | public int getM_FreightCostShipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCostShipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Shipper getM_Shipper() throws RuntimeException
{
return (I_M_Shipper)MTable.get(getCtx(), I_M_Shipper.Table_Name)
.getPO(getM_Shipper_ID(), get_TrxName()); }
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung | */
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gueltig ab.
@param ValidFrom
Gueltig ab inklusiv (erster Tag)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gueltig ab.
@return Gueltig ab inklusiv (erster Tag)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostShipper.java | 1 |
请完成以下Java代码 | public MRequestProcessorRoute[] getRoutes (boolean reload)
{
if (m_routes != null && !reload)
return m_routes;
String sql = "SELECT * FROM R_RequestProcessor_Route WHERE R_RequestProcessor_ID=? ORDER BY SeqNo";
ArrayList<MRequestProcessorRoute> list = new ArrayList<>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getR_RequestProcessor_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MRequestProcessorRoute (getCtx(), rs, get_TrxName()));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
//
m_routes = new MRequestProcessorRoute[list.size ()];
list.toArray (m_routes);
return m_routes;
} // getRoutes
/**
* Get Logs
* @return Array of Logs
*/
@Override
public AdempiereProcessorLog[] getLogs()
{
ArrayList<MRequestProcessorLog> list = new ArrayList<>();
String sql = "SELECT * "
+ "FROM R_RequestProcessorLog "
+ "WHERE R_RequestProcessor_ID=? "
+ "ORDER BY Created DESC";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getR_RequestProcessor_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MRequestProcessorLog (getCtx(), rs, get_TrxName()));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
MRequestProcessorLog[] retValue = new MRequestProcessorLog[list.size ()];
list.toArray (retValue);
return retValue;
} // getLogs | /**
* Delete old Request Log
* @return number of records
*/
public int deleteLog()
{
if (getKeepLogDays() < 1)
return 0;
String sql = "DELETE FROM R_RequestProcessorLog "
+ "WHERE R_RequestProcessor_ID=" + getR_RequestProcessor_ID()
+ " AND (Created+" + getKeepLogDays() + ") < now()";
int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
return no;
} // deleteLog
/**
* Get the date Next run
* @param requery requery database
* @return date next run
*/
@Override
public Timestamp getDateNextRun (boolean requery)
{
if (requery)
load(get_TrxName());
return getDateNextRun();
} // getDateNextRun
/**
* Get Unique ID
* @return Unique ID
*/
@Override
public String getServerID()
{
return "RequestProcessor" + get_ID();
} // getServerID
@Override
public boolean saveOutOfTrx()
{
return save(ITrx.TRXNAME_None);
}
} // MRequestProcessor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRequestProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UserResponse getUser(@ApiParam(name = "userId") @PathVariable String userId) {
return restResponseFactory.createUserResponse(getUserFromRequest(userId), false);
}
@ApiOperation(value = "Update a user", tags = { "Users" }, notes = "All request values are optional. "
+ "For example, you can only include the firstName attribute in the request body JSON-object, only updating the firstName of the user, leaving all other fields unaffected. "
+ "When an attribute is explicitly included and is set to null, the user-value will be updated to null. "
+ "Example: {\"firstName\" : null} will clear the firstName of the user).")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the user was updated."),
@ApiResponse(code = 404, message = "Indicates the requested user was not found."),
@ApiResponse(code = 409, message = "Indicates the requested user was updated simultaneously.")
})
@PutMapping(value = "/users/{userId}", produces = "application/json")
public UserResponse updateUser(@ApiParam(name = "userId") @PathVariable String userId, @RequestBody UserRequest userRequest) {
User user = getUserFromRequest(userId);
if (userRequest.isEmailChanged()) {
user.setEmail(userRequest.getEmail());
}
if (userRequest.isFirstNameChanged()) {
user.setFirstName(userRequest.getFirstName());
}
if (userRequest.isLastNameChanged()) {
user.setLastName(userRequest.getLastName());
}
if (userRequest.isDisplayNameChanged()) {
user.setDisplayName(userRequest.getDisplayName());
}
if (userRequest.isPasswordChanged()) { | user.setPassword(userRequest.getPassword());
identityService.updateUserPassword(user);
} else {
identityService.saveUser(user);
}
return restResponseFactory.createUserResponse(user, false);
}
@ApiOperation(value = "Delete a user", tags = { "Users" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the user was found and has been deleted. Response-body is intentionally empty."),
@ApiResponse(code = 404, message = "Indicates the requested user was not found.")
})
@DeleteMapping("/users/{userId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@ApiParam(name = "userId") @PathVariable String userId) {
User user = getUserFromRequest(userId);
if (restApiInterceptor != null) {
restApiInterceptor.deleteUser(user);
}
identityService.deleteUser(user.getId());
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\user\UserResource.java | 2 |
请完成以下Java代码 | 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 Deployed.
@param IsDeployed
Entity is deployed
*/
public void setIsDeployed (boolean IsDeployed)
{
set_Value (COLUMNNAME_IsDeployed, Boolean.valueOf(IsDeployed));
}
/** Get Deployed.
@return Entity is deployed
*/
public boolean isDeployed ()
{
Object oo = get_Value(COLUMNNAME_IsDeployed);
if (oo != null) | {
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Last Synchronized.
@param LastSynchronized
Date when last synchronized
*/
public void setLastSynchronized (Timestamp LastSynchronized)
{
set_Value (COLUMNNAME_LastSynchronized, LastSynchronized);
}
/** Get Last Synchronized.
@return Date when last synchronized
*/
public Timestamp getLastSynchronized ()
{
return (Timestamp)get_Value(COLUMNNAME_LastSynchronized);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_MediaDeploy.java | 1 |
请完成以下Java代码 | public Collection<EventPayloadInstance> extractPayload(EventModel eventModel, Document payload) {
return eventModel.getPayload().stream()
.filter(parameterDefinition -> parameterDefinition.isFullPayload() || getChildNode(payload, parameterDefinition.getName()) != null)
.map(payloadDefinition -> new EventPayloadInstanceImpl(payloadDefinition, getPayloadValue(payload,
payloadDefinition.getName(), payloadDefinition.getType(), payloadDefinition.isFullPayload())))
.collect(Collectors.toList());
}
protected Object getPayloadValue(Document document, String definitionName, String definitionType, boolean isFullPayload) {
if (isFullPayload) {
return document;
}
Node childNode = getChildNode(document, definitionName);
if (childNode != null) {
String textContent = childNode.getTextContent();
if (EventPayloadTypes.STRING.equals(definitionType)) {
return textContent;
} else if (EventPayloadTypes.BOOLEAN.equals(definitionType)) {
return Boolean.valueOf(textContent);
} else if (EventPayloadTypes.INTEGER.equals(definitionType)) {
return Integer.valueOf(textContent);
} else if (EventPayloadTypes.DOUBLE.equals(definitionType)) {
return Double.valueOf(textContent);
} else if (EventPayloadTypes.LONG.equals(definitionType)) {
return Long.valueOf(textContent);
} else {
LOGGER.warn("Unsupported payload type: {} ", definitionType);
return textContent;
}
} | return null;
}
protected Node getChildNode(Document document, String elementName) {
NodeList childNodes = null;
if (document.getChildNodes().getLength() == 1) {
childNodes = document.getFirstChild().getChildNodes();
} else {
childNodes = document.getChildNodes();
}
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (elementName.equals(node.getNodeName())) {
return node;
}
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\payload\XmlElementsToMapPayloadExtractor.java | 1 |
请完成以下Java代码 | public void setGL_Category_ID (int GL_Category_ID)
{
if (GL_Category_ID < 1)
set_Value (COLUMNNAME_GL_Category_ID, null);
else
set_Value (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID));
}
/** Get GL Category.
@return General Ledger Category
*/
public int getGL_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
} | /** 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Reval_Entry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SAPGLJournalLineId implements RepoIdAware
{
@JsonCreator
public static SAPGLJournalLineId ofRepoId(@NonNull final SAPGLJournalId glJournalId, final int repoId)
{
return new SAPGLJournalLineId(glJournalId, repoId);
}
@JsonCreator
public static SAPGLJournalLineId ofRepoId(final int glJournalRepoId, final int repoId)
{
return new SAPGLJournalLineId(SAPGLJournalId.ofRepoId(glJournalRepoId), repoId);
}
public static SAPGLJournalLineId ofRepoIdOrNull(@Nullable final SAPGLJournalId glJournalId, final int repoId)
{
return glJournalId != null && repoId > 0 ? new SAPGLJournalLineId(glJournalId, repoId) : null;
}
public static SAPGLJournalLineId ofRepoIdOrNull(final int glJournalRepoId, final int repoId)
{
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoIdOrNull(glJournalRepoId);
return ofRepoIdOrNull(glJournalId, repoId);
}
@NonNull SAPGLJournalId glJournalId;
int repoId;
private SAPGLJournalLineId(final @NonNull SAPGLJournalId glJournalId, final int repoId) | {
this.glJournalId = glJournalId;
this.repoId = Check.assumeGreaterThanZero(repoId, "SAP_GLJournalLine_ID");
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final SAPGLJournalLineId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final SAPGLJournalLineId id1, @Nullable final SAPGLJournalLineId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\acct\gljournal_sap\SAPGLJournalLineId.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.