instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class DefaultTrendzSettingsService implements TrendzSettingsService {
private final AdminSettingsService adminSettingsService;
private static final String SETTINGS_KEY = "trendz";
@CacheEvict(cacheNames = CacheConstants.TRENDZ_SETTINGS_CACHE, key = "#tenantId")
@Override
public void saveTrendzSettings(TenantId tenantId, TrendzSettings settings) {
AdminSettings adminSettings = Optional.ofNullable(adminSettingsService.findAdminSettingsByTenantIdAndKey(tenantId, SETTINGS_KEY))
.orElseGet(() -> {
AdminSettings newAdminSettings = new AdminSettings();
newAdminSettings.setTenantId(tenantId);
newAdminSettings.setKey(SETTINGS_KEY);
return newAdminSettings;
});
adminSettings.setJsonValue(JacksonUtil.valueToTree(settings));
adminSettingsService.saveAdminSettings(tenantId, adminSettings);
} | @Cacheable(cacheNames = CacheConstants.TRENDZ_SETTINGS_CACHE, key = "#tenantId")
@Override
public TrendzSettings findTrendzSettings(TenantId tenantId) {
return Optional.ofNullable(adminSettingsService.findAdminSettingsByTenantIdAndKey(tenantId, SETTINGS_KEY))
.map(adminSettings -> JacksonUtil.treeToValue(adminSettings.getJsonValue(), TrendzSettings.class))
.orElseGet(TrendzSettings::new);
}
@CacheEvict(cacheNames = CacheConstants.TRENDZ_SETTINGS_CACHE, key = "#tenantId")
@Override
public void deleteTrendzSettings(TenantId tenantId) {
adminSettingsService.deleteAdminSettingsByTenantIdAndKey(tenantId, SETTINGS_KEY);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\trendz\DefaultTrendzSettingsService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ReturnT<String> pause(int id) {
return xxlJobService.stop(id);
}
@RequestMapping("/start")
@ResponseBody
public ReturnT<String> start(int id) {
return xxlJobService.start(id);
}
@RequestMapping("/trigger")
@ResponseBody
public ReturnT<String> triggerJob(HttpServletRequest request, int id, String executorParam, String addressList) {
// login user
XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
// trigger
return xxlJobService.trigger(loginUser, id, executorParam, addressList);
}
@RequestMapping("/nextTriggerTime")
@ResponseBody
public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) {
XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
paramXxlJobInfo.setScheduleType(scheduleType);
paramXxlJobInfo.setScheduleConf(scheduleConf);
List<String> result = new ArrayList<>();
try {
Date lastTime = new Date(); | for (int i = 0; i < 5; i++) {
lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
if (lastTime != null) {
result.add(DateUtil.formatDateTime(lastTime));
} else {
break;
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) + e.getMessage());
}
return new ReturnT<List<String>>(result);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobInfoController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity login() {
//TODO:登录日志。
ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
user.setToken(SecurityUtils.getSubject().getSession().getId().toString());
return ResponseEntity.ok(user);
}
/**
* 获取当前登录人的登录信息,包括拥有的角色、权限等。
*
* @return
*/
@GetMapping("/logininfo")
public ResponseEntity loginInfo() {
ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
Map<String, Object> map = new HashMap<>();
Set<String> permissions = Sets.newHashSet();
//TODO 获取当前用户所有的权限和角色
User user = userService.getById(shiroUser.getUserId().intValue());
map.put("roleList", user.getRoles());
map.put("permissionList", permissions);
map.put("userId", shiroUser.getUserId());
map.put("username", shiroUser.getLoginName()); | return ResponseEntity.ok(map);
}
/**
* 注销
* @return
*/
@PostMapping("/logout")
public ResponseEntity logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return ResponseEntity.ok();
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\controller\LoginController.java | 2 |
请完成以下Java代码 | public String getCbudgetid() {
return cbudgetid;
}
public void setCbudgetid(String cbudgetid) {
this.cbudgetid = cbudgetid;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getAuditmsg() {
return auditmsg;
}
public void setAuditmsg(String auditmsg) {
this.auditmsg = auditmsg;
}
public String getTrialstatus() {
return trialstatus;
}
public void setTrialstatus(String trialstatus) {
this.trialstatus = trialstatus;
}
public String getFirauditer() {
return firauditer;
}
public void setFirauditer(String firauditer) {
this.firauditer = firauditer;
}
public String getFiraudittime() {
return firaudittime;
}
public void setFiraudittime(String firaudittime) {
this.firaudittime = firaudittime;
}
public String getFinauditer() {
return finauditer;
} | public void setFinauditer(String finauditer) {
this.finauditer = finauditer;
}
public String getFinaudittime() {
return finaudittime;
}
public void setFinaudittime(String finaudittime) {
this.finaudittime = finaudittime;
}
public String getEdittime() {
return edittime;
}
public void setEdittime(String edittime) {
this.edittime = edittime;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\vtoll\BudgetVtoll.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MultipleHUInventoryLineAggregator implements InventoryLineAggregator
{
@VisibleForTesting
public static final MultipleHUInventoryLineAggregator INSTANCE = new MultipleHUInventoryLineAggregator();
private MultipleHUInventoryLineAggregator()
{
}
@Override
public InventoryLineAggregationKey createAggregationKey(@NonNull final HuForInventoryLine huForInventoryLine)
{
final Quantity qty = CoalesceUtil.coalesce(huForInventoryLine.getQuantityCount(), huForInventoryLine.getQuantityBooked());
final UomId uomId = qty == null ? null : qty.getUomId();
return MultipleHUInventoryLineInventoryLineAggregationKey.builder()
.productId(huForInventoryLine.getProductId())
.uomId(uomId)
.storageAttributesKey(huForInventoryLine.getStorageAttributesKey())
.locatorId(huForInventoryLine.getLocatorId())
.build();
}
@Override
public InventoryLineAggregationKey createAggregationKey(@NonNull final InventoryLine inventoryLine)
{
final Quantity qty = CoalesceUtil.coalesce(inventoryLine.getQtyCount(), inventoryLine.getQtyBook()); | final UomId uomId = qty == null ? null : qty.getUomId();
return MultipleHUInventoryLineInventoryLineAggregationKey.builder()
.productId(inventoryLine.getProductId())
.uomId(uomId)
.storageAttributesKey(AttributesKeys.createAttributesKeyFromASIStorageAttributes(inventoryLine.getAsiId()).orElse(AttributesKey.NONE))
.locatorId(inventoryLine.getLocatorId())
.build();
}
@Override
public AggregationType getAggregationType()
{
return AggregationType.MULTIPLE_HUS;
}
@Value
@Builder
private static class MultipleHUInventoryLineInventoryLineAggregationKey implements InventoryLineAggregationKey
{
@NonNull ProductId productId;
// needed for the case that stocking UOM has changed, and there are still HUs with an old UOM
@Nullable UomId uomId;
@NonNull AttributesKey storageAttributesKey;
@NonNull LocatorId locatorId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\aggregator\MultipleHUInventoryLineAggregator.java | 2 |
请完成以下Java代码 | public abstract class ValuedDataObject extends DataObject {
protected Object value;
public Object getValue() {
return value;
}
public abstract void setValue(Object value);
@Override
public abstract ValuedDataObject clone();
public void setValues(ValuedDataObject otherElement) {
super.setValues(otherElement);
if (otherElement.getValue() != null) {
setValue(otherElement.getValue());
}
}
public String getType() {
String structureRef = itemSubjectRef.getStructureRef();
return structureRef.substring(structureRef.indexOf(':') + 1);
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + (itemSubjectRef.getStructureRef() != null ? itemSubjectRef.getStructureRef().hashCode() : 0);
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} | if (o == null || getClass() != o.getClass()) {
return false;
}
ValuedDataObject otherObject = (ValuedDataObject) o;
if (!otherObject.getItemSubjectRef().getStructureRef().equals(this.itemSubjectRef.getStructureRef())) {
return false;
}
if (!otherObject.getId().equals(this.id)) {
return false;
}
if (!otherObject.getName().equals(this.name)) {
return false;
}
return otherObject.getValue().equals(this.value.toString());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ValuedDataObject.java | 1 |
请完成以下Java代码 | public void setClassname (final java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
@Override
public java.lang.String getClassname()
{
return get_ValueAsString(COLUMNNAME_Classname);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setIs_AD_User_InCharge_UI_Setting (final boolean Is_AD_User_InCharge_UI_Setting) | {
set_Value (COLUMNNAME_Is_AD_User_InCharge_UI_Setting, Is_AD_User_InCharge_UI_Setting);
}
@Override
public boolean is_AD_User_InCharge_UI_Setting()
{
return get_ValueAsBoolean(COLUMNNAME_Is_AD_User_InCharge_UI_Setting);
}
@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 setTableName (final java.lang.String TableName)
{
set_Value (COLUMNNAME_TableName, TableName);
}
@Override
public java.lang.String getTableName()
{
return get_ValueAsString(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_ILCandHandler.java | 1 |
请完成以下Java代码 | public long getCreatedDate() {
return createdDate;
}
public void setCreatedDate(final long createdDate) {
this.createdDate = createdDate;
}
public long getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(final long modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(final String modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
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 Bar other = (Bar) obj;
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("Bar [name=").append(name).append("]");
return builder.toString();
}
@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());
}
public enum OPERATION {
INSERT, UPDATE, DELETE;
private String value;
OPERATION() {
value = toString();
}
public static OPERATION parse(final String value) {
OPERATION operation = null;
for (final OPERATION op : OPERATION.values()) {
if (op.getValue().equals(value)) {
operation = op;
break;
}
}
return operation;
}
public String getValue() {
return value;
}
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\Bar.java | 1 |
请完成以下Java代码 | public final class HuIdsFilterList
{
public static final HuIdsFilterList ALL = new HuIdsFilterList(true, null);
public static final HuIdsFilterList NONE = new HuIdsFilterList(false, ImmutableSet.of());
public static HuIdsFilterList of(@NonNull final Collection<HuId> huIds)
{
return !huIds.isEmpty()
? new HuIdsFilterList(false, ImmutableSet.copyOf(huIds))
: NONE;
}
public static HuIdsFilterList of(@NonNull final HuId... huIds)
{
return huIds != null && huIds.length > 0
? new HuIdsFilterList(false, ImmutableSet.copyOf(huIds))
: NONE;
}
private final boolean all;
private final ImmutableSet<HuId> huIds;
private HuIdsFilterList(final boolean all, @Nullable final ImmutableSet<HuId> huIds)
{
this.all = all;
if (this.all)
{
this.huIds = null;
}
else
{
this.huIds = Check.assumeNotNull(huIds, "huIds");
}
}
public boolean isAll()
{
return all;
}
private void assertNotAll()
{
if (all) | {
throw new AdempiereException("method not supported for ALL");
}
}
public boolean isNone()
{
return !all && huIds.isEmpty();
}
public Integer estimateSize()
{
return all ? null : huIds.size();
}
public Stream<HuId> stream()
{
assertNotAll();
return huIds.stream();
}
public ImmutableSet<HuId> toSet()
{
assertNotAll();
return huIds;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HuIdsFilterList.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TaskRecord {
@Id
@Column(name = "task_id")
private String id;
private String title;
@Column(name = "created_at")
private Instant created;
@Column(name = "created_by")
private String createdBy;
@Column(name = "assigned_to")
private String assignedTo;
private String status;
public TaskRecord(final String id, final String title, final Instant created, final String createdBy, final String assignedTo, final String status) {
this.id = id;
this.title = title;
this.created = created;
this.createdBy = createdBy;
this.assignedTo = assignedTo;
this.status = status;
}
private TaskRecord() {
// Needed for JPA
}
public String getId() {
return id;
} | public String getTitle() {
return title;
}
public Instant getCreated() {
return created;
}
public String getCreatedBy() {
return createdBy;
}
public String getAssignedTo() {
return assignedTo;
}
public String getStatus() {
return status;
}
public void setAssignedTo(final String assignedTo) {
this.assignedTo = assignedTo;
}
public void setStatus(final String status) {
this.status = status;
}
} | repos\tutorials-master\lightrun\lightrun-tasks-service\src\main\java\com\baeldung\tasksservice\adapters\repository\TaskRecord.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
} | @Override
public String getScopeDefinitionKey() {
return scopeDefinitionKey;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getConfiguration() {
return configuration;
}
} | repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java | 2 |
请完成以下Java代码 | public ExplainedOptional<HULabelConfig> getFirstMatching(HULabelConfigQuery query)
{
return getMap().getFirstMatching(query);
}
private HULabelConfigMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private HULabelConfigMap retrieveMap()
{
ImmutableList<HULabelConfigRoute> list = queryBL.createQueryBuilder(I_M_HU_Label_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(HULabelConfigRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new HULabelConfigMap(list);
}
public static HULabelConfigRoute fromRecord(final I_M_HU_Label_Config record)
{
return HULabelConfigRoute.builder()
.seqNo(SeqNo.ofInt(record.getSeqNo()))
.sourceDocType(HULabelSourceDocType.ofNullableCode(record.getHU_SourceDocType()))
.acceptHUUnitTypes(extractAcceptedHuUnitTypes(record))
.bpartnerId(BPartnerId.ofRepoIdOrNull(record.getC_BPartner_ID()))
.config(HULabelConfig.builder()
.printFormatProcessId(AdProcessId.ofRepoId(record.getLabelReport_Process_ID()))
.autoPrint(record.isAutoPrint())
.autoPrintCopies(PrintCopies.ofIntOrOne(record.getAutoPrintCopies()))
.build())
.build();
}
public static ImmutableSet<HuUnitType> extractAcceptedHuUnitTypes(final I_M_HU_Label_Config record)
{
final ImmutableSet.Builder<HuUnitType> builder = ImmutableSet.builder();
if (record.isApplyToLUs())
{
builder.add(HuUnitType.LU);
}
if (record.isApplyToTUs())
{
builder.add(HuUnitType.TU);
}
if (record.isApplyToCUs())
{
builder.add(HuUnitType.VHU);
} | return builder.build();
}
//
//
//
//
//
private static class HULabelConfigMap
{
private final ImmutableList<HULabelConfigRoute> orderedList;
public HULabelConfigMap(final ImmutableList<HULabelConfigRoute> list)
{
this.orderedList = list.stream()
.sorted(Comparator.comparing(HULabelConfigRoute::getSeqNo))
.collect(ImmutableList.toImmutableList());
}
public ExplainedOptional<HULabelConfig> getFirstMatching(@NonNull final HULabelConfigQuery query)
{
return orderedList.stream()
.filter(route -> route.isMatching(query))
.map(HULabelConfigRoute::getConfig)
.findFirst()
.map(ExplainedOptional::of)
.orElseGet(() -> ExplainedOptional.emptyBecause("No HU Label Config found for " + query));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\labels\HULabelConfigRepository.java | 1 |
请完成以下Java代码 | public IQuery<I_MD_Cockpit> createQuery(@NonNull final DocumentFilterList filters)
{
final IQueryBuilder<I_MD_Cockpit> queryBuilder = createInitialQueryBuilder();
boolean anyRestrictionAdded = false;
if (augmentQueryBuilder(queryBuilder, DateFilterUtil.extractDateFilterVO(filters)))
{
anyRestrictionAdded = true;
}
if (augmentQueryBuilder(queryBuilder, ProductFilterUtil.extractProductFilterVO(filters)))
{
anyRestrictionAdded = true;
}
if (anyRestrictionAdded)
{
final IQuery<I_MD_Cockpit> query = augmentQueryBuilderWithOrderBy(queryBuilder).create();
return query;
}
else
{
// avoid memory problems in case the filters are accidentally empty
return queryBuilder.filter(ConstantQueryFilter.of(false)).create();
}
}
private IQueryBuilder<I_MD_Cockpit> createInitialQueryBuilder()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_MD_Cockpit> queryBuilder = queryBL
.createQueryBuilder(I_MD_Cockpit.class)
.addOnlyActiveRecordsFilter();
return queryBuilder;
}
private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final DateFilterVO dateFilterVO)
{
if (dateFilterVO == null)
{
return false;
}
final LocalDate date = dateFilterVO.getDate();
if (date == null)
{
return false;
}
queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.GREATER_OR_EQUAL, date); | queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.LESS, date.plusDays(1));
return true;
}
private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final ProductFilterVO productFilterVO)
{
final IQuery<I_M_Product> productQuery = ProductFilterUtil.createProductQueryOrNull(productFilterVO);
if (productQuery == null)
{
return false;
}
queryBuilder.addInSubQueryFilter(I_MD_Cockpit.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, productQuery);
return true;
}
private IQueryBuilder<I_MD_Cockpit> augmentQueryBuilderWithOrderBy(@NonNull final IQueryBuilder<I_MD_Cockpit> queryBuilder)
{
return queryBuilder
.orderByDescending(I_MD_Cockpit.COLUMNNAME_QtyStockEstimateSeqNo_AtDate)
.orderBy(I_MD_Cockpit.COLUMNNAME_DateGeneral)
.orderBy(I_MD_Cockpit.COLUMNNAME_M_Product_ID)
.orderBy(I_MD_Cockpit.COLUMNNAME_AttributesKey);
}
public LocalDate getFilterByDate(@NonNull final DocumentFilterList filters)
{
final DateFilterVO dateFilterVO = DateFilterUtil.extractDateFilterVO(filters);
return dateFilterVO.getDate();
}
public Predicate<I_M_Product> toProductFilterPredicate(@NonNull final DocumentFilterList filters)
{
return ProductFilterUtil.toPredicate(filters);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\MaterialCockpitFilters.java | 1 |
请完成以下Java代码 | public Integer getPriviledgeComment() {
return priviledgeComment;
}
public void setPriviledgeComment(Integer priviledgeComment) {
this.priviledgeComment = priviledgeComment;
}
public Integer getPriviledgePromotion() {
return priviledgePromotion;
}
public void setPriviledgePromotion(Integer priviledgePromotion) {
this.priviledgePromotion = priviledgePromotion;
}
public Integer getPriviledgeMemberPrice() {
return priviledgeMemberPrice;
}
public void setPriviledgeMemberPrice(Integer priviledgeMemberPrice) {
this.priviledgeMemberPrice = priviledgeMemberPrice;
}
public Integer getPriviledgeBirthday() {
return priviledgeBirthday;
}
public void setPriviledgeBirthday(Integer priviledgeBirthday) {
this.priviledgeBirthday = priviledgeBirthday;
}
public String getNote() {
return note;
}
public void setNote(String note) { | this.note = note;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", growthPoint=").append(growthPoint);
sb.append(", defaultStatus=").append(defaultStatus);
sb.append(", freeFreightPoint=").append(freeFreightPoint);
sb.append(", commentGrowthPoint=").append(commentGrowthPoint);
sb.append(", priviledgeFreeFreight=").append(priviledgeFreeFreight);
sb.append(", priviledgeSignIn=").append(priviledgeSignIn);
sb.append(", priviledgeComment=").append(priviledgeComment);
sb.append(", priviledgePromotion=").append(priviledgePromotion);
sb.append(", priviledgeMemberPrice=").append(priviledgeMemberPrice);
sb.append(", priviledgeBirthday=").append(priviledgeBirthday);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLevel.java | 1 |
请完成以下Java代码 | public void setName(String name) {
activiti5Task.setName(name);
}
@Override
public void setLocalizedName(String name) {
activiti5Task.setLocalizedName(name);
}
@Override
public void setDescription(String description) {
activiti5Task.setDescription(description);
}
@Override
public void setLocalizedDescription(String description) {
activiti5Task.setLocalizedDescription(description);
}
@Override
public void setPriority(int priority) {
activiti5Task.setPriority(priority);
}
@Override
public void setOwner(String owner) {
activiti5Task.setOwner(owner);
}
@Override
public void setAssignee(String assignee) {
activiti5Task.setAssignee(assignee);
}
@Override
public DelegationState getDelegationState() {
return activiti5Task.getDelegationState();
}
@Override
public void setDelegationState(DelegationState delegationState) {
activiti5Task.setDelegationState(delegationState);
}
@Override
public void setDueDate(Date dueDate) {
activiti5Task.setDueDate(dueDate);
}
@Override
public void setCategory(String category) { | activiti5Task.setCategory(category);
}
@Override
public void setParentTaskId(String parentTaskId) {
activiti5Task.setParentTaskId(parentTaskId);
}
@Override
public void setTenantId(String tenantId) {
activiti5Task.setTenantId(tenantId);
}
@Override
public void setFormKey(String formKey) {
activiti5Task.setFormKey(formKey);
}
@Override
public boolean isSuspended() {
return activiti5Task.isSuspended();
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5TaskWrapper.java | 1 |
请完成以下Java代码 | public DocTypeSequenceMap build()
{
return new DocTypeSequenceMap(this);
}
public void addDocSequenceId(final ClientId adClientId, final OrgId adOrgId, final DocSequenceId docSequenceId)
{
final DocTypeSequence docTypeSequence = new DocTypeSequence(adClientId, adOrgId, docSequenceId);
final ArrayKey key = mkKey(docTypeSequence.getAdClientId(), docTypeSequence.getAdOrgId());
docTypeSequences.put(key, docTypeSequence);
}
public Builder defaultDocNoSequenceId(final DocSequenceId defaultDocNoSequenceId)
{
this.defaultDocNoSequenceId = defaultDocNoSequenceId;
return this;
}
}
@Value | private static final class DocTypeSequence
{
private final ClientId adClientId;
private final OrgId adOrgId;
private final DocSequenceId docSequenceId;
private DocTypeSequence(
@Nullable final ClientId adClientId,
@Nullable final OrgId adOrgId,
@NonNull final DocSequenceId docSequenceId)
{
this.adClientId = adClientId != null ? adClientId : ClientId.SYSTEM;
this.adOrgId = adOrgId != null ? adOrgId : OrgId.ANY;
this.docSequenceId = docSequenceId;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\DocTypeSequenceMap.java | 1 |
请完成以下Java代码 | public class NullPointer {
private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class);
public static void main(String[] args) {
Person personObj = null;
try {
String name = personObj.personName; // Accessing the field of a null object
personObj.personName = "Jon Doe"; // Modifying the field of a null object
} catch (NullPointerException e) {
LOGGER.error("NullPointerException caught!");
} | }
}
class Person {
public String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
} | repos\tutorials-master\core-java-modules\core-java-exceptions-5\src\main\java\com\baeldung\exceptions\common\NullPointer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReactiveTransitionService {
final ReactiveProcessRepository repository;
final ReactiveMongoTemplate template;
final AtomicInteger counter = new AtomicInteger(0);
public Mono<Process> newProcess() {
return repository.save(new Process(counter.incrementAndGet(), State.CREATED, 0));
}
public Mono<Integer> run(Integer id) {
return lookup(id) //
.flatMap(process -> start(template, process)) //
.flatMap(it -> verify(it)) //
.flatMap(process -> finish(template, process)).map(Process::id);
}
private Mono<Process> finish(ReactiveMongoOperations operations, Process process) {
return operations.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.DONE).inc("transitionCount", 1)).first() //
.then(Mono.just(process));
}
Mono<Process> start(ReactiveMongoOperations operations, Process process) { | return operations.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.ACTIVE).inc("transitionCount", 1)).first() //
.then(Mono.just(process));
}
Mono<Process> lookup(Integer id) {
return repository.findById(id);
}
Mono<Process> verify(Process process) {
Assert.state(process.id() % 3 != 0, "We're sorry but we needed to drop that one");
return Mono.just(process);
}
} | repos\spring-data-examples-main\mongodb\transactions\src\main\java\example\springdata\mongodb\reactive\ReactiveTransitionService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public static class ServerRegionProperties {
public static final RegionShortcut DEFAULT_SERVER_REGION_SHORTCUT = RegionShortcut.PARTITION;
private RegionShortcut shortcut;
public RegionShortcut getShortcut() {
return this.shortcut != null ? this.shortcut : DEFAULT_SERVER_REGION_SHORTCUT;
}
public void setShortcut(RegionShortcut shortcut) {
this.shortcut = shortcut;
}
}
public static class SessionProperties {
@NestedConfigurationProperty
private final SessionAttributesProperties attributes = new SessionAttributesProperties();
@NestedConfigurationProperty
private final SessionExpirationProperties expiration = new SessionExpirationProperties();
@NestedConfigurationProperty
private final SessionRegionProperties region = new SessionRegionProperties();
@NestedConfigurationProperty
private final SessionSerializerProperties serializer = new SessionSerializerProperties();
public SessionAttributesProperties getAttributes() {
return this.attributes;
}
public SessionExpirationProperties getExpiration() {
return this.expiration;
}
public SessionRegionProperties getRegion() {
return this.region;
}
public SessionSerializerProperties getSerializer() {
return this.serializer;
}
}
public static class SessionAttributesProperties {
private String[] indexable;
public String[] getIndexable() {
return this.indexable;
}
public void setIndexable(String[] indexable) {
this.indexable = indexable;
}
}
public static class SessionExpirationProperties { | private int maxInactiveIntervalSeconds;
public int getMaxInactiveIntervalSeconds() {
return this.maxInactiveIntervalSeconds;
}
public void setMaxInactiveIntervalSeconds(int maxInactiveIntervalSeconds) {
this.maxInactiveIntervalSeconds = maxInactiveIntervalSeconds;
}
public void setMaxInactiveInterval(Duration duration) {
int maxInactiveIntervalInSeconds = duration != null
? Long.valueOf(duration.toSeconds()).intValue()
: GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS;
setMaxInactiveIntervalSeconds(maxInactiveIntervalInSeconds);
}
}
public static class SessionRegionProperties {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public static class SessionSerializerProperties {
private String beanName;
public String getBeanName() {
return this.beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\SpringSessionProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getREFERENCE() {
return reference;
}
/**
* Sets the value of the reference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCE(String value) {
this.reference = value;
}
/**
* Gets the value of the referenceline property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCELINE() {
return referenceline;
}
/**
* Sets the value of the referenceline property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCELINE(String value) {
this.referenceline = value;
}
/**
* Gets the value of the referencedate1 property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getREFERENCEDATE1() {
return referencedate1;
}
/**
* Sets the value of the referencedate1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE1(String value) {
this.referencedate1 = value;
}
/**
* Gets the value of the referencedate2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getREFERENCEDATE2() {
return referencedate2;
}
/**
* Sets the value of the referencedate2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setREFERENCEDATE2(String value) {
this.referencedate2 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DREFE1.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_ConversionRate_Rule_ID (final int C_ConversionRate_Rule_ID)
{
if (C_ConversionRate_Rule_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ConversionRate_Rule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ConversionRate_Rule_ID, C_ConversionRate_Rule_ID);
}
@Override
public int getC_ConversionRate_Rule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ConversionRate_Rule_ID);
}
@Override
public void setC_Currency_ID (final int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID);
}
@Override
public int getC_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_ID);
}
@Override
public void setC_Currency_To_ID (final int C_Currency_To_ID)
{
if (C_Currency_To_ID < 1)
set_Value (COLUMNNAME_C_Currency_To_ID, null);
else | set_Value (COLUMNNAME_C_Currency_To_ID, C_Currency_To_ID);
}
@Override
public int getC_Currency_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Currency_To_ID);
}
@Override
public void setMultiplyRate_Max (final @Nullable BigDecimal MultiplyRate_Max)
{
set_Value (COLUMNNAME_MultiplyRate_Max, MultiplyRate_Max);
}
@Override
public BigDecimal getMultiplyRate_Max()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Max);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMultiplyRate_Min (final @Nullable BigDecimal MultiplyRate_Min)
{
set_Value (COLUMNNAME_MultiplyRate_Min, MultiplyRate_Min);
}
@Override
public BigDecimal getMultiplyRate_Min()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MultiplyRate_Min);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionRate_Rule.java | 1 |
请完成以下Java代码 | public Object createValue(Class type, String value)
{
if (Enum.class.isAssignableFrom(type))
{
return Enum.valueOf(type, value);
}
return null;
}
};
private static final List<ValueCreator> DEFAULT_VALUE_CREATORS = Arrays.asList(Args.FROM_STRING_CONSTRUCTOR, Args.ENUM_CREATOR);
private static List<ValueCreator> valueCreators = new ArrayList<ValueCreator>(DEFAULT_VALUE_CREATORS);
/**
* Allows external extension of the valiue creators.
*
* @param vc another value creator to take into account for trying to create values | */
public static void registerValueCreator(ValueCreator vc)
{
valueCreators.add(vc);
}
/**
* Cleanup of registered ValueCreators (mainly for tests)
*/
public static void resetValueCreators()
{
valueCreators.clear();
valueCreators.addAll(DEFAULT_VALUE_CREATORS);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\cli\Args.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Sequence getSerialNo_Sequence()
{
return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class);
}
@Override
public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence)
{
set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence);
}
@Override
public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID)
{
if (SerialNo_Sequence_ID < 1)
set_Value (COLUMNNAME_SerialNo_Sequence_ID, null);
else
set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID);
}
@Override
public int getSerialNo_Sequence_ID()
{
return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
} | @Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOM.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_ChatTypeUpdate[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_User getAD_User() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_ChatType getCM_ChatType() throws RuntimeException
{
return (I_CM_ChatType)MTable.get(getCtx(), I_CM_ChatType.Table_Name)
.getPO(getCM_ChatType_ID(), get_TrxName()); }
/** Set Chat Type.
@param CM_ChatType_ID
Type of discussion / chat
*/
public void setCM_ChatType_ID (int CM_ChatType_ID)
{
if (CM_ChatType_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null); | else
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID));
}
/** Get Chat Type.
@return Type of discussion / chat
*/
public int getCM_ChatType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
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_CM_ChatTypeUpdate.java | 1 |
请完成以下Java代码 | public class Book {
private Long id;
private String author;
private String title;
private List<Rating> ratings;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) { | this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Rating> getRatings() {
return ratings;
}
public void setRatings(List<Rating> ratings) {
this.ratings = ratings;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\gateway\src\main\java\com\baeldung\spring\cloud\bootstrap\gateway\client\book\Book.java | 1 |
请完成以下Java代码 | public String getEmail() {
return super.getEmail();
}
@Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
@JsonIgnore
public boolean isPublic() {
if (getAdditionalInfo() != null && getAdditionalInfo().has("isPublic")) {
return getAdditionalInfo().get("isPublic").asBoolean();
}
return false;
}
@JsonIgnore
public ShortCustomerInfo toShortCustomerInfo() {
return new ShortCustomerInfo(id, title, isPublic());
}
@Override
@JsonProperty(access = Access.READ_ONLY)
@Schema(description = "Name of the customer. Read-only, duplicated from title for backward compatibility", example = "Company A", accessMode = Schema.AccessMode.READ_ONLY)
public String getName() {
return title;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [title=");
builder.append(title);
builder.append(", tenantId="); | builder.append(tenantId);
builder.append(", additionalInfo=");
builder.append(getAdditionalInfo());
builder.append(", country=");
builder.append(country);
builder.append(", state=");
builder.append(state);
builder.append(", city=");
builder.append(city);
builder.append(", address=");
builder.append(address);
builder.append(", address2=");
builder.append(address2);
builder.append(", zip=");
builder.append(zip);
builder.append(", phone=");
builder.append(phone);
builder.append(", email=");
builder.append(email);
builder.append(", createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Customer.java | 1 |
请完成以下Java代码 | public IHandlingUnitsInfo createFromModel(final Object model)
{
return null;
}
/**
* Does nothing.
*/
@Override
public void updateInvoiceDetail(final I_C_Invoice_Detail invoiceDetail, final IHandlingUnitsInfo handlingUnitsInfo)
{
// nothing
}
/**
* @return and ad-hoc implementation that actually works; TODO: fuse with the one in de.metas.materialtracking.
*/
@Override
public IHandlingUnitsInfoWritableQty createHUInfoWritableQty(@NonNull final IHandlingUnitsInfo wrappedHUInfo)
{
return new IHandlingUnitsInfoWritableQty()
{
private int qtyTU = wrappedHUInfo.getQtyTU();
@Override
public String getTUName()
{
return wrappedHUInfo.getTUName();
}
@Override
public int getQtyTU()
{ | return qtyTU;
}
@Override
public IHandlingUnitsInfo add(@NonNull final IHandlingUnitsInfo infoToAdd)
{
Check.assume(Objects.equals(infoToAdd.getTUName(), this.getTUName()), "infoToAdd {} has a TUName that differs from ours {}", infoToAdd, this);
return new PlainHandlingUnitsInfo(
wrappedHUInfo.getTUName(),
wrappedHUInfo.getQtyTU() + infoToAdd.getQtyTU());
}
@Override
public void setQtyTU(int qtyTU)
{
this.qtyTU = qtyTU;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\spi\impl\HandlingUnitsInfoFactory.java | 1 |
请完成以下Java代码 | private static int findMainSqlSelectIndex(final List<SqlSelect> sqlSelects)
{
final int sqlSelectsCount = sqlSelects.size();
if (sqlSelectsCount == 0)
{
// TODO: shall we throw ex?
return -1;
}
else if (sqlSelectsCount == 1)
{
return 0;
}
else
{
for (int i = sqlSelectsCount - 1; i >= 0; i--)
{
final SqlSelect sqlSelect = sqlSelects.get(i);
if (sqlSelect.getSql().charAt(0) != '(')
{
return i;
}
}
return -1;
}
}
public SqlSelect getMainSqlSelect()
{
return sqlSelects.get(mainSqlIndex);
}
/**
* Transform the key words WHERE, FROM and ON in lowercase.
* TODO: Delete this logic when we get rid of the workaround in org.compiere.model.AccessSqlParser.getTableInfo(String)
*
* @param whereClause
* @return
*/
public static String rewriteWhereClauseWithLowercaseKeyWords(final String whereClause)
{
return whereClause.replaceAll("\\s", " ")
.replaceAll(WHERE, WHERE_LOWERCASE)
.replaceAll(FROM, FROM_LOWERCASE)
.replaceAll(ON, ON_LOWERCASE);
}
@Value
public static class TableNameAndAlias
{
public static TableNameAndAlias ofTableNameAndAlias(final String tableName, final String alias)
{
return new TableNameAndAlias(tableName, alias);
}
public static TableNameAndAlias ofTableName(final String tableName)
{
final String synonym = "";
return new TableNameAndAlias(tableName, synonym);
}
private final String tableName;
private final String alias;
private TableNameAndAlias(@NonNull final String tableName, final String alias)
{
this.tableName = tableName;
this.alias = alias != null ? alias : "";
}
public String getAliasOrTableName()
{
return !alias.isEmpty() ? alias : tableName;
}
public boolean isTrlTable()
{ | return tableName.toUpperCase().endsWith("_TRL");
}
}
@Value
public static final class SqlSelect
{
private final String sql;
private final ImmutableList<TableNameAndAlias> tableNameAndAliases;
@Builder
private SqlSelect(
@NonNull final String sql,
@NonNull @Singular final ImmutableList<TableNameAndAlias> tableNameAndAliases)
{
this.sql = sql;
this.tableNameAndAliases = tableNameAndAliases;
}
public boolean hasWhereClause()
{
return sql.indexOf(" WHERE ") >= 0;
}
public String getFirstTableAliasOrTableName()
{
if (tableNameAndAliases.isEmpty()) // TODO check if we still need this check!
{
return "";
}
return tableNameAndAliases.get(0).getAliasOrTableName();
}
public String getFirstTableNameOrEmpty()
{
if (tableNameAndAliases.isEmpty())
{
return "";
}
return tableNameAndAliases.get(0).getTableName();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\ParsedSql.java | 1 |
请完成以下Java代码 | public void invalidate(final I_M_DeliveryDay deliveryDay)
{
Check.assumeNotNull(deliveryDay, "deliveryDay not null");
// TODO: implement
}
/**
* Sets DeliveryDateTimeMax = DeliveryDate + BufferHours.
*
* @param deliveryDay
*/
@Override
public void setDeliveryDateTimeMax(final I_M_DeliveryDay deliveryDay)
{
final Timestamp deliveryDate = deliveryDay.getDeliveryDate();
final int bufferHours = deliveryDay.getBufferHours();
final Timestamp deliveryDateTimeMax = TimeUtil.addHours(deliveryDate, bufferHours);
deliveryDay.setDeliveryDateTimeMax(deliveryDateTimeMax);
}
/**
* The search will initially be made for the first deliveryDay of the day of the promised date.
* For example, if there are 3 deliveryDay entries for a certain date and the products are
* promised to be shipped in that day's evening, the first deliveryDay of that day will be chosen.
* If there are no deliveryDay entries for the given date that are before the promised date/time,
* select the last available deliveryDay that is before the promised date/time
*/
@NonNull
@Override
public ImmutablePair<TourId, ZonedDateTime> calculateTourAndPreparationDate(
@NonNull final IContextAware context,
@NonNull final SOTrx soTrx,
@NonNull final ZonedDateTime calculationTime,
@NonNull final ZonedDateTime datePromised,
@NonNull final BPartnerLocationId bpartnerLocationId)
{
LocalDate preparationDay = datePromised.toLocalDate(); | //
// Create Delivery Day Query Parameters
final PlainDeliveryDayQueryParams deliveryDayQueryParams = new PlainDeliveryDayQueryParams();
deliveryDayQueryParams.setBPartnerLocationId(bpartnerLocationId);
deliveryDayQueryParams.setDeliveryDate(datePromised);
deliveryDayQueryParams.setToBeFetched(soTrx.isPurchase());
deliveryDayQueryParams.setProcessed(false);
deliveryDayQueryParams.setCalculationTime(calculationTime);
deliveryDayQueryParams.setPreparationDay(preparationDay);
//
// Find matching delivery day record
final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class);
I_M_DeliveryDay dd = deliveryDayDAO.retrieveDeliveryDay(context, deliveryDayQueryParams);
// No same-day deliveryDay found => chose the closest one
if (dd == null)
{
preparationDay = null;
deliveryDayQueryParams.setPreparationDay(preparationDay);
dd = deliveryDayDAO.retrieveDeliveryDay(context, deliveryDayQueryParams);
}
//
// Extract PreparationDate from DeliveryDay record
final ImmutablePair<TourId, ZonedDateTime> ret;
if (dd == null)
{
ret = ImmutablePair.of(null, null);
}
else
{
ret = ImmutablePair.of(TourId.ofRepoIdOrNull(dd.getM_Tour_ID()), TimeUtil.asZonedDateTime(dd.getDeliveryDate()));
}
return ret;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\DeliveryDayBL.java | 1 |
请完成以下Java代码 | public boolean stopCellEditing()
{
try
{
return super.stopCellEditing();
}
catch (Exception e)
{
final Component comp = (Component)m_editor;
final int windowNo = Env.getWindowNo(comp);
Services.get(IClientUI.class).warn(windowNo, e);
}
return false;
}
@Override
public void cancelCellEditing()
{
super.cancelCellEditing();
}
private Object convertToEditorValue(final Object valueModel) | {
final Object valueEditor;
if (valueModel instanceof KeyNamePair && editorValueClass == Integer.class)
{
valueEditor = ((KeyNamePair)valueModel).getKey();
}
else
{
valueEditor = valueModel;
}
return valueEditor;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableModelCellEditor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StatsdPropertiesConfigAdapter extends PropertiesConfigAdapter<StatsdProperties> implements StatsdConfig {
public StatsdPropertiesConfigAdapter(StatsdProperties properties) {
super(properties);
}
@Override
public @Nullable String get(String s) {
return null;
}
@Override
public String prefix() {
return "management.statsd.metrics.export";
}
@Override
public StatsdFlavor flavor() {
return obtain(StatsdProperties::getFlavor, StatsdConfig.super::flavor);
}
@Override
public boolean enabled() {
return obtain(StatsdProperties::isEnabled, StatsdConfig.super::enabled);
}
@Override
public String host() {
return obtain(StatsdProperties::getHost, StatsdConfig.super::host);
}
@Override
public int port() {
return obtain(StatsdProperties::getPort, StatsdConfig.super::port);
}
@Override
public StatsdProtocol protocol() {
return obtain(StatsdProperties::getProtocol, StatsdConfig.super::protocol); | }
@Override
public int maxPacketLength() {
return obtain(StatsdProperties::getMaxPacketLength, StatsdConfig.super::maxPacketLength);
}
@Override
public Duration pollingFrequency() {
return obtain(StatsdProperties::getPollingFrequency, StatsdConfig.super::pollingFrequency);
}
@Override
public Duration step() {
return obtain(StatsdProperties::getStep, StatsdConfig.super::step);
}
@Override
public boolean publishUnchangedMeters() {
return obtain(StatsdProperties::isPublishUnchangedMeters, StatsdConfig.super::publishUnchangedMeters);
}
@Override
public boolean buffered() {
return obtain(StatsdProperties::isBuffered, StatsdConfig.super::buffered);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\statsd\StatsdPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public Object getFieldValue(String fieldName) {
return this.fieldValues.get(fieldName);
}
public void setFieldValue(String fieldName, Object value) {
this.fieldValues.put(fieldName, value);
}
public int getFieldSize() {
return this.structureDefinition.getFieldSize();
}
public String getFieldNameAt(int index) {
return this.structureDefinition.getFieldNameAt(index);
}
public Object[] toArray() {
int fieldSize = this.getFieldSize(); | Object[] arguments = new Object[fieldSize];
for (int i = 0; i < fieldSize; i++) {
String fieldName = this.getFieldNameAt(i);
Object argument = this.getFieldValue(fieldName);
arguments[i] = argument;
}
return arguments;
}
public void loadFrom(Object[] array) {
int fieldSize = this.getFieldSize();
for (int i = 0; i < fieldSize; i++) {
String fieldName = this.getFieldNameAt(i);
Object fieldValue = array[i];
this.setFieldValue(fieldName, fieldValue);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\data\FieldBaseStructureInstance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private String getAction(ConnectionFactoryBeanCreationException cause) {
StringBuilder action = new StringBuilder();
action.append(String.format("Consider the following:%n"));
if (EmbeddedDatabaseConnection.NONE == cause.getEmbeddedDatabaseConnection()) {
action.append(String.format("\tIf you want an embedded database (H2), please put it on the classpath.%n"));
}
else {
action.append(String.format("\tReview the configuration of %s%n.", cause.getEmbeddedDatabaseConnection()));
}
action
.append("\tIf you have database settings to be loaded from a particular "
+ "profile you may need to activate it")
.append(getActiveProfiles());
return action.toString();
} | private String getActiveProfiles() {
StringBuilder message = new StringBuilder();
String[] profiles = this.environment.getActiveProfiles();
if (ObjectUtils.isEmpty(profiles)) {
message.append(" (no profiles are currently active).");
}
else {
message.append(" (the profiles ");
message.append(StringUtils.arrayToCommaDelimitedString(profiles));
message.append(" are currently active).");
}
return message.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryBeanCreationFailureAnalyzer.java | 2 |
请完成以下Java代码 | protected boolean lockJobIfNeeded() {
try {
if (job.isExclusive()) {
processEngineConfiguration.getCommandExecutor().execute(new LockExclusiveJobCmd(job));
}
} catch (Throwable lockException) {
if (log.isDebugEnabled()) {
log.debug(
"Could not lock exclusive job. Unlocking job so it can be acquired again. Catched exception: " +
lockException.getMessage()
);
}
// Release the job again so it can be acquired later or by another node
unacquireJob();
return false;
}
return true;
}
protected void unacquireJob() {
CommandContext commandContext = Context.getCommandContext();
if (commandContext != null) {
commandContext.getJobManager().unacquire(job);
} else {
processEngineConfiguration
.getCommandExecutor()
.execute( | new Command<Void>() {
public Void execute(CommandContext commandContext) {
commandContext.getJobManager().unacquire(job);
return null;
}
}
);
}
}
protected void handleFailedJob(final Throwable exception) {
processEngineConfiguration
.getCommandExecutor()
.execute(new HandleFailedJobCmd(jobId, processEngineConfiguration, exception));
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\ExecuteAsyncRunnable.java | 1 |
请完成以下Java代码 | public void save(final I_AD_Process process)
{
InterfaceWrapperHelper.save(process);
}
@Override
public void updateColumnNameByAdElementId(
@NonNull final AdElementId adElementId,
@Nullable final String newColumnName)
{
// NOTE: accept newColumnName to be null and expect to fail in case there is an AD_Process_Para which is using given AD_Element_ID
DB.executeUpdateAndThrowExceptionOnFail(
// Inline parameters because this sql will be logged into the migration script.
"UPDATE " + I_AD_Process_Para.Table_Name + " SET ColumnName=" + DB.TO_STRING(newColumnName) + " WHERE AD_Element_ID=" + adElementId.getRepoId(),
ITrx.TRXNAME_ThreadInherited);
}
@Override
public ProcessType retrieveProcessType(@NonNull final AdProcessId processId)
{
final I_AD_Process process = InterfaceWrapperHelper.loadOutOfTrx(processId, I_AD_Process.class);
return ProcessType.ofCode(process.getType());
}
@Override
public ImmutableSet<AdProcessId> retrieveAllActiveAdProcesIds() | {
return queryBL.createQueryBuilderOutOfTrx(I_AD_Process.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_Process.COLUMNNAME_AD_Process_ID)
.create()
.idsAsSet(AdProcessId::ofRepoId);
}
@NonNull
@Override
public List<I_AD_Process> retrieveProcessRecordsByValRule(@NonNull final AdValRuleId valRuleId)
{
return queryBL.createQueryBuilder(I_AD_Process.class)
.addOnlyActiveRecordsFilter()
.filter(new ValidationRuleQueryFilter<>(I_AD_Process.Table_Name, valRuleId))
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\impl\ADProcessDAO.java | 1 |
请完成以下Java代码 | public EventDefinitionQueryImpl withoutTenantId() {
this.withoutTenantId = true;
return this;
}
// sorting ////////////////////////////////////////////
@Override
public EventDefinitionQuery orderByDeploymentId() {
return orderBy(EventDefinitionQueryProperty.DEPLOYMENT_ID);
}
@Override
public EventDefinitionQuery orderByEventDefinitionKey() {
return orderBy(EventDefinitionQueryProperty.KEY);
}
@Override
public EventDefinitionQuery orderByEventDefinitionCategory() {
return orderBy(EventDefinitionQueryProperty.CATEGORY);
}
@Override
public EventDefinitionQuery orderByEventDefinitionId() {
return orderBy(EventDefinitionQueryProperty.ID);
}
@Override
public EventDefinitionQuery orderByEventDefinitionName() {
return orderBy(EventDefinitionQueryProperty.NAME);
}
@Override
public EventDefinitionQuery orderByTenantId() {
return orderBy(EventDefinitionQueryProperty.TENANT_ID);
}
// results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getEventDefinitionEntityManager(commandContext).findEventDefinitionCountByQueryCriteria(this);
}
@Override
public List<EventDefinition> executeList(CommandContext commandContext) {
return CommandContextUtil.getEventDefinitionEntityManager(commandContext).findEventDefinitionsByQueryCriteria(this);
}
// getters ////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public Set<String> getDeploymentIds() {
return deploymentIds;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getId() {
return id;
}
public Set<String> getIds() {
return ids;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
} | public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getKeyLikeIgnoreCase() {
return keyLikeIgnoreCase;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventDefinitionQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CloudFoundryWebEndpointDiscoverer extends WebEndpointDiscoverer {
/**
* Create a new {@link WebEndpointDiscoverer} instance.
* @param applicationContext the source application context
* @param parameterValueMapper the parameter value mapper
* @param endpointMediaTypes the endpoint media types
* @param endpointPathMappers the endpoint path mappers
* @param invokerAdvisors invoker advisors to apply
* @param endpointFilters endpoint filters to apply
* @param operationFilters operation filters to apply
*/
public CloudFoundryWebEndpointDiscoverer(ApplicationContext applicationContext,
ParameterValueMapper parameterValueMapper, EndpointMediaTypes endpointMediaTypes,
@Nullable List<PathMapper> endpointPathMappers, Collection<OperationInvokerAdvisor> invokerAdvisors,
Collection<EndpointFilter<ExposableWebEndpoint>> endpointFilters,
Collection<OperationFilter<WebOperation>> operationFilters) {
super(applicationContext, parameterValueMapper, endpointMediaTypes, endpointPathMappers, null, invokerAdvisors,
endpointFilters, operationFilters);
}
@Override
protected boolean isExtensionTypeExposed(Class<?> extensionBeanType) {
// Filter regular health endpoint extensions so a CF version can replace them
return !isHealthEndpointExtension(extensionBeanType)
|| isCloudFoundryHealthEndpointExtension(extensionBeanType);
} | private boolean isHealthEndpointExtension(Class<?> extensionBeanType) {
return MergedAnnotations.from(extensionBeanType)
.get(EndpointWebExtension.class)
.getValue("endpoint", Class.class)
.map(HealthEndpoint.class::isAssignableFrom)
.orElse(false);
}
private boolean isCloudFoundryHealthEndpointExtension(Class<?> extensionBeanType) {
return MergedAnnotations.from(extensionBeanType).isPresent(EndpointCloudFoundryExtension.class);
}
static class CloudFoundryWebEndpointDiscovererRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection()
.registerType(CloudFoundryEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\CloudFoundryWebEndpointDiscoverer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Object ping() {
log.info("进入ping");
return "pong study";
}
@RequestMapping("log")
public Object log() {
log.info("this is info log");
log.error("this is error log");
log.debug("this is debug log");
log.warn("this is warn log");
log.trace("this is trace log");
return "123";
}
@RequestMapping("http")
public Object httpQuery() {
String studyUrl = "http://localhost:8088/ping";
URI studyUri = URI.create(studyUrl);
String study = restTemplate.getForObject(studyUri, String.class); | log.info("study:{}", study);
String floorUrl = "http://localhost:8088/log";
URI floorUri = URI.create(floorUrl);
String floor = restTemplate.getForObject(floorUri, String.class);
log.info("floor:{}", floor);
String roomUrl = "http://localhost:8088/ping";
URI roomUri = URI.create(roomUrl);
String room = restTemplate.getForObject(roomUri, String.class);
log.info("room:{}", room);
return study + "-------" + floor + "-------" + room + "-------";
}
} | repos\springboot-demo-master\zipkin\src\main\java\com\et\zipkin\controller\HelloWorldController.java | 2 |
请完成以下Java代码 | public String getNm() {
return nm;
}
/**
* Sets the value of the nm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNm(String value) {
this.nm = value;
}
/**
* Gets the value of the pstlAdr property.
*
* @return
* possible object is
* {@link PostalAddressSEPA }
*
*/
public PostalAddressSEPA getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link PostalAddressSEPA }
* | */
public void setPstlAdr(PostalAddressSEPA value) {
this.pstlAdr = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link PartySEPAChoice }
*
*/
public PartySEPAChoice getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link PartySEPAChoice }
*
*/
public void setId(PartySEPAChoice value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PartyIdentificationSEPA2.java | 1 |
请完成以下Java代码 | public void setMSGRAPH_TenantId (final @Nullable java.lang.String MSGRAPH_TenantId)
{
set_Value (COLUMNNAME_MSGRAPH_TenantId, MSGRAPH_TenantId);
}
@Override
public java.lang.String getMSGRAPH_TenantId()
{
return get_ValueAsString(COLUMNNAME_MSGRAPH_TenantId);
}
@Override
public void setPassword (final @Nullable java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setSMTPHost (final @Nullable java.lang.String SMTPHost)
{
set_Value (COLUMNNAME_SMTPHost, SMTPHost);
}
@Override
public java.lang.String getSMTPHost()
{
return get_ValueAsString(COLUMNNAME_SMTPHost);
}
@Override
public void setSMTPPort (final int SMTPPort)
{
set_Value (COLUMNNAME_SMTPPort, SMTPPort);
}
@Override
public int getSMTPPort()
{
return get_ValueAsInt(COLUMNNAME_SMTPPort);
}
/**
* Type AD_Reference_ID=541904
* Reference name: AD_MailBox_Type
*/
public static final int TYPE_AD_Reference_ID=541904;
/** SMTP = smtp */
public static final String TYPE_SMTP = "smtp";
/** MSGraph = msgraph */
public static final String TYPE_MSGraph = "msgraph"; | @Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PayBizException extends BizException {
/**
*
*/
private static final long serialVersionUID = -7163126205323125757L;
/** 支付方式已存在 **/
public static final int PAY_TYPE_IS_EXIST = 101;
/** 支付产品已存在 **/
public static final int PAY_PRODUCT_IS_EXIST = 102;
/** 支付产品已关联数据 **/
public static final int PAY_PRODUCT_HAS_DATA = 103;
/** 用户支付配置已存在 **/
public static final int USER_PAY_CONFIG_IS_EXIST = 104;
/** 用户支付配置不存在 **/
public static final int USER_PAY_CONFIG_IS_NOT_EXIST = 105;
/** 用户支付配置已生效 **/
public static final int USER_PAY_CONFIG_IS_EFFECTIVE = 106;
/** 支付产品已生效 **/
public static final int PAY_PRODUCT_IS_EFFECTIVE = 107;
/** 支付产品不存在 **/
public static final int PAY_PRODUCT_IS_NOT_EXIST = 108;
/** 支付方式不存在 **/
public static final int PAY_TYPE_IS_NOT_EXIST = 109;
/** 请求参数异常 **/
public static final int REQUEST_PARAM_ERR = 110;
/**
* 请求银行异常
*/
public static final int REQUEST_BANK_ERR = 111; | private static final Log LOG = LogFactory.getLog(PayBizException.class);
public PayBizException() {
}
public PayBizException(int code, String msgFormat, Object... args) {
super(code, msgFormat, args);
}
public PayBizException(int code, String msg) {
super(code, msg);
}
public PayBizException print() {
LOG.info("==>BizException, code:" + this.code + ", msg:" + this.msg);
return this;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\exception\PayBizException.java | 2 |
请完成以下Java代码 | public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
}
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("endTime", endTime);
persistentState.put("executionStartTime", executionStartTime);
return persistentState;
} | public void delete() {
HistoricIncidentManager historicIncidentManager = Context.getCommandContext().getHistoricIncidentManager();
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(seedJobDefinitionId);
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(monitorJobDefinitionId);
historicIncidentManager.deleteHistoricIncidentsByJobDefinitionId(batchJobDefinitionId);
HistoricJobLogManager historicJobLogManager = Context.getCommandContext().getHistoricJobLogManager();
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(seedJobDefinitionId);
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(monitorJobDefinitionId);
historicJobLogManager.deleteHistoricJobLogsByJobDefinitionId(batchJobDefinitionId);
Context.getCommandContext().getHistoricBatchManager().delete(this);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\history\HistoricBatchEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<ChannelDefinitionResponse> createChannelDefinitionResponseList(List<ChannelDefinition> channelDefinitions) {
RestUrlBuilder urlBuilder = createUrlBuilder();
List<ChannelDefinitionResponse> responseList = new ArrayList<>(channelDefinitions.size());
for (ChannelDefinition channelDef : channelDefinitions) {
responseList.add(createChannelDefinitionResponse(channelDef, urlBuilder));
}
return responseList;
}
public ChannelDefinitionResponse createChannelDefinitionResponse(ChannelDefinition channelDefinition) {
return createChannelDefinitionResponse(channelDefinition, createUrlBuilder());
}
public ChannelDefinitionResponse createChannelDefinitionResponse(ChannelDefinition channelDefinition, RestUrlBuilder urlBuilder) {
ChannelDefinitionResponse response = new ChannelDefinitionResponse();
response.setUrl(urlBuilder.buildUrl(EventRestUrls.URL_CHANNEL_DEFINITION, channelDefinition.getId()));
response.setId(channelDefinition.getId());
response.setKey(channelDefinition.getKey());
response.setVersion(channelDefinition.getVersion());
response.setCategory(channelDefinition.getCategory());
response.setName(channelDefinition.getName());
response.setType(channelDefinition.getType());
response.setImplementation(channelDefinition.getImplementation());
response.setCreateTime(channelDefinition.getCreateTime());
response.setDescription(channelDefinition.getDescription());
response.setTenantId(channelDefinition.getTenantId());
// Links to other resources
response.setDeploymentId(channelDefinition.getDeploymentId());
response.setResourceName(channelDefinition.getResourceName());
response.setDeploymentUrl(urlBuilder.buildUrl(EventRestUrls.URL_DEPLOYMENT, channelDefinition.getDeploymentId())); | response.setResource(urlBuilder.buildUrl(EventRestUrls.URL_DEPLOYMENT_RESOURCE, channelDefinition.getDeploymentId(), channelDefinition.getResourceName()));
return response;
}
protected String formatUrl(String serverRootUrl, String[] fragments, Object... arguments) {
StringBuilder urlBuilder = new StringBuilder(serverRootUrl);
for (String urlFragment : fragments) {
urlBuilder.append("/");
urlBuilder.append(MessageFormat.format(urlFragment, arguments));
}
return urlBuilder.toString();
}
protected RestUrlBuilder createUrlBuilder() {
return RestUrlBuilder.fromCurrentRequest();
}
} | repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\EventRegistryRestResponseFactory.java | 2 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIncrementNo (final int IncrementNo)
{
set_Value (COLUMNNAME_IncrementNo, IncrementNo);
}
@Override
public int getIncrementNo()
{
return get_ValueAsInt(COLUMNNAME_IncrementNo);
}
@Override
public void setIsAudited (final boolean IsAudited)
{
set_Value (COLUMNNAME_IsAudited, IsAudited);
}
@Override
public boolean isAudited()
{
return get_ValueAsBoolean(COLUMNNAME_IsAudited);
}
@Override
public void setIsAutoSequence (final boolean IsAutoSequence)
{
set_Value (COLUMNNAME_IsAutoSequence, IsAutoSequence);
}
@Override
public boolean isAutoSequence()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoSequence);
}
@Override
public void setIsTableID (final boolean IsTableID)
{
set_Value (COLUMNNAME_IsTableID, IsTableID);
}
@Override
public boolean isTableID()
{
return get_ValueAsBoolean(COLUMNNAME_IsTableID);
}
@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 setPrefix (final @Nullable java.lang.String Prefix)
{
set_Value (COLUMNNAME_Prefix, Prefix);
}
@Override
public java.lang.String getPrefix()
{
return get_ValueAsString(COLUMNNAME_Prefix);
}
/**
* RestartFrequency AD_Reference_ID=541879
* Reference name: AD_SequenceRestart Frequency
*/
public static final int RESTARTFREQUENCY_AD_Reference_ID=541879;
/** Year = Y */
public static final String RESTARTFREQUENCY_Year = "Y";
/** Month = M */
public static final String RESTARTFREQUENCY_Month = "M";
/** Day = D */
public static final String RESTARTFREQUENCY_Day = "D";
@Override
public void setRestartFrequency (final @Nullable java.lang.String RestartFrequency) | {
set_Value (COLUMNNAME_RestartFrequency, RestartFrequency);
}
@Override
public java.lang.String getRestartFrequency()
{
return get_ValueAsString(COLUMNNAME_RestartFrequency);
}
@Override
public void setStartNo (final int StartNo)
{
set_Value (COLUMNNAME_StartNo, StartNo);
}
@Override
public int getStartNo()
{
return get_ValueAsInt(COLUMNNAME_StartNo);
}
@Override
public void setSuffix (final @Nullable java.lang.String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
@Override
public java.lang.String getSuffix()
{
return get_ValueAsString(COLUMNNAME_Suffix);
}
@Override
public void setVFormat (final @Nullable java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
@Override
public java.lang.String getVFormat()
{
return get_ValueAsString(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GraphQLConfig {
@Bean
public GraphQL graphQL() {
SchemaParser schemaParser = new SchemaParser();
SchemaGenerator schemaGenerator = new SchemaGenerator();
TypeDefinitionRegistry typeRegistry = schemaParser.parse(
new InputStreamReader(getClass().getResourceAsStream("/schema.graphqls"))
);
RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
.type("Mutation", builder ->
builder.dataFetcher("updateProfile", new MutationResolver().updateProfile())
)
.type("AnydataResponse", typeWiring ->
typeWiring.typeResolver(env -> { | Object javaObject = env.getObject();
if (javaObject instanceof SimpleMessage) {
return env.getSchema().getObjectType("SimpleMessage");
} else if (javaObject instanceof UserProfile) {
return env.getSchema().getObjectType("UserProfile");
}
return null;
})
)
.build();
GraphQLSchema schema = schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
return GraphQL.newGraphQL(schema).build();
}
} | repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphqlanydata\GraphQLConfig.java | 2 |
请完成以下Java代码 | public void fireDocumentNoChange(final Object model, final String newDocumentNo)
{
final String tableName = InterfaceWrapperHelper.getModelTableNameOrNull(model);
if (Check.isEmpty(tableName))
{
return;
}
final IDocumentNoListener documentNoListener = listeners.get(tableName);
if (documentNoListener == null)
{
return;
}
final Optional<IDocumentNoAware> documentNoAware = asDocumentNoAware(model);
if (!documentNoAware.isPresent()) | {
return;
}
documentNoListener.onDocumentNoChange(documentNoAware.get(), newDocumentNo);
}
@Override
public Optional<IDocumentNoAware> asDocumentNoAware(final Object model)
{
final IDocumentNoAware documentNoAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(model, IDocumentNoAware.class);
return Optional.of(documentNoAware);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getSecurityMoney() {
return securityMoney;
}
public void setSecurityMoney(BigDecimal securityMoney) {
this.securityMoney = securityMoney;
}
public BigDecimal getTotalIncome() {
return totalIncome;
}
public void setTotalIncome(BigDecimal totalIncome) {
this.totalIncome = totalIncome;
}
public BigDecimal getTotalExpend() {
return totalExpend;
}
public void setTotalExpend(BigDecimal totalExpend) {
this.totalExpend = totalExpend;
}
public BigDecimal getTodayIncome() {
return todayIncome;
}
public void setTodayIncome(BigDecimal todayIncome) {
this.todayIncome = todayIncome;
}
public BigDecimal getTodayExpend() {
return todayExpend;
}
public void setTodayExpend(BigDecimal todayExpend) { | this.todayExpend = todayExpend;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType == null ? null : accountType.trim();
}
public BigDecimal getSettAmount() {
return settAmount;
}
public void setSettAmount(BigDecimal settAmount) {
this.settAmount = settAmount;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccount.java | 2 |
请完成以下Java代码 | public String firstNotBlank(@Nullable final Supplier<String>... valueSuppliers)
{
if(valueSuppliers == null)
{
return null;
}
for (final Supplier<String> valueSupplier : valueSuppliers)
{
if (valueSupplier == null)
{
continue;
}
final String value = valueSupplier.get();
final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm != null)
{
return valueNorm;
}
}
return null;
}
public boolean isAllNotNulls(final Object... values)
{
for (final Object value : values)
{
if (value == null)
{
return false;
}
}
return true;
}
public int countNotNulls(@Nullable final Object... values)
{
if (values == null || values.length == 0) | {
return 0;
}
int count = 0;
for (final Object value : values)
{
if (value != null)
{
count++;
}
}
return count;
}
@NonNull
public BigDecimal firstPositiveOrZero(final BigDecimal... values)
{
if (values == null)
{
return BigDecimal.ZERO;
}
for (final BigDecimal value : values)
{
if (value != null && value.signum() > 0)
{
return value;
}
}
return BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\CoalesceUtil.java | 1 |
请完成以下Java代码 | private ITranslatableString getWarehouseName(final WarehouseId warehouseId)
{
return warehouseNames.computeIfAbsent(warehouseId, this::retrieveWarehouseName);
}
private ITranslatableString retrieveWarehouseName(WarehouseId warehouseId)
{
return TranslatableStrings.anyLanguage(warehouseService.getWarehouseName(warehouseId));
}
private ITranslatableString getSalesOrderDocumentNo(final OrderId orderId)
{
return salesOrderDocumentNos.computeIfAbsent(orderId, this::retrieveOrderDocumentNo);
}
private ITranslatableString retrieveOrderDocumentNo(final OrderId orderId)
{
return TranslatableStrings.anyLanguage(sourceDocService.getDocumentNoById(orderId));
}
private ITranslatableString getManufacturingOrderDocumentNo(final PPOrderId manufacturingOrderId)
{
return manufacturingOrderDocumentNos.computeIfAbsent(manufacturingOrderId, this::retrieveManufacturingOrderDocumentNo);
}
private ITranslatableString retrieveManufacturingOrderDocumentNo(final PPOrderId manufacturingOrderId)
{
return TranslatableStrings.anyLanguage(sourceDocService.getDocumentNoById(manufacturingOrderId));
}
private ITranslatableString getProductName(final ProductId productId)
{
return productNames.computeIfAbsent(productId, this::retrieveProductName);
}
private ITranslatableString retrieveProductName(final ProductId productId)
{
return TranslatableStrings.anyLanguage(productService.getProductValueAndName(productId));
}
@NonNull
public static Quantity extractQtyEntered(final I_DD_OrderLine ddOrderLine)
{
return Quantitys.of(ddOrderLine.getQtyEntered(), UomId.ofRepoId(ddOrderLine.getC_UOM_ID()));
} | private void processPendingRequests()
{
if (!pendingCollectProductsFromDDOrderIds.isEmpty())
{
ddOrderService.getProductIdsByDDOrderIds(pendingCollectProductsFromDDOrderIds)
.forEach(this::collectProduct);
pendingCollectProductsFromDDOrderIds.clear();
}
if (!pendingCollectQuantitiesFromDDOrderIds.isEmpty())
{
ddOrderService.streamLinesByDDOrderIds(pendingCollectQuantitiesFromDDOrderIds)
.forEach(this::collectQuantity);
pendingCollectQuantitiesFromDDOrderIds.clear();
}
}
private ITranslatableString getPlantName(final ResourceId resourceId)
{
return resourceNames.computeIfAbsent(resourceId, id -> TranslatableStrings.constant(sourceDocService.getPlantName(id)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetsCollector.java | 1 |
请完成以下Java代码 | public Long getRid() {
return rid;
}
public void setRid(Long rid) {
this.rid = rid;
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
public String getRdesc() {
return rdesc;
}
public void setRdesc(String rdesc) {
this.rdesc = rdesc;
}
public String getRval() {
return rval;
}
public void setRval(String rval) {
this.rval = rval;
} | public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
} | repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\Role.java | 1 |
请完成以下Java代码 | public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public void setCaseExecutionId(String caseExecutionId) {
this.caseExecutionId = caseExecutionId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getOperationType() {
return operationType;
}
public void setOperationType(String operationType) {
this.operationType = operationType;
}
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
public List<PropertyChange> getPropertyChanges() {
return propertyChanges;
}
public void setPropertyChanges(List<PropertyChange> propertyChanges) {
this.propertyChanges = propertyChanges;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) { | this.batchId = batchId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityUtil {
private Logger logger = LoggerFactory.getLogger(SecurityUtil.class);
@Autowired
private UserDetailsService userDetailsService;
public void logInAs(String username) {
UserDetails user = userDetailsService.loadUserByUsername(username);
if (user == null) {
throw new IllegalStateException("User " + username + " doesn't exist, please provide a valid user");
}
logger.info("> Logged in as: " + username);
SecurityContextHolder.setContext(
new SecurityContextImpl(
new Authentication() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getAuthorities();
}
@Override
public Object getCredentials() {
return user.getPassword();
}
@Override
public Object getDetails() {
return user;
}
@Override
public Object getPrincipal() {
return user;
}
@Override | public boolean isAuthenticated() {
return true;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {}
@Override
public String getName() {
return user.getUsername();
}
}
)
);
org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);
}
} | repos\Activiti-develop\activiti-examples\activiti-api-basic-connector-example\src\main\java\org\activiti\examples\SecurityUtil.java | 2 |
请完成以下Java代码 | public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricDecisionOutputInstanceDto fromHistoricDecisionOutputInstance(HistoricDecisionOutputInstance historicDecisionOutputInstance) {
HistoricDecisionOutputInstanceDto dto = new HistoricDecisionOutputInstanceDto();
dto.id = historicDecisionOutputInstance.getId();
dto.decisionInstanceId = historicDecisionOutputInstance.getDecisionInstanceId();
dto.clauseId = historicDecisionOutputInstance.getClauseId();
dto.clauseName = historicDecisionOutputInstance.getClauseName();
dto.ruleId = historicDecisionOutputInstance.getRuleId();
dto.ruleOrder = historicDecisionOutputInstance.getRuleOrder();
dto.variableName = historicDecisionOutputInstance.getVariableName(); | dto.createTime = historicDecisionOutputInstance.getCreateTime();
dto.removalTime = historicDecisionOutputInstance.getRemovalTime();
dto.rootProcessInstanceId = historicDecisionOutputInstance.getRootProcessInstanceId();
if(historicDecisionOutputInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, historicDecisionOutputInstance.getTypedValue());
}
else {
dto.errorMessage = historicDecisionOutputInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(historicDecisionOutputInstance.getTypeName());
}
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionOutputInstanceDto.java | 1 |
请完成以下Java代码 | public class UOMPrecision
{
@JsonCreator
public static UOMPrecision ofInt(final int precision)
{
if (precision >= 0 && precision < cachedValues.length)
{
return cachedValues[precision];
}
else
{
return new UOMPrecision(precision);
}
}
public static final UOMPrecision ZERO = new UOMPrecision(0);
public static final UOMPrecision TWO = new UOMPrecision(2);
public static final UOMPrecision TWELVE = new UOMPrecision(12);
private static final UOMPrecision[] cachedValues = new UOMPrecision[] {
ZERO,
new UOMPrecision(1),
TWO,
new UOMPrecision(3),
new UOMPrecision(4),
new UOMPrecision(5),
new UOMPrecision(6),
new UOMPrecision(7),
new UOMPrecision(8),
new UOMPrecision(9),
new UOMPrecision(10),
new UOMPrecision(11),
TWELVE,
};
private final int precision;
private UOMPrecision(final int precision)
{
Check.assumeGreaterOrEqualToZero(precision, "precision");
this.precision = precision;
}
@JsonValue
public int toInt()
{
return precision;
}
/**
* @return always RoundingMode#UP. Example: we convert 300GR to piece; one piece is one kilo; we need one piece and not 0 piece as the result, so we need to round UP.
*/
public RoundingMode getRoundingMode()
{
return RoundingMode.UP;
}
public BigDecimal roundIfNeeded(@NonNull final BigDecimal qty)
{
if (qty.scale() > precision)
{
return qty.setScale(precision, getRoundingMode());
}
else
{ | return qty;
}
}
public BigDecimal round(@NonNull final BigDecimal qty)
{
return qty.setScale(precision, getRoundingMode());
}
public BigDecimal adjustToPrecisionWithoutRoundingIfPossible(@NonNull final BigDecimal qty)
{
// NOTE: it seems that ZERO is a special case of BigDecimal, so we are computing it right away
if (qty == null || qty.signum() == 0)
{
return BigDecimal.ZERO.setScale(precision);
}
final BigDecimal qtyNoZero = qty.stripTrailingZeros();
final int qtyScale = qtyNoZero.scale();
if (qtyScale >= precision)
{
// Qty's actual scale is bigger than UOM precision, don't touch it
return qtyNoZero;
}
else
{
// Qty's actual scale is less than UOM precision. Try to convert it to UOM precision
// NOTE: we are using without scale because it shall be scaled without any problem
return qtyNoZero.setScale(precision, RoundingMode.HALF_UP);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMPrecision.java | 1 |
请完成以下Java代码 | public JAXBElement<AddEmployee> createAddEmployee(AddEmployee value) {
return new JAXBElement<AddEmployee>(_AddEmployee_QNAME, AddEmployee.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetAllEmployees }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://bottomup.server.jaxws.baeldung.com/", name = "getAllEmployees")
public JAXBElement<GetAllEmployees> createGetAllEmployees(GetAllEmployees value) {
return new JAXBElement<GetAllEmployees>(_GetAllEmployees_QNAME, GetAllEmployees.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link CountEmployeesResponse }{@code >}}
* | */
@XmlElementDecl(namespace = "http://bottomup.server.jaxws.baeldung.com/", name = "countEmployeesResponse")
public JAXBElement<CountEmployeesResponse> createCountEmployeesResponse(CountEmployeesResponse value) {
return new JAXBElement<CountEmployeesResponse>(_CountEmployeesResponse_QNAME, CountEmployeesResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetEmployee }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://bottomup.server.jaxws.baeldung.com/", name = "getEmployee")
public JAXBElement<GetEmployee> createGetEmployee(GetEmployee value) {
return new JAXBElement<GetEmployee>(_GetEmployee_QNAME, GetEmployee.class, null, value);
}
} | repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\ObjectFactory.java | 1 |
请完成以下Java代码 | public Set keys() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
return new HashSet(ehcache.getKeys());
}
throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");
}
@SuppressWarnings("unchecked")
@Override
public Collection values() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
List keys = ehcache.getKeys();
if (!CollectionUtils.isEmpty(keys)) {
List values = new ArrayList(keys.size()); | for (Object key : keys) {
Object value = get(key);
if (value != null) {
values.add(value);
}
}
return Collections.unmodifiableList(values);
} else {
return Collections.emptyList();
}
}
throw new UnsupportedOperationException("invoke spring cache abstract values method not supported");
}
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\spring\SpringCacheManagerWrapper.java | 1 |
请完成以下Java代码 | 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 setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference); | }
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Archive.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void handleEvent(final AbstractStockEstimateEvent event)
{
final Candidate existingStockEstimateCandidate = stockEstimateEventService.retrieveExistingStockEstimateCandidateOrNull(event);
if (existingStockEstimateCandidate != null)
{
throw new AdempiereException("No candidate should exist for event, but an actual candidate was returned")
.appendParametersToMessage()
.setParameter("StockEstimateCreatedEvent", event);
}
final Candidate previousStockOrNull = stockEstimateEventService.retrievePreviousStockCandidateOrNull(event);
final BigDecimal currentATP = previousStockOrNull != null ? previousStockOrNull.getQuantity() : BigDecimal.ZERO;
final BigDecimal deltaATP = currentATP.subtract(event.getQuantityDelta());
final StockChangeDetail stockChangeDetail = StockChangeDetail.builder()
.eventDate(event.getEventDate())
.freshQuantityOnHandRepoId(event.getFreshQtyOnHandId())
.freshQuantityOnHandLineRepoId(event.getFreshQtyOnHandLineId())
.isReverted(false)
.build();
final Candidate.CandidateBuilder supplyCandidateBuilder = Candidate.builder()
.clientAndOrgId(event.getClientAndOrgId())
.materialDescriptor(event.getMaterialDescriptor()) | .businessCase(CandidateBusinessCase.STOCK_CHANGE)
.businessCaseDetail(stockChangeDetail);
if (deltaATP.signum() > 0)
{
supplyCandidateBuilder
.type(CandidateType.INVENTORY_DOWN)
.quantity(deltaATP);
}
else
{
supplyCandidateBuilder
.type(CandidateType.INVENTORY_UP)
.quantity(deltaATP.negate());
}
candidateChangeHandler.onCandidateNewOrChange(supplyCandidateBuilder.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\stockchange\StockEstimateCreatedHandler.java | 2 |
请完成以下Java代码 | private void registerMethodSecurityHints(RuntimeHints hints) {
hints.reflection()
.registerType(
TypeReference
.of("org.springframework.security.access.expression.method.MethodSecurityExpressionRoot"),
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
hints.reflection()
.registerType(AbstractAuthenticationToken.class,
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
}
private void registerExpressionEvaluationHints(RuntimeHints hints) {
hints.reflection()
.registerTypes(
List.of(TypeReference.of(SecurityExpressionOperations.class),
TypeReference.of(SecurityExpressionRoot.class)),
(builder) -> builder.withMembers(MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_METHODS));
}
private void registerExceptionEventsHints(RuntimeHints hints) {
hints.reflection()
.registerTypes(getDefaultAuthenticationExceptionEventPublisherTypes(),
(builder) -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
}
private List<TypeReference> getDefaultAuthenticationExceptionEventPublisherTypes() {
return Stream
.of(AuthenticationFailureBadCredentialsEvent.class, AuthenticationFailureCredentialsExpiredEvent.class,
AuthenticationFailureDisabledEvent.class, AuthenticationFailureExpiredEvent.class, | AuthenticationFailureLockedEvent.class, AuthenticationFailureProviderNotFoundEvent.class,
AuthenticationFailureProxyUntrustedEvent.class, AuthenticationFailureServiceExceptionEvent.class,
AuthenticationServiceException.class, AccountExpiredException.class, BadCredentialsException.class,
CredentialsExpiredException.class, DisabledException.class, LockedException.class,
UsernameNotFoundException.class, ProviderNotFoundException.class)
.map(TypeReference::of)
.toList();
}
private void registerDefaultJdbcSchemaFileHint(RuntimeHints hints) {
hints.resources().registerPattern(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION);
}
private void registerSecurityContextHints(RuntimeHints hints) {
hints.reflection()
.registerType(SecurityContextImpl.class,
(builder) -> builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\aot\hint\CoreSecurityRuntimeHints.java | 1 |
请完成以下Spring Boot application配置 | spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?characterEncoding=UTF-8&serverTimezone=UTC
spring | .datasource.username=root
spring.datasource.password=posilka2020 | repos\Spring-Boot-Advanced-Projects-main\Springboot-Employee-Salary\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, Object> options = new HashMap<String, Object>();
// if we don't have keytab or principal only option is to rely on
// credentials cache.
if (!StringUtils.hasText(this.keyTabLocation) || !StringUtils.hasText(this.userPrincipal)) {
// cache
options.put("useTicketCache", "true");
}
else {
// keytab
options.put("useKeyTab", "true");
options.put("keyTab", this.keyTabLocation);
options.put("principal", this.userPrincipal);
options.put("storeKey", "true");
}
options.put("doNotPrompt", Boolean.toString(this.password == null));
options.put("isInitiator", "true");
if (this.loginOptions != null) {
options.putAll(this.loginOptions);
}
return new AppConfigurationEntry[] {
new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
}
}
private static class NullCredentials implements Credentials {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public char[] getPassword() {
return null;
}
}
private static final class CallbackHandlerImpl implements CallbackHandler { | private final String userPrincipal;
private final String password;
private CallbackHandlerImpl(String userPrincipal, String password) {
super();
this.userPrincipal = userPrincipal;
this.password = password;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
NameCallback nc = (NameCallback) callback;
nc.setName(this.userPrincipal);
}
else if (callback instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callback;
pc.setPassword(this.password.toCharArray());
}
else {
throw new UnsupportedCallbackException(callback, "Unknown Callback");
}
}
}
}
} | repos\spring-security-main\kerberos\kerberos-client\src\main\java\org\springframework\security\kerberos\client\KerberosRestTemplate.java | 1 |
请完成以下Java代码 | public void setC_HierarchyCommissionSettings(final de.metas.contracts.commission.model.I_C_HierarchyCommissionSettings C_HierarchyCommissionSettings)
{
set_ValueFromPO(COLUMNNAME_C_HierarchyCommissionSettings_ID, de.metas.contracts.commission.model.I_C_HierarchyCommissionSettings.class, C_HierarchyCommissionSettings);
}
@Override
public void setC_HierarchyCommissionSettings_ID (final int C_HierarchyCommissionSettings_ID)
{
if (C_HierarchyCommissionSettings_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_HierarchyCommissionSettings_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_HierarchyCommissionSettings_ID, C_HierarchyCommissionSettings_ID);
}
@Override
public int getC_HierarchyCommissionSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_HierarchyCommissionSettings_ID);
}
@Override
public org.compiere.model.I_C_BP_Group getCustomer_Group()
{
return get_ValueAsPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setCustomer_Group(final org.compiere.model.I_C_BP_Group Customer_Group)
{
set_ValueFromPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class, Customer_Group);
}
@Override
public void setCustomer_Group_ID (final int Customer_Group_ID)
{
if (Customer_Group_ID < 1)
set_Value (COLUMNNAME_Customer_Group_ID, null);
else
set_Value (COLUMNNAME_Customer_Group_ID, Customer_Group_ID);
}
@Override
public int getCustomer_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_Customer_Group_ID);
}
@Override
public void setIsExcludeBPGroup (final boolean IsExcludeBPGroup)
{
set_Value (COLUMNNAME_IsExcludeBPGroup, IsExcludeBPGroup);
}
@Override
public boolean isExcludeBPGroup() | {
return get_ValueAsBoolean(COLUMNNAME_IsExcludeBPGroup);
}
@Override
public void setIsExcludeProductCategory (final boolean IsExcludeProductCategory)
{
set_Value (COLUMNNAME_IsExcludeProductCategory, IsExcludeProductCategory);
}
@Override
public boolean isExcludeProductCategory()
{
return get_ValueAsBoolean(COLUMNNAME_IsExcludeProductCategory);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PPOrderRequestedEvent implements MaterialEvent
{
public static final String TYPE = "PPOrderRequestedEvent";
EventDescriptor eventDescriptor;
Instant dateOrdered;
PPOrder ppOrder;
@JsonCreator
@Builder
private PPOrderRequestedEvent(
@JsonProperty("eventDescriptor") @NonNull final EventDescriptor eventDescriptor,
@JsonProperty("dateOrdered") @NonNull final Instant dateOrdered,
@JsonProperty("ppOrder") @NonNull final PPOrder ppOrder)
{
this.eventDescriptor = eventDescriptor;
this.dateOrdered = dateOrdered;
this.ppOrder = ppOrder;
} | public void validate()
{
// we need the PPOrder's MaterialDispoGroupId to map the order that was created to its respective candidates
Check.errorIf(ppOrder.getPpOrderData().getMaterialDispoGroupId() == null, "The ppOrder of a PPOrderRequestedEvent needs to have a group id");
}
@Override
public TableRecordReference getSourceTableReference()
{
return TableRecordReference.ofNullable(I_PP_Order.Table_Name, ppOrder.getPpOrderId());
}
@Override
public String getEventName() {return TYPE;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRequestedEvent.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RedisConfig extends CachingConfigurerSupport{
private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
@Autowired
private Environment env;
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(env.getProperty("redis.hostname"));
redisConnectionFactory.setPort(Integer.parseInt(env.getProperty("redis.port")));
return redisConnectionFactory;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(cf);
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(600);
return cacheManager;
}
public CacheErrorHandler errorHandler() { | return new CacheErrorHandler(){
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
logger.warn("handleCacheGetError in redis: {}", exception.getMessage());
}
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
logger.warn("handleCachePutError in redis: {}", exception.getMessage());
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
logger.warn("handleCacheEvictError in redis: {}", exception.getMessage());
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
logger.warn("handleCacheClearError in redis: {}", exception.getMessage());
}};
}
} | repos\springBoot-master\springboot-Cache\src\main\java\com\us\example\config\RedisConfig.java | 2 |
请完成以下Java代码 | public int getC_Letter_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Letter_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zu druckende Mitgliederausweise.
@param IsMembershipBadgeToPrint Zu druckende Mitgliederausweise */
@Override
public void setIsMembershipBadgeToPrint (boolean IsMembershipBadgeToPrint)
{
set_Value (COLUMNNAME_IsMembershipBadgeToPrint, Boolean.valueOf(IsMembershipBadgeToPrint));
}
/** Get Zu druckende Mitgliederausweise.
@return Zu druckende Mitgliederausweise */
@Override
public boolean isMembershipBadgeToPrint ()
{
Object oo = get_Value(COLUMNNAME_IsMembershipBadgeToPrint);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Body.
@param LetterBody Body */
@Override
public void setLetterBody (java.lang.String LetterBody)
{
set_Value (COLUMNNAME_LetterBody, LetterBody);
}
/** Get Body.
@return Body */
@Override
public java.lang.String getLetterBody ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterBody);
}
/** Set Body (parsed).
@param LetterBodyParsed Body (parsed) */
@Override
public void setLetterBodyParsed (java.lang.String LetterBodyParsed)
{
set_Value (COLUMNNAME_LetterBodyParsed, LetterBodyParsed);
}
/** Get Body (parsed). | @return Body (parsed) */
@Override
public java.lang.String getLetterBodyParsed ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterBodyParsed);
}
/** Set Subject.
@param LetterSubject Subject */
@Override
public void setLetterSubject (java.lang.String LetterSubject)
{
set_Value (COLUMNNAME_LetterSubject, LetterSubject);
}
/** Get Subject.
@return Subject */
@Override
public java.lang.String getLetterSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_LetterSubject);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_C_Letter.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("hashed", hashed)
.add("value", hashed ? value : "*******")
.toString();
}
public boolean isEmpty()
{
return isPlain() && Check.isEmpty(value);
}
public static boolean isEmpty(@Nullable final HashableString hashableString)
{
return hashableString == null || hashableString.isEmpty();
}
public boolean isPlain()
{
return !isHashed();
}
public HashableString hash()
{
final String salt = UIDStringUtil.createRandomUUID();
return hashWithSalt(salt);
}
public HashableString hashWithSalt(@Nullable final String salt)
{
if (hashed)
{
return this;
}
HashableString hashedObject = _hashedObject;
if (hashedObject == null)
{
final String valueHashed = hashValue(value, salt);
hashedObject = _hashedObject = new HashableString(valueHashed, true, salt);
}
return hashedObject;
}
private static String hashValue(final String valuePlain, @Nullable final String salt)
{
// IMPORTANT: please keep it in sync with "hash_column_value" database function
final String valuePlainNorm = valuePlain != null ? valuePlain : "";
final String valueWithSalt;
if (salt != null && !salt.isEmpty())
{
valueWithSalt = valuePlainNorm + salt;
}
else
{
valueWithSalt = valuePlainNorm;
}
final HashCode valueHashed = Hashing.sha512().hashString(valueWithSalt, StandardCharsets.UTF_8);
final String valueHashedAndEncoded = valueHashed.toString(); // hex encoding
return PREFIX_SHA512 + valueHashedAndEncoded + SEPARATOR + salt;
}
public boolean isMatching(@Nullable final HashableString other)
{
if (this == other)
{
return true; | }
if (other == null)
{
return false;
}
if (isPlain())
{
if (other.isPlain())
{
return valueEquals(other.value);
}
else
{
return hashWithSalt(other.salt).valueEquals(other.value);
}
}
else
{
if (other.isPlain())
{
return other.hashWithSalt(salt).valueEquals(value);
}
else
{
return valueEquals(other.value);
}
}
}
private boolean valueEquals(final String otherValue)
{
return Objects.equals(this.value, otherValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\hash\HashableString.java | 1 |
请完成以下Java代码 | private void updateFlatrateTerms()
{
updateFlatrateTermsColumn(I_C_Flatrate_Term.COLUMNNAME_Bill_Location_ID, oldBPLocationId, newBPLocationId);
updateFlatrateTermsColumn(I_C_Flatrate_Term.COLUMNNAME_DropShip_Location_ID, oldBPLocationId, newBPLocationId);
}
private void updateFlatrateTermsColumn(final String columnName, final RepoIdAware oldLocationId, final RepoIdAware newLocationId)
{
final Collection<String> disallowedFlatrateStatuses = ImmutableSet.of(X_C_Flatrate_Term.CONTRACTSTATUS_Voided, X_C_Flatrate_Term.CONTRACTSTATUS_Quit);
final ICompositeQueryUpdater<I_C_Flatrate_Term> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_Flatrate_Term.class)
.addSetColumnValue(columnName, newLocationId);
queryBL
.createQueryBuilder(I_C_Flatrate_Term.class)
.addEqualsFilter(columnName, oldLocationId)
.addNotInArrayFilter(I_C_Flatrate_Term.COLUMN_ContractStatus,disallowedFlatrateStatuses)
.addCompareFilter(I_C_Flatrate_Term.COLUMN_EndDate, CompareQueryFilter.Operator.GREATER_OR_EQUAL, Env.getDate())
// .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Processed, false) in this case contracts are already processed
.create()
.update(queryUpdater); | }
private void deactivateOldBPLocation()
{
newLocation.setIsBillToDefault(newLocation.isBillToDefault() || oldLocation.isBillToDefault());
newLocation.setIsShipToDefault(newLocation.isShipToDefault() || oldLocation.isShipToDefault());
newLocation.setIsBillTo(newLocation.isBillTo() || oldLocation.isBillTo());
newLocation.setIsShipTo(newLocation.isShipTo() || oldLocation.isShipTo());
oldLocation.setIsBillToDefault(false);
oldLocation.setIsShipToDefault(false);
oldLocation.setIsActive(false);
bpartnerDAO.save(oldLocation);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\command\BPartnerLocationReplaceCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getC_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Tax_ID);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPrice (final BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
@Override
public BigDecimal getPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProductName (final java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override | public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setScannedBarcode (final @Nullable java.lang.String ScannedBarcode)
{
set_Value (COLUMNNAME_ScannedBarcode, ScannedBarcode);
}
@Override
public java.lang.String getScannedBarcode()
{
return get_ValueAsString(COLUMNNAME_ScannedBarcode);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_OrderLine.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SendToTCPRouteBuilder extends RouteBuilder
{
public static final String SEND_TO_TCP_ROUTE_ID = "LeichUndMehl-sendToTCP";
@Override
public void configure() throws Exception
{
//@formatter:off
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
from(direct(SEND_TO_TCP_ROUTE_ID))
.routeId(SEND_TO_TCP_ROUTE_ID)
.log("Route invoked!")
.log(LoggingLevel.DEBUG, "exchange body: ${body}")
.doTry()
.process(this::sendToTcpSocket)
.endDoTry()
.doCatch(RuntimeException.class)
.to(direct(MF_ERROR_ROUTE_ID));
//@formatter:on
}
private void sendToTcpSocket(@NonNull final Exchange exchange) throws Exception
{
final DispatchMessageRequest request = exchange.getIn().getBody(DispatchMessageRequest.class);
final TCPConnectionDetails tcpConnection = request.getDestinationDetails().getConnectionDetailsNotNull();
try (final Socket socket = new Socket(tcpConnection.getTcpHost(), tcpConnection.getTcpPort());
final DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) | {
sendContent(request.getPayload(), dataOutputStream);
}
catch (final IOException e)
{
throw new RuntimeException("Error on sending data to scale", e);
}
}
private static void sendContent(
@NonNull final String payload,
@NonNull final DataOutputStream dataOutputStream) throws Exception
{
try (final InputStream inputStream = new ByteArrayInputStream(payload.getBytes(StandardCharsets.ISO_8859_1)))
{
// break payload into chunks
final byte[] buffer = new byte[4 * 1024];
int bytes;
while ((bytes = inputStream.read(buffer)) != -1)
{
dataOutputStream.write(buffer, 0, bytes);
dataOutputStream.flush();
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\networking\tcp\SendToTCPRouteBuilder.java | 2 |
请完成以下Java代码 | public MapReduceAggregator<GroupType, ItemType> addAll(final Iterator<ItemType> items)
{
Check.assumeNotNull(items, "items not null");
while (items.hasNext())
{
final ItemType item = items.next();
add(item);
}
return this;
}
/**
* Invokes this instance's {@link IAggregationKeyBuilder}'s (see {@link #setItemAggregationKeyBuilder(IAggregationKeyBuilder)}) <code>buildKey</code> method.
*
* @return hash/aggregation key for given <code>item</code>
*/
private Object createItemHashKey(@NonNull final ItemType item)
{
final Function<ItemType, Object> itemAggregationKeyBuilder = getItemAggregationKeyBuilder();
final Object itemHashKey = itemAggregationKeyBuilder.apply(item);
return itemHashKey;
}
/**
* Creates a new group based on given item and adds it to groups buffer.
*
* If the groups buffer capacity is reached the last used group will be removed from buffer (this is done indirectly by {@link LRUMap}).
*
* @param item item to be used for creating the new group
*/
private GroupType createAndAddGroupToBuffer(@NonNull final Object itemHashKey, @NonNull final ItemType item)
{
// We put a null value to map (before actually creating the group),
// to make sure the previous groups are closed before the new group is actually created
_itemHashKey2group.put(itemHashKey, null);
final GroupType group = createGroup(itemHashKey, item);
_itemHashKey2group.put(itemHashKey, group);
_countGroups++;
return group;
}
private void closeGroupAndCollect(final GroupType group)
{
closeGroup(group);
if (closedGroupsCollector != null)
{
closedGroupsCollector.add(group);
}
}
/**
* Close all groups from buffer. As a result, after this call the groups buffer will be empty.
*/
public final void closeAllGroups()
{
final GroupType exceptGroup = null; // no exception
closeAllGroupsExcept(exceptGroup);
}
/** | * Close all groups, but not the last used one. Last used one is considered that group where we added last item.
*/
public final void closeAllGroupExceptLastUsed()
{
closeAllGroupsExcept(_lastGroupUsed);
}
/**
* Close all groups.
*
* @param exceptGroup optional group to except from closing
*/
private void closeAllGroupsExcept(@Nullable final GroupType exceptGroup)
{
final Iterator<GroupType> groups = _itemHashKey2group.values().iterator();
while (groups.hasNext())
{
final GroupType group = groups.next();
if (group == null)
{
continue;
}
// Skip the excepted group
if (group == exceptGroup)
{
continue;
}
closeGroupAndCollect(group);
groups.remove();
}
}
/**
* @return how many groups were created
*/
public final int getGroupsCount()
{
return _countGroups;
}
/**
* @return how many items were added
*/
public final int getItemsCount()
{
return _countItems;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MapReduceAggregator.java | 1 |
请完成以下Java代码 | private Optional<AdMessageKey> isProductUsed(@NonNull final ProductId productId)
{
if (productDAO.isProductUsed(productId))
{
return Optional.of(ProductConstants.MSG_PRODUCT_ALREADY_USED);
}
return Optional.empty();
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_M_Product.COLUMNNAME_Weight })
public void updateOrderWeight(@NonNull final I_M_Product product)
{
final List<OrderId> orderIdsToBeUpdated = orderBL.getUnprocessedIdsBy(ProductId.ofRepoId(product.getM_Product_ID()));
Iterators.partition(orderIdsToBeUpdated.iterator(), 100)
.forEachRemaining(this::setWeightFromLines);
}
private void setWeightFromLines(@NonNull final List<OrderId> orderIds)
{
orderBL.getByIds(orderIds)
.forEach(order -> {
orderBL.setWeightFromLines(order);
saveRecord(order);
}); | }
private void normalizeProductCodeFields(@NonNull I_M_Product record)
{
if (InterfaceWrapperHelper.isValueChanged(record, I_M_Product.COLUMNNAME_GTIN))
{
final GTIN gtin = GTIN.ofNullableString(record.getGTIN());
productBL.setProductCodeFieldsFromGTIN(record, gtin);
}
// NOTE: syncing UPC to GTIN is not quite correct, but we have a lot of BPs which are relying on this logic
else if (InterfaceWrapperHelper.isValueChanged(record, I_M_Product.COLUMNNAME_UPC))
{
final GTIN gtin = GTIN.ofNullableString(record.getUPC());
productBL.setProductCodeFieldsFromGTIN(record, gtin);
}
else if (InterfaceWrapperHelper.isValueChanged(record, I_M_Product.COLUMNNAME_EAN13_ProductCode))
{
final EAN13ProductCode ean13ProductCode = EAN13ProductCode.ofNullableString(record.getEAN13_ProductCode());
productBL.setProductCodeFieldsFromEAN13ProductCode(record, ean13ProductCode);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\model\interceptor\M_Product.java | 1 |
请完成以下Java代码 | public int getSelectedId()
{
if (idColumnIndex < 0)
return -1;
int row = getSelectedRow();
if (row != -1)
{
Object data = getModel().getValueAt(row, 0);
if (data != null)
{
Integer id = ((IDColumn)data).getRecord_ID();
return id == null ? -1 : id.intValue();
}
}
return -1;
}
public void selectById(int id)
{
selectById(id, true);
}
public void selectById(int id, boolean fireEvent)
{
if (idColumnIndex < 0)
return;
boolean fireSelectionEventOld = fireSelectionEvent;
try
{
fireSelectionEvent = fireEvent; | if (id < 0)
{
this.getSelectionModel().removeSelectionInterval(0, this.getRowCount());
return;
}
for (int i = 0; i < this.getRowCount(); i++)
{
IDColumn key = (IDColumn)this.getModel().getValueAt(i, idColumnIndex);
if (key != null && id > 0 && key.getRecord_ID() == id)
{
this.getSelectionModel().setSelectionInterval(i, i);
break;
}
}
}
finally
{
fireSelectionEvent = fireSelectionEventOld;
}
}
private boolean fireSelectionEvent = true;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\ui\swing\MiniTable2.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConnectorDefinitionService {
private String connectorRoot;
private final ObjectMapper objectMapper;
private ResourcePatternResolver resourceLoader;
public ConnectorDefinitionService(
String connectorRoot,
ObjectMapper objectMapper,
ResourcePatternResolver resourceLoader
) {
this.connectorRoot = connectorRoot;
this.objectMapper = objectMapper;
this.resourceLoader = resourceLoader;
}
private Optional<Resource[]> retrieveResources() throws IOException {
Optional<Resource[]> resources = Optional.empty();
Resource connectorRootPath = resourceLoader.getResource(connectorRoot);
if (connectorRootPath.exists()) {
return Optional.ofNullable(resourceLoader.getResources(connectorRoot + "**.json"));
}
return resources;
}
private ConnectorDefinition read(InputStream inputStream) throws IOException {
return objectMapper.readValue(inputStream, ConnectorDefinition.class);
}
public List<ConnectorDefinition> get() throws IOException {
List<ConnectorDefinition> connectorDefinitions = new ArrayList<>();
Optional<Resource[]> resourcesOptional = retrieveResources();
if (resourcesOptional.isPresent()) {
for (Resource resource : resourcesOptional.get()) {
connectorDefinitions.add(read(resource.getInputStream())); | }
validate(connectorDefinitions);
}
return connectorDefinitions;
}
protected void validate(List<ConnectorDefinition> connectorDefinitions) {
if (!connectorDefinitions.isEmpty()) {
Set<String> processedNames = new HashSet<>();
for (ConnectorDefinition connectorDefinition : connectorDefinitions) {
String name = connectorDefinition.getName();
if (name == null || name.isEmpty()) {
throw new IllegalStateException("connectorDefinition name cannot be null or empty");
}
if (name.contains(".")) {
throw new IllegalStateException("connectorDefinition name cannot have '.' character");
}
if (!processedNames.add(name)) {
throw new IllegalStateException(
"More than one connectorDefinition with name '" + name + "' was found. Names must be unique."
);
}
}
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-connector\src\main\java\org\activiti\core\common\spring\connector\ConnectorDefinitionService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class ReactiveMethodSecurityConfiguration implements ImportAware {
private int advisorOrder;
private GrantedAuthorityDefaults grantedAuthorityDefaults;
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static MethodSecurityMetadataSourceAdvisor methodSecurityInterceptor(AbstractMethodSecurityMetadataSource source,
ReactiveMethodSecurityConfiguration configuration) {
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"securityMethodInterceptor", source, "methodMetadataSource");
advisor.setOrder(configuration.advisorOrder);
return advisor;
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static DelegatingMethodSecurityMetadataSource methodMetadataSource(
MethodSecurityExpressionHandler methodSecurityExpressionHandler) {
ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory(
methodSecurityExpressionHandler);
PrePostAnnotationSecurityMetadataSource prePostSource = new PrePostAnnotationSecurityMetadataSource(
attributeFactory);
return new DelegatingMethodSecurityMetadataSource(Arrays.asList(prePostSource));
}
@Bean
static PrePostAdviceReactiveMethodInterceptor securityMethodInterceptor(AbstractMethodSecurityMetadataSource source,
MethodSecurityExpressionHandler handler) {
ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(handler); | ExpressionBasedPreInvocationAdvice preAdvice = new ExpressionBasedPreInvocationAdvice();
preAdvice.setExpressionHandler(handler);
return new PrePostAdviceReactiveMethodInterceptor(source, preAdvice, postAdvice);
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Fallback
static DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler(
ReactiveMethodSecurityConfiguration configuration) {
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
if (configuration.grantedAuthorityDefaults != null) {
handler.setDefaultRolePrefix(configuration.grantedAuthorityDefaults.getRolePrefix());
}
return handler;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName())
.get("order");
}
@Autowired(required = false)
void setGrantedAuthorityDefaults(GrantedAuthorityDefaults grantedAuthorityDefaults) {
this.grantedAuthorityDefaults = grantedAuthorityDefaults;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\ReactiveMethodSecurityConfiguration.java | 2 |
请完成以下Java代码 | public class ReplRequestHandlerCtx implements IReplRequestHandlerCtx
{
private Properties envCtxToUse;
private I_EXP_Format importFormat;
private I_IMP_RequestHandler requestHandlerRecord;
@Override
public Properties getEnvCtxToUse()
{
return envCtxToUse;
}
@Override
public I_EXP_Format getImportFormat()
{
return importFormat;
}
@Override
public I_IMP_RequestHandler getRequestHandlerRecord()
{
return requestHandlerRecord;
} | public void setEnvCtxToUse(Properties envCtxToUse)
{
this.envCtxToUse = envCtxToUse;
}
public void setImportFormat(I_EXP_Format importFormat)
{
this.importFormat = importFormat;
}
public void setRequestHandlerRecord(I_IMP_RequestHandler requestHandlerRecord)
{
this.requestHandlerRecord = requestHandlerRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\rpl\requesthandler\api\impl\ReplRequestHandlerCtx.java | 1 |
请完成以下Java代码 | public IInvoiceCandInvalidUpdater setLimit(final int limit)
{
assertNotExecuted();
icTagger.setLimit(limit);
return this;
}
@Override
public IInvoiceCandInvalidUpdater setRecomputeTagToUse(final InvoiceCandRecomputeTag tag)
{
assertNotExecuted();
icTagger.setRecomputeTag(tag);
return this;
}
@Override
public IInvoiceCandInvalidUpdater setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds)
{
assertNotExecuted();
icTagger.setOnlyInvoiceCandidateIds(onlyInvoiceCandidateIds);
return this;
}
private int getItemsPerBatch()
{
return sysConfigBL.getIntValue(SYSCONFIG_ItemsPerBatch, DEFAULT_ItemsPerBatch);
}
/**
* IC update result.
*
* @author metas-dev <dev@metasfresh.com>
*/
private static final class ICUpdateResult
{
private int countOk = 0;
private int countErrors = 0;
public void addInvoiceCandidate()
{
countOk++;
}
public void incrementErrorsCount()
{
countErrors++;
}
@Override
public String toString()
{ | return getSummary();
}
public String getSummary()
{
return "Updated " + countOk + " invoice candidates, " + countErrors + " errors";
}
}
/**
* IC update exception handler
*/
private final class ICTrxItemExceptionHandler extends FailTrxItemExceptionHandler
{
private final ICUpdateResult result;
public ICTrxItemExceptionHandler(@NonNull final ICUpdateResult result)
{
this.result = result;
}
/**
* Resets the given IC to its old values, and sets an error flag in it.
*/
@Override
public void onItemError(final Throwable e, final Object item)
{
result.incrementErrorsCount();
final I_C_Invoice_Candidate ic = InterfaceWrapperHelper.create(item, I_C_Invoice_Candidate.class);
// gh #428: don't discard changes that were already made, because they might include a change of QtyInvoice.
// in that case, a formerly Processed IC might need to be flagged as unprocessed.
// if we discard all changes in this case, then we will have IsError='Y' and also an error message in the IC,
// but the user will probably ignore it, because the IC is still flagged as processed.
invoiceCandBL.setError(ic, e);
// invoiceCandBL.discardChangesAndSetError(ic, e);
invoiceCandDAO.save(ic);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandInvalidUpdater.java | 1 |
请完成以下Java代码 | class EntityKeyValue {
@Getter
private DataType dataType;
private Long lngValue;
private Double dblValue;
private Boolean boolValue;
private String strValue;
public Long getLngValue() {
return dataType == DataType.LONG ? lngValue : null;
}
public void setLngValue(Long lngValue) {
this.dataType = DataType.LONG;
this.lngValue = lngValue;
}
public Double getDblValue() {
return dataType == DataType.DOUBLE ? dblValue : null;
}
public void setDblValue(Double dblValue) {
this.dataType = DataType.DOUBLE;
this.dblValue = dblValue;
}
public Boolean getBoolValue() {
return dataType == DataType.BOOLEAN ? boolValue : null;
}
public void setBoolValue(Boolean boolValue) {
this.dataType = DataType.BOOLEAN;
this.boolValue = boolValue;
}
public String getStrValue() {
return dataType == DataType.STRING ? strValue : null;
}
public void setStrValue(String strValue) {
this.dataType = DataType.STRING;
this.strValue = strValue;
}
public void setJsonValue(String jsonValue) {
this.dataType = DataType.JSON; | this.strValue = jsonValue;
}
public String getJsonValue() {
return dataType == DataType.JSON ? strValue : null;
}
boolean isSet() {
return dataType != null;
}
static EntityKeyValue fromString(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setStrValue(s);
return result;
}
static EntityKeyValue fromBool(boolean b) {
EntityKeyValue result = new EntityKeyValue();
result.setBoolValue(b);
return result;
}
static EntityKeyValue fromLong(long l) {
EntityKeyValue result = new EntityKeyValue();
result.setLngValue(l);
return result;
}
static EntityKeyValue fromDouble(double d) {
EntityKeyValue result = new EntityKeyValue();
result.setDblValue(d);
return result;
}
static EntityKeyValue fromJson(String s) {
EntityKeyValue result = new EntityKeyValue();
result.setJsonValue(s);
return result;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\EntityKeyValue.java | 1 |
请完成以下Java代码 | public class Main {
public static void main(String[] args) throws FileNotFoundException {
TryCatch tryCatch = new TryCatch();
try {
tryCatch.execute();
} catch (ConnectionException | SocketException ex) {
System.out.println("IOException");
} catch (Exception ex) {
System.out.println("General exception");
}
checkedExceptionWithTryCatch();
checkedExceptionWithThrows();
divideByZero();
}
private static void checkedExceptionWithThrows() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
} | private static void checkedExceptionWithTryCatch() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void divideByZero() {
int numerator = 1;
int denominator = 0;
int result = numerator / denominator;
}
} | repos\tutorials-master\core-java-modules\core-java-exceptions-5\src\main\java\com\baeldung\exceptions\throwvsthrows\Main.java | 1 |
请完成以下Java代码 | public int hashCode(PhoneNumber x) {
return x.hashCode();
}
@Override
public PhoneNumber deepCopy(PhoneNumber value) {
if (Objects.isNull(value)) {
return null;
}
return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber());
}
@Override
public boolean isMutable() {
return false;
} | @Override
public Serializable disassemble(PhoneNumber value) {
return (Serializable) value;
}
@Override
public PhoneNumber assemble(Serializable cached, Object owner) {
return (PhoneNumber) cached;
}
@Override
public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) {
return detached;
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\PhoneNumberType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RabbitConfig {
/**
* Direct Exchange 示例的配置类
*/
public static class DirectExchangeDemoConfiguration {
// 创建 Queue
@Bean
public Queue demo10Queue0() {
return new Queue(Demo10Message.QUEUE_0);
}
@Bean
public Queue demo10Queue1() {
return new Queue(Demo10Message.QUEUE_1);
}
@Bean
public Queue demo10Queue2() {
return new Queue(Demo10Message.QUEUE_2);
}
@Bean
public Queue demo10Queue3() {
return new Queue(Demo10Message.QUEUE_3);
}
// 创建 Direct Exchange
@Bean
public DirectExchange demo10Exchange() {
return new DirectExchange(Demo10Message.EXCHANGE,
true, // durable: 是否持久化
false); // exclusive: 是否排它
}
// 创建 Binding
@Bean
public Binding demo10Binding0() {
return BindingBuilder.bind(demo10Queue0()).to(demo10Exchange()).with("0"); | }
@Bean
public Binding demo10Binding1() {
return BindingBuilder.bind(demo10Queue1()).to(demo10Exchange()).with("1");
}
@Bean
public Binding demo10Binding2() {
return BindingBuilder.bind(demo10Queue2()).to(demo10Exchange()).with("2");
}
@Bean
public Binding demo10Binding3() {
return BindingBuilder.bind(demo10Queue3()).to(demo10Exchange()).with("3");
}
}
} | repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-orderly\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java | 2 |
请完成以下Java代码 | public void setRestApiBaseURL (java.lang.String RestApiBaseURL)
{
set_Value (COLUMNNAME_RestApiBaseURL, RestApiBaseURL);
}
/** Get REST API URL.
@return REST API URL */
@Override
public java.lang.String getRestApiBaseURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_RestApiBaseURL);
}
/** Set Creditpass-Prüfung wiederholen .
@param RetryAfterDays Creditpass-Prüfung wiederholen */
@Override
public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays)
{
set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays);
}
/** Get Creditpass-Prüfung wiederholen .
@return Creditpass-Prüfung wiederholen */
@Override
public java.math.BigDecimal getRetryAfterDays ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** 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();
}
/** 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));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java | 1 |
请完成以下Java代码 | public Mono<ReactiveAuthenticationManager> resolve(ServerWebExchange exchange) {
return Flux.fromIterable(this.authenticationManagers)
.filterWhen((entry) -> isMatch(exchange, entry))
.next()
.map(ServerWebExchangeMatcherEntry::getEntry)
.defaultIfEmpty(this.defaultAuthenticationManager);
}
/**
* Set the default {@link ReactiveAuthenticationManager} to use when a request does
* not match
* @param defaultAuthenticationManager the default
* {@link ReactiveAuthenticationManager} to use
*/
public void setDefaultAuthenticationManager(ReactiveAuthenticationManager defaultAuthenticationManager) {
Assert.notNull(defaultAuthenticationManager, "defaultAuthenticationManager cannot be null");
this.defaultAuthenticationManager = defaultAuthenticationManager;
}
/**
* Creates a builder for {@link RequestMatcherDelegatingAuthorizationManager}.
* @return the new {@link RequestMatcherDelegatingAuthorizationManager.Builder}
* instance
*/
public static Builder builder() {
return new Builder();
}
private Mono<Boolean> isMatch(ServerWebExchange exchange,
ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager> entry) {
ServerWebExchangeMatcher matcher = entry.getMatcher();
return matcher.matches(exchange).map(ServerWebExchangeMatcher.MatchResult::isMatch);
}
/**
* A builder for
* {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver}.
*/
public static final class Builder {
private final List<ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager>> entries = new ArrayList<>();
private Builder() {
}
/**
* Maps a {@link ServerWebExchangeMatcher} to an
* {@link ReactiveAuthenticationManager}.
* @param matcher the {@link ServerWebExchangeMatcher} to use
* @param manager the {@link ReactiveAuthenticationManager} to use | * @return the
* {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.Builder}
* for further customizations
*/
public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.Builder add(
ServerWebExchangeMatcher matcher, ReactiveAuthenticationManager manager) {
Assert.notNull(matcher, "matcher cannot be null");
Assert.notNull(manager, "manager cannot be null");
this.entries.add(new ServerWebExchangeMatcherEntry<>(matcher, manager));
return this;
}
/**
* Creates a
* {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver}
* instance.
* @return the
* {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver}
* instance
*/
public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver build() {
return new ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver(this.entries);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.java | 1 |
请完成以下Java代码 | public void setIsInvoiced (boolean IsInvoiced)
{
set_Value (COLUMNNAME_IsInvoiced, Boolean.valueOf(IsInvoiced));
}
/** Get Invoiced.
@return Is this invoiced?
*/
public boolean isInvoiced ()
{
Object oo = get_Value(COLUMNNAME_IsInvoiced);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_M_Product_Category getM_Product_Category() throws RuntimeException
{
return (I_M_Product_Category)MTable.get(getCtx(), I_M_Product_Category.Table_Name)
.getPO(getM_Product_Category_ID(), get_TrxName()); }
/** Set Product Category.
@param M_Product_Category_ID
Category of a Product
*/
public void setM_Product_Category_ID (int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, Integer.valueOf(M_Product_Category_ID));
}
/** Get Product Category.
@return Category of a Product
*/
public int getM_Product_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Expense Type.
@param S_ExpenseType_ID | Expense report type
*/
public void setS_ExpenseType_ID (int S_ExpenseType_ID)
{
if (S_ExpenseType_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, Integer.valueOf(S_ExpenseType_ID));
}
/** Get Expense Type.
@return Expense report type
*/
public int getS_ExpenseType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ExpenseType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ExpenseType.java | 1 |
请完成以下Java代码 | public class Context {
protected static ThreadLocal<Stack<CommandContext>> commandContextThreadLocal = new ThreadLocal<>();
public static CommandContext getCommandContext() {
Stack<CommandContext> stack = getStack(commandContextThreadLocal);
if (stack.isEmpty()) {
return null;
}
return stack.peek();
}
public static void setCommandContext(CommandContext commandContext) {
getStack(commandContextThreadLocal).push(commandContext);
}
public static void removeCommandContext() {
getStack(commandContextThreadLocal).pop();
}
public static TransactionContext getTransactionContext() {
return TransactionContextHolder.getTransactionContext();
} | public static void setTransactionContext(TransactionContext transactionContext) {
TransactionContextHolder.setTransactionContext(transactionContext);
}
public static void removeTransactionContext() {
TransactionContextHolder.removeTransactionContext();
}
protected static <T> Stack<T> getStack(ThreadLocal<Stack<T>> threadLocal) {
Stack<T> stack = threadLocal.get();
if (stack == null) {
stack = new Stack<>();
threadLocal.set(stack);
}
return stack;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\context\Context.java | 1 |
请完成以下Spring Boot application配置 | spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/javastack
username: root
password: 12345678
quartz:
job-store-type: jdbc
jdbc:
initialize-schema: never # always
overwrite- | existing-jobs: true
properties:
org:
quartz:
threadPool:
threadCount: 5 | repos\spring-boot-best-practice-master\spring-boot-quartz\src\main\resources\application.yml | 2 |
请完成以下Java代码 | private String generateSequenceResult()
{
synchronized (MockedEndpoint.class)
{
weightSequenceIdx++;
if (weightSequenceIdx >= weightSequence.length)
{
weightSequenceIdx = 0;
}
final BigDecimal weighFromArray = weightSequence[weightSequenceIdx];
final BigDecimal weightToUse = weighFromArray.add(new BigDecimal(mockedEndpointInstanceNumber));
final String returnString = createWeightString(weightToUse); | return returnString;
}
}
public static String createWeightString(final BigDecimal weight)
{
final DecimalFormat weightFormat = new DecimalFormat("#########.000");
String weightStr = weightFormat.format(weight);
while (weightStr.length() < 11)
{
weightStr = " " + weightStr;
}
final String resultString = "S S " + weightStr + " kg";
return resultString;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\endpoint\MockedEndpoint.java | 1 |
请完成以下Java代码 | public void deleteByTenantId(TenantId tenantId) {
adminSettingsDao.removeByTenantId(tenantId.getId());
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
adminSettingsDao.removeById(tenantId, id.getId());
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(adminSettingsDao.findById(tenantId, entityId.getId()));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(adminSettingsDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override | public EntityType getEntityType() {
return EntityType.ADMIN_SETTINGS;
}
private void dropTokenIfProviderInfoChanged(JsonNode newJsonValue, JsonNode oldJsonValue) {
if (newJsonValue.has("enableOauth2") && newJsonValue.get("enableOauth2").asBoolean()) {
if (!newJsonValue.get("providerId").equals(oldJsonValue.get("providerId")) ||
!newJsonValue.get("clientId").equals(oldJsonValue.get("clientId")) ||
!newJsonValue.get("clientSecret").equals(oldJsonValue.get("clientSecret")) ||
!newJsonValue.get("redirectUri").equals(oldJsonValue.get("redirectUri")) ||
(newJsonValue.has("providerTenantId") && !newJsonValue.get("providerTenantId").equals(oldJsonValue.get("providerTenantId")))) {
((ObjectNode) newJsonValue).put("tokenGenerated", false);
((ObjectNode) newJsonValue).remove("refreshToken");
((ObjectNode) newJsonValue).remove("refreshTokenExpires");
}
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\settings\AdminSettingsServiceImpl.java | 1 |
请完成以下Spring Boot application配置 | # database init, supports postgres too
database=postgres
spring.datasource.url=${POSTGRES_URL:jdbc:postgresql://localhost/petclinic}
spring.datasource.username=${POSTGRES_USER:petclinic}
spring.datasource.password=${POSTGR | ES_PASS:petclinic}
# SQL is written to be idempotent so this is safe
spring.sql.init.mode=always | repos\spring-petclinic-main\src\main\resources\application-postgres.properties | 2 |
请完成以下Java代码 | public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final HUPIItemProductId id1, @Nullable final HUPIItemProductId id2)
{
return Objects.equals(id1, id2);
}
public static HUPIItemProductId nullToVirtual(final HUPIItemProductId id)
{
return id != null ? id : VIRTUAL_HU;
}
public boolean isVirtualHU()
{ | return isVirtualHU(repoId);
}
public static boolean isVirtualHU(final int repoId)
{
return repoId == VIRTUAL_HU.repoId;
}
public boolean isRegular()
{
return repoId != VIRTUAL_HU.repoId
&& repoId != TEMPLATE_HU.repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HUPIItemProductId.java | 1 |
请完成以下Java代码 | public ResourceList<User> findAll(QuerySpec querySpec) {
return querySpec.apply(userRepository.findAll());
}
@Override
public ResourceList<User> findAll(Iterable<Long> ids, QuerySpec querySpec) {
return querySpec.apply(userRepository.findAllById(ids));
}
@Override
public <S extends User> S save(S entity) {
return userRepository.save(entity);
}
@Override | public void delete(Long id) {
userRepository.deleteById(id);
}
@Override
public Class<User> getResourceClass() {
return User.class;
}
@Override
public <S extends User> S create(S entity) {
return save(entity);
}
} | repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\katharsis\UserResourceRepository.java | 1 |
请完成以下Java代码 | private static ProductsProposalViewFilter extractPackageableViewFilterVO(final DocumentFilterList filters)
{
return filters.getFilterById(ProductsProposalViewFilter.FILTER_ID)
.map(filter -> toProductsProposalViewFilterValue(filter))
.orElse(ProductsProposalViewFilter.ANY);
}
private static ProductsProposalViewFilter toProductsProposalViewFilterValue(final DocumentFilter filter)
{
return ProductsProposalViewFilter.builder()
.productName(filter.getParameterValueAsString(ProductsProposalViewFilter.PARAM_ProductName, null))
.build();
}
public static DocumentFilterList toDocumentFilters(final ProductsProposalViewFilter filter)
{ | final DocumentFilter.DocumentFilterBuilder builder = DocumentFilter.builder()
.setFilterId(ProductsProposalViewFilter.FILTER_ID)
.setCaption(getDefaultFilterCaption());
if (!Check.isEmpty(filter.getProductName()))
{
builder.addParameter(DocumentFilterParam.ofNameEqualsValue(ProductsProposalViewFilter.PARAM_ProductName, filter.getProductName()));
}
if (!builder.hasParameters())
{
return DocumentFilterList.EMPTY;
}
return DocumentFilterList.of(builder.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\filters\ProductsProposalViewFilters.java | 1 |
请完成以下Java代码 | Long getId() {
return this.id;
}
@Override
public List<AccessControlEntry> getEntries() {
throw new UnsupportedOperationException("Stub only");
}
@Override
public ObjectIdentity getObjectIdentity() {
throw new UnsupportedOperationException("Stub only");
}
@Override
public Sid getOwner() {
throw new UnsupportedOperationException("Stub only");
}
@Override
public Acl getParentAcl() { | throw new UnsupportedOperationException("Stub only");
}
@Override
public boolean isEntriesInheriting() {
throw new UnsupportedOperationException("Stub only");
}
@Override
public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode)
throws NotFoundException, UnloadedSidException {
throw new UnsupportedOperationException("Stub only");
}
@Override
public boolean isSidLoaded(List<Sid> sids) {
throw new UnsupportedOperationException("Stub only");
}
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\BasicLookupStrategy.java | 1 |
请完成以下Java代码 | public static ExternalTaskEntity createAndInsert(ExecutionEntity execution, String topic, long priority) {
ExternalTaskEntity externalTask = new ExternalTaskEntity();
externalTask.setTopicName(topic);
externalTask.setExecutionId(execution.getId());
externalTask.setProcessInstanceId(execution.getProcessInstanceId());
externalTask.setProcessDefinitionId(execution.getProcessDefinitionId());
externalTask.setActivityId(execution.getActivityId());
externalTask.setActivityInstanceId(execution.getActivityInstanceId());
externalTask.setTenantId(execution.getTenantId());
externalTask.setPriority(priority);
externalTask.setCreateTime(ClockUtil.getCurrentTime());
ProcessDefinitionEntity processDefinition = execution.getProcessDefinition();
externalTask.setProcessDefinitionKey(processDefinition.getKey());
externalTask.insert();
externalTask.produceHistoricExternalTaskCreatedEvent();
return externalTask;
}
protected void produceHistoricExternalTaskCreatedEvent() {
CommandContext commandContext = Context.getCommandContext();
commandContext.getHistoricExternalTaskLogManager().fireExternalTaskCreatedEvent(this);
}
protected void produceHistoricExternalTaskFailedEvent() {
CommandContext commandContext = Context.getCommandContext();
commandContext.getHistoricExternalTaskLogManager().fireExternalTaskFailedEvent(this);
}
protected void produceHistoricExternalTaskSuccessfulEvent() {
CommandContext commandContext = Context.getCommandContext();
commandContext.getHistoricExternalTaskLogManager().fireExternalTaskSuccessfulEvent(this);
}
protected void produceHistoricExternalTaskDeletedEvent() {
CommandContext commandContext = Context.getCommandContext();
commandContext.getHistoricExternalTaskLogManager().fireExternalTaskDeletedEvent(this);
} | public void extendLock(long newLockExpirationTime) {
ensureActive();
long newTime = ClockUtil.getCurrentTime().getTime() + newLockExpirationTime;
this.lockExpirationTime = new Date(newTime);
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
if (executionId != null) {
referenceIdAndClass.put(executionId, ExecutionEntity.class);
}
if (errorDetailsByteArrayId != null) {
referenceIdAndClass.put(errorDetailsByteArrayId, ByteArrayEntity.class);
}
return referenceIdAndClass;
}
public String getLastFailureLogId() {
return lastFailureLogId;
}
public void setLastFailureLogId(String lastFailureLogId) {
this.lastFailureLogId = lastFailureLogId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExternalTaskEntity.java | 1 |
请完成以下Java代码 | 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 Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType () | {
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@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\org\compiere\model\X_AD_ColumnCallout.java | 1 |
请完成以下Java代码 | public void setDiscount (java.math.BigDecimal Discount)
{
set_Value (COLUMNNAME_Discount, Discount);
}
/** Get Rabatt %.
@return Discount in percent
*/
@Override
public java.math.BigDecimal getDiscount ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Discount);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (java.math.BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
/** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Zusagbar.
@param QtyPromised Zusagbar */
@Override
public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override | public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ranking.
@param Ranking
Relative Rank Number
*/
@Override
public void setRanking (int Ranking)
{
set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking));
}
/** Get Ranking.
@return Relative Rank Number
*/
@Override
public int getRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ranking);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty.java | 1 |
请完成以下Java代码 | public void add(final I_M_ReceiptSchedule_Alloc rsa)
{
//
// Create HUReceiptLineCandidate Part
final IHUContext huContext = getHUContext();
final I_M_HU tuHU = rsa.getM_TU_HU();
final HUReceiptLinePartAttributes partAttributes = HUReceiptLinePartAttributes.newInstance(huContext, tuHU);
final HUReceiptLinePartCandidate receiptLinePartToAdd = new HUReceiptLinePartCandidate(partAttributes, productId, uomId);
receiptLinePartToAdd.add(rsa);
//
// Add it
add(receiptLinePartToAdd);
}
/**
* Aggregates and adds given {@link HUReceiptLinePartCandidate}.
*
* @param receiptLinePartToAdd
*/
protected void add(final HUReceiptLinePartCandidate receiptLinePartToAdd)
{
//
// Try adding Part to existing Receipt Line Candidate
for (final HUReceiptLineCandidate receiptLineCandidate : receiptLineCandidates)
{
if (receiptLineCandidate.add(receiptLinePartToAdd))
{
stale = true; // we need to recompute the amounts
return;
}
}
//
// Create a new Receipt Line Candidate and add the Part to it
final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule();
final HUReceiptLineCandidate receiptLineCandidate = new HUReceiptLineCandidate(receiptSchedule);
if (!receiptLineCandidate.add(receiptLinePartToAdd))
{
// shall not happen
throw new AdempiereException("New candidate " + receiptLineCandidate + " refused to add " + receiptLinePartToAdd);
}
receiptLineCandidates.add(receiptLineCandidate); // 06135: don't forget to add the fruits of our labour :-P
stale = true; // we need to recompute the amounts
}
public List<HUReceiptLineCandidate> getHUReceiptLineCandidates()
{
return receiptLineCandidatesRO;
}
private final void updateIfStale()
{
if (!stale)
{ | return;
}
//
// Compute qty&quality (qtys, discount percent, quality notices)
// Collect receipt schedule allocations
final ReceiptQty qtyAndQuality = ReceiptQty.newWithoutCatchWeight(productId);
final List<I_M_ReceiptSchedule_Alloc> receiptScheduleAllocs = new ArrayList<I_M_ReceiptSchedule_Alloc>();
for (final HUReceiptLineCandidate receiptLineCandidate : receiptLineCandidates)
{
final ReceiptQty lineQtyAndQuality = receiptLineCandidate.getQtyAndQuality();
qtyAndQuality.add(lineQtyAndQuality);
receiptScheduleAllocs.addAll(receiptLineCandidate.getReceiptScheduleAllocs());
}
//
// Update cumulated values
_qtyAndQuality = qtyAndQuality;
stale = false; // not staled anymore
}
public final ReceiptQty getQtyAndQuality()
{
updateIfStale();
return _qtyAndQuality;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLineCandidatesBuilder.java | 1 |
请完成以下Java代码 | public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
/**
* Returns task State of history tasks
*/
public String getTaskState() { return taskState; }
public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) {
HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto();
dto.id = taskInstance.getId();
dto.processDefinitionKey = taskInstance.getProcessDefinitionKey();
dto.processDefinitionId = taskInstance.getProcessDefinitionId();
dto.processInstanceId = taskInstance.getProcessInstanceId();
dto.executionId = taskInstance.getExecutionId();
dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey();
dto.caseDefinitionId = taskInstance.getCaseDefinitionId();
dto.caseInstanceId = taskInstance.getCaseInstanceId();
dto.caseExecutionId = taskInstance.getCaseExecutionId();
dto.activityInstanceId = taskInstance.getActivityInstanceId();
dto.name = taskInstance.getName();
dto.description = taskInstance.getDescription();
dto.deleteReason = taskInstance.getDeleteReason();
dto.owner = taskInstance.getOwner();
dto.assignee = taskInstance.getAssignee();
dto.startTime = taskInstance.getStartTime(); | dto.endTime = taskInstance.getEndTime();
dto.duration = taskInstance.getDurationInMillis();
dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey();
dto.priority = taskInstance.getPriority();
dto.due = taskInstance.getDueDate();
dto.parentTaskId = taskInstance.getParentTaskId();
dto.followUp = taskInstance.getFollowUpDate();
dto.tenantId = taskInstance.getTenantId();
dto.removalTime = taskInstance.getRemovalTime();
dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId();
dto.taskState = taskInstance.getTaskState();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceDto.java | 1 |
请完成以下Java代码 | public Map<String, Object> executeWithSingleResult() {
return decisionService.executeWithSingleResult(this);
}
@Override
public Map<String, Object> executeDecisionWithSingleResult() {
return decisionService.executeDecisionWithSingleResult(this);
}
@Override
public Map<String, Object> executeDecisionServiceWithSingleResult() {
return decisionService.executeDecisionServiceWithSingleResult(this);
}
@Override
public DecisionExecutionAuditContainer executeWithAuditTrail() {
return decisionService.executeWithAuditTrail(this);
}
@Override
public DecisionExecutionAuditContainer executeDecisionWithAuditTrail() {
return decisionService.executeDecisionWithAuditTrail(this);
}
@Override
public DecisionServiceExecutionAuditContainer executeDecisionServiceWithAuditTrail() {
return decisionService.executeDecisionServiceWithAuditTrail(this);
}
public String getDecisionKey() {
return decisionKey;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getInstanceId() {
return instanceId;
}
public String getExecutionId() { | return executionId;
}
public String getActivityId() {
return activityId;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public boolean isFallbackToDefaultTenant() {
return this.fallbackToDefaultTenant;
}
public Map<String, Object> getVariables() {
return variables;
}
@Override
public ExecuteDecisionContext buildExecuteDecisionContext() {
ExecuteDecisionContext executeDecisionContext = new ExecuteDecisionContext();
executeDecisionContext.setDecisionKey(decisionKey);
executeDecisionContext.setParentDeploymentId(parentDeploymentId);
executeDecisionContext.setInstanceId(instanceId);
executeDecisionContext.setExecutionId(executionId);
executeDecisionContext.setActivityId(activityId);
executeDecisionContext.setScopeType(scopeType);
executeDecisionContext.setVariables(variables);
executeDecisionContext.setTenantId(tenantId);
executeDecisionContext.setFallbackToDefaultTenant(fallbackToDefaultTenant);
executeDecisionContext.setDisableHistory(disableHistory);
return executeDecisionContext;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\ExecuteDecisionBuilderImpl.java | 1 |
请完成以下Java代码 | protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth)
throws AuthenticationException {
_logger.info("MyShiroRealm.doGetAuthenticationInfo()");
String token = (String) auth.getCredentials();
// 解密获得username,用于和数据库进行对比
String username = JWTUtil.getUsername(token);
if (username == null) {
throw new AuthenticationException("token invalid");
}
//通过username从数据库中查找 ManagerInfo对象
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
ManagerInfo managerInfo = managerInfoService.findByUsername(username);
if (managerInfo == null) {
throw new AuthenticationException("用户不存在!");
}
if (!JWTUtil.verify(token, username, managerInfo.getPassword())) {
throw new AuthenticationException("Token认证失败");
}
return new SimpleAuthenticationInfo(token, token, "my_realm");
}
/**
* 此方法调用hasRole,hasPermission的时候才会进行回调.
* <p>
* 权限信息.(授权):
* 1、如果用户正常退出,缓存自动清空;
* 2、如果用户非正常退出,缓存自动清空;
* 3、如果我们修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。
* (需要手动编程进行实现;放在service进行调用)
* 在权限修改后调用realm中的方法,realm已经由spring管理,所以从spring中获取realm实例,调用clearCached方法; | * :Authorization 是授权访问控制,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。
*
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
/*
* 当没有使用缓存的时候,不断刷新页面的话,这个代码会不断执行,
* 当其实没有必要每次都重新设置权限信息,所以我们需要放到缓存中进行管理;
* 当放到缓存中时,这样的话,doGetAuthorizationInfo就只会执行一次了,
* 缓存过期之后会再次执行。
*/
_logger.info("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
String username = JWTUtil.getUsername(principals.toString());
// 下面的可以使用缓存提升速度
ManagerInfo managerInfo = managerInfoService.findByUsername(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//设置相应角色的权限信息
for (SysRole role : managerInfo.getRoles()) {
//设置角色
authorizationInfo.addRole(role.getRole());
for (Permission p : role.getPermissions()) {
//设置权限
authorizationInfo.addStringPermission(p.getPermission());
}
}
return authorizationInfo;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\shiro\MyShiroRealm.java | 1 |
请完成以下Java代码 | public DeliveryAddress setSurname(String surname) {
this.surname = surname;
return this;
}
public String getStreet() {
return street;
}
public DeliveryAddress setStreet(String street) {
this.street = street;
return this;
}
public String getPostalcode() {
return postalcode; | }
public DeliveryAddress setPostalcode(String postalcode) {
this.postalcode = postalcode;
return this;
}
public String getCounty() {
return county;
}
public DeliveryAddress setCounty(String county) {
this.county = county;
return this;
}
} | repos\tutorials-master\mapstruct\src\main\java\com\baeldung\entity\DeliveryAddress.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.