instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
class Employee {
@Id
private String id;
private String name;
/**
* Only hold the id of the manager to link to it.
*/
private String managerId;
public Employee() {
}
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
|
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getManagerId() {
return managerId;
}
public void setManagerId(String managerId) {
this.managerId = managerId;
}
}
|
repos\spring-data-examples-main\mongodb\linking\src\main\java\example\springdata\mongodb\linking\docref\jpastyle\Employee.java
| 1
|
请完成以下Java代码
|
public class AuthorizationCheckCmd implements Command<Boolean> {
protected static final EnginePersistenceLogger LOG = ProcessEngineLogger.PERSISTENCE_LOGGER;
protected String userId;
protected List<String> groupIds;
protected Permission permission;
protected Resource resource;
protected String resourceId;
public AuthorizationCheckCmd(String userId, List<String> groupIds, Permission permission, Resource resource, String resourceId) {
this.userId = userId;
this.groupIds = groupIds;
this.permission = permission;
this.resource = resource;
this.resourceId = resourceId;
validate(userId, groupIds, permission, resource);
}
public Boolean execute(CommandContext commandContext) {
final AuthorizationManager authorizationManager = commandContext.getAuthorizationManager();
if (authorizationManager.isPermissionDisabled(permission)) {
throw LOG.disabledPermissionException(permission.getName());
}
if (isHistoricInstancePermissionsDisabled(commandContext) && isHistoricInstanceResource()) {
throw LOG.disabledHistoricInstancePermissionsException();
}
|
return authorizationManager.isAuthorized(userId, groupIds, permission, resource, resourceId);
}
protected void validate(String userId, List<String> groupIds, Permission permission, Resource resource) {
ensureAtLeastOneNotNull("Authorization must have a 'userId' or/and a 'groupId'.", userId, groupIds);
ensureNotNull("Invalid permission for an authorization", "authorization.getResource()", permission);
ensureNotNull("Invalid resource for an authorization", "authorization.getResource()", resource);
}
protected boolean isHistoricInstancePermissionsDisabled(CommandContext commandContext) {
return !commandContext.getProcessEngineConfiguration().isEnableHistoricInstancePermissions();
}
protected boolean isHistoricInstanceResource() {
return Objects.equals(Resources.HISTORIC_TASK, resource) ||
Objects.equals(Resources.HISTORIC_PROCESS_INSTANCE, resource);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AuthorizationCheckCmd.java
| 1
|
请完成以下Java代码
|
public class SysUserExportVo {
/**
* 登录账号
*/
@Excel(name = "登录账号", width = 15)
private String username;
/**
* 真实姓名
*/
@Excel(name = "真实姓名", width = 15)
private String realname;
/**
* 头像
*/
@Excel(name = "头像", width = 15, type = 2)
private String avatar;
/**
* 生日
*/
@Excel(name = "生日", width = 15, format = "yyyy-MM-dd")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
/**
* 性别(1:男 2:女)
*/
@Excel(name = "性别", width = 15, dicCode = "sex")
private Integer sex;
/**
* 电子邮件
*/
@Excel(name = "电子邮件", width = 15)
private String email;
/**
* 电话
*/
@Excel(name = "电话", width = 15)
private String phone;
/**
* 状态(1:正常 2:冻结 )
*/
@Excel(name = "状态", width = 15, dicCode = "user_status")
private Integer status;
/**
* 删除状态(0,正常,1已删除)
*/
@Excel(name = "删除状态", width = 15, dicCode = "del_flag")
private Integer delFlag;
/**
* 工号,唯一键
*/
@Excel(name = "工号", width = 15)
private String workNo;
/**
* 主岗位
*/
@Excel(name="主岗位",width = 15,dictTable ="sys_depart",dicText = "depart_name",dicCode = "id")
@Dict(dictTable ="sys_depart",dicText = "depart_name",dicCode = "id")
private String mainDepPostId;
/**
* 职级
*/
@Excel(name="职级", width = 15)
private String postName;
|
/**
* 兼职岗位
*/
@Excel(name="兼职岗位",width = 15,dictTable ="sys_depart",dicText = "depart_name",dicCode = "id")
@Dict(dictTable ="sys_depart",dicText = "depart_name",dicCode = "id")
private String otherDepPostId;
/**
* 座机号
*/
@Excel(name = "座机号", width = 15)
private String telephone;
/**
* 身份(0 普通成员 1 上级)
*/
@Excel(name = "(1普通成员 2上级)", width = 15)
private Integer userIdentity;
/**
* 角色名称
*/
@Excel(name = "角色", width = 15)
private String roleNames;
/**
* 部门名称
*/
@Excel(name = "所属部门", width = 15)
private String departNames;
/**
* 机构类型
* 公司(1)、部门(2)、岗位(3)、子公司(4)
*/
@Excel(name = "部门类型(1-公司,2-部门,3-岗位,4-子公司)",width = 15)
private String orgCategorys;
/**
* 负责部门
*/
@Excel(name = "负责部门", width = 15)
private String departIds;
/**
* 职务
*/
@Excel(name="职务", dicCode = "user_position")
private String positionType;
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\SysUserExportVo.java
| 1
|
请完成以下Java代码
|
public String getRuleConditions() {
return ruleConditions;
}
public void setRuleConditions(String ruleConditions) {
this.ruleConditions = ruleConditions;
}
public String getRuleValue() {
return ruleValue;
}
public void setRuleValue(String ruleValue) {
this.ruleValue = ruleValue;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
|
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysPermissionDataRuleModel.java
| 1
|
请完成以下Java代码
|
public boolean isHistoryEnabledForIdentityLink(IdentityLinkEntity identityLink) {
String processDefinitionId = getProcessDefinitionId(identityLink);
return isHistoryLevelAtLeast(HistoryLevel.AUDIT, processDefinitionId);
}
protected String getProcessDefinitionId(IdentityLinkEntity identityLink) {
String processDefinitionId = null;
if (identityLink.getProcessInstanceId() != null) {
ExecutionEntity execution = processEngineConfiguration.getExecutionEntityManager().findById(identityLink.getProcessInstanceId());
if (execution != null) {
processDefinitionId = execution.getProcessDefinitionId();
}
} else if (identityLink.getTaskId() != null) {
TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(identityLink.getTaskId());
if (task != null) {
processDefinitionId = task.getProcessDefinitionId();
}
}
return processDefinitionId;
}
@Override
public boolean isHistoryEnabledForEntityLink(EntityLinkEntity entityLink) {
String processDefinitionId = getProcessDefinitionId(entityLink);
return isHistoryEnabled(processDefinitionId);
}
@Override
public boolean isHistoryEnabledForVariables(HistoricTaskInstance historicTaskInstance) {
return processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY);
}
|
protected String getProcessDefinitionId(EntityLinkEntity entityLink) {
String processDefinitionId = null;
if (ScopeTypes.BPMN.equals(entityLink.getScopeType()) && entityLink.getScopeId() != null) {
ExecutionEntity execution = processEngineConfiguration.getExecutionEntityManager().findById(entityLink.getScopeId());
if (execution != null) {
processDefinitionId = execution.getProcessDefinitionId();
}
} else if (ScopeTypes.TASK.equals(entityLink.getScopeType()) && entityLink.getScopeId() != null) {
TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(entityLink.getScopeId());
if (task != null) {
processDefinitionId = task.getProcessDefinitionId();
}
}
return processDefinitionId;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\DefaultHistoryConfigurationSettings.java
| 1
|
请完成以下Java代码
|
public static Optional<BPartnerId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
@JsonCreator
public static BPartnerId ofObject(@NonNull final Object object)
{
return RepoIdAwares.ofObject(object, BPartnerId.class, BPartnerId::ofRepoId);
}
public static int toRepoId(@Nullable final BPartnerId bpartnerId)
{
return toRepoIdOr(bpartnerId, -1);
}
public static int toRepoIdOr(@Nullable final BPartnerId bpartnerId, final int defaultValue)
{
|
return bpartnerId != null ? bpartnerId.getRepoId() : defaultValue;
}
private BPartnerId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BPartner_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final BPartnerId o1, @Nullable final BPartnerId o2)
{
return Objects.equals(o1, o2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private boolean isCountryMatching(final I_M_PriceList priceList)
{
if (countryIds == null)
{
return true;
}
final CountryId priceListCountryId = CountryId.ofRepoIdOrNull(priceList.getC_Country_ID());
if (priceListCountryId == null && acceptNoCountry)
{
return true;
}
if (countryIds.isEmpty())
{
|
return priceListCountryId == null;
}
else
{
return countryIds.contains(priceListCountryId);
}
}
private boolean isSOTrxMatching(final I_M_PriceList priceList)
{
return soTrx == null || soTrx.isSales() == priceList.isSOPriceList();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\PriceListsCollection.java
| 2
|
请完成以下Java代码
|
public int getC_InvoiceTax_ID()
{
return get_ValueAsInt(COLUMNNAME_C_InvoiceTax_ID);
}
@Override
public void setC_Tax_ID (final int C_Tax_ID)
{
if (C_Tax_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Tax_ID, C_Tax_ID);
}
@Override
public int getC_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Tax_ID);
}
@Override
public void setIsDocumentLevel (final boolean IsDocumentLevel)
{
set_Value (COLUMNNAME_IsDocumentLevel, IsDocumentLevel);
}
@Override
public boolean isDocumentLevel()
{
return get_ValueAsBoolean(COLUMNNAME_IsDocumentLevel);
}
@Override
public void setIsPackagingTax (final boolean IsPackagingTax)
{
set_Value (COLUMNNAME_IsPackagingTax, IsPackagingTax);
}
@Override
public boolean isPackagingTax()
{
return get_ValueAsBoolean(COLUMNNAME_IsPackagingTax);
}
@Override
public void setIsTaxIncluded (final boolean IsTaxIncluded)
{
set_Value (COLUMNNAME_IsTaxIncluded, IsTaxIncluded);
}
@Override
public boolean isTaxIncluded()
{
return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded);
}
@Override
public void setIsWholeTax (final boolean IsWholeTax)
{
set_Value (COLUMNNAME_IsWholeTax, IsWholeTax);
}
@Override
public boolean isWholeTax()
{
return get_ValueAsBoolean(COLUMNNAME_IsWholeTax);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
|
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTaxBaseAmt (final BigDecimal TaxBaseAmt)
{
set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt);
}
@Override
public BigDecimal getTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt);
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_InvoiceTax.java
| 1
|
请完成以下Java代码
|
public void addEmit(Collection<Integer> emits)
{
for (int emit : emits)
{
addEmit(emit);
}
}
/**
* 获取这个节点代表的模式串(们)
* @return
*/
public Collection<Integer> emit()
{
return this.emits == null ? Collections.<Integer>emptyList() : this.emits;
}
/**
* 是否是终止状态
* @return
*/
public boolean isAcceptable()
{
return this.depth > 0 && this.emits != null;
}
/**
* 获取failure状态
* @return
*/
public State failure()
{
return this.failure;
}
/**
* 设置failure状态
* @param failState
*/
public void setFailure(State failState, int fail[])
{
this.failure = failState;
fail[index] = failState.index;
}
/**
* 转移到下一个状态
* @param character 希望按此字符转移
* @param ignoreRootState 是否忽略根节点,如果是根节点自己调用则应该是true,否则为false
* @return 转移结果
*/
private State nextState(Character character, boolean ignoreRootState)
{
State nextState = this.success.get(character);
if (!ignoreRootState && nextState == null && this.depth == 0)
{
nextState = this;
}
return nextState;
}
/**
* 按照character转移,根节点转移失败会返回自己(永远不会返回null)
* @param character
* @return
*/
public State nextState(Character character)
{
return nextState(character, false);
}
/**
* 按照character转移,任何节点转移失败会返回null
* @param character
* @return
*/
public State nextStateIgnoreRootState(Character character)
{
return nextState(character, true);
}
|
public State addState(Character character)
{
State nextState = nextStateIgnoreRootState(character);
if (nextState == null)
{
nextState = new State(this.depth + 1);
this.success.put(character, nextState);
}
return nextState;
}
public Collection<State> getStates()
{
return this.success.values();
}
public Collection<Character> getTransitions()
{
return this.success.keySet();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("State{");
sb.append("depth=").append(depth);
sb.append(", ID=").append(index);
sb.append(", emits=").append(emits);
sb.append(", success=").append(success.keySet());
sb.append(", failureID=").append(failure == null ? "-1" : failure.index);
sb.append(", failure=").append(failure);
sb.append('}');
return sb.toString();
}
/**
* 获取goto表
* @return
*/
public Map<Character, State> getSuccess()
{
return success;
}
public int getIndex()
{
return index;
}
public void setIndex(int index)
{
this.index = index;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\AhoCorasick\State.java
| 1
|
请完成以下Java代码
|
public void updateBPartnerGlobalIDImortTable(@NonNull final ImportRecordsSelection selection)
{
dbUpdateCbPartnerIdsFromGlobalID(selection);
dbUpdateErrorMessages(selection);
}
private void dbUpdateCbPartnerIdsFromGlobalID(final ImportRecordsSelection selection)
{
StringBuilder sql;
int no;
sql = new StringBuilder("UPDATE " + I_I_BPartner_GlobalID.Table_Name + " i ")
.append("SET C_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner p ")
.append("WHERE i." + I_I_BPartner_GlobalID.COLUMNNAME_GlobalId)
.append("=p." + I_C_BPartner.COLUMNNAME_GlobalId)
.append(" AND p.AD_Client_ID=i.AD_Client_ID ")
.append(" AND p.IsActive='Y') ")
.append("WHERE C_BPartner_ID IS NULL AND " + I_I_BPartner_GlobalID.COLUMNNAME_GlobalId + " IS NOT NULL")
.append(" AND " + COLUMNNAME_I_IsImported + "='N'")
|
.append(selection.toSqlWhereClause("i"));
no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
logger.info("Found BPartner={}", no);
}
private void dbUpdateErrorMessages(final ImportRecordsSelection selection)
{
StringBuilder sql;
int no;
sql = new StringBuilder("UPDATE " + I_I_BPartner_GlobalID.Table_Name)
.append(" SET " + COLUMNNAME_I_IsImported + "='N', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Partner is mandatory, ' ")
.append("WHERE " + I_I_BPartner_GlobalID.COLUMNNAME_C_BPartner_ID + " IS NULL ")
.append("AND " + COLUMNNAME_I_IsImported + "<>'Y'")
.append(selection.toSqlWhereClause());
no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
logger.info("Value is mandatory={}", no);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\globalid\impexp\BPartnerGlobalIDImportTableSqlUpdater.java
| 1
|
请完成以下Spring Boot application配置
|
#
# Copyright 2015-2022 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language gove
|
rning permissions and
# limitations under the License.
#
logging.level.root=WARN
logging.level.sample.mybatis.velocity.mapper=TRACE
mybatis.mapper-locations=classpath*:/mappers/*.xml
mybatis.type-aliases-package=sample.mybatis.velocity.domain
|
repos\spring-boot-starter-master\mybatis-spring-boot-samples\mybatis-spring-boot-sample-velocity\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void saveAndPush(@NonNull final ProductSupply productSupply)
{
productSupplyRepository.save(productSupply);
senderToMetasfreshService.syncAfterCommit().add(productSupply);
}
private void saveAndPush(@NonNull final WeekSupply weeklySupply)
{
weekSupplyRepository.save(weeklySupply);
senderToMetasfreshService.syncAfterCommit().add(weeklySupply);
}
@Override
public Product getProductById(final long productId)
{
return productRepository.getOne(productId);
}
@Override
public void importPlanningSupply(@NonNull final ImportPlanningSupplyRequest request)
{
final BPartner bpartner = request.getBpartner();
final ContractLine contractLine = request.getContractLine();
final Product product = productRepository.findByUuid(request.getProduct_uuid());
final LocalDate day = request.getDate();
final BigDecimal qty = request.getQty();
ProductSupply productSupply = productSupplyRepository.findByProductAndBpartnerAndDay(product, bpartner, DateUtils.toSqlDate(day));
final boolean isNew;
if (productSupply == null)
{
isNew = true;
productSupply = ProductSupply.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.product(product)
.day(day)
.build();
}
else
{
isNew = false;
}
//
// Contract line
if (!isNew)
{
final ContractLine contractLineOld = productSupply.getContractLine();
if (!Objects.equals(contractLine, contractLineOld))
{
logger.warn("Changing contract line {}->{} for {} because of planning supply: {}", contractLineOld, contractLine, productSupply, request);
}
productSupply.setContractLine(contractLine);
|
}
//
// Quantity
if (!isNew)
{
final BigDecimal qtyOld = productSupply.getQty();
if (qty.compareTo(qtyOld) != 0)
{
logger.warn("Changing quantity {}->{} for {} because of planning supply: {}", qtyOld, qty, productSupply, request);
}
}
productSupply.setQtyUserEntered(qty);
productSupply.setQty(qty);
//
// Save the product supply
saveAndPush(productSupply);
}
@Override
@Transactional
public void confirmUserEntries(@NonNull final User user)
{
final BPartner bpartner = user.getBpartner();
final List<ProductSupply> productSupplies = productSupplyRepository.findUnconfirmed(bpartner);
for (final ProductSupply productSupply : productSupplies)
{
productSupply.setQty(productSupply.getQtyUserEntered());
saveAndPush(productSupply);
}
}
@Override
public long getCountUnconfirmed(@NonNull final User user)
{
return productSupplyRepository.countUnconfirmed(user.getBpartner());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\ProductSuppliesService.java
| 2
|
请完成以下Java代码
|
public class Author {
@Id
private Object id;
private String firstName;
private String lastName;
private int level;
public Author() {
}
public Author(String firstName, String lastName, int level) {
this.firstName = firstName;
this.lastName = lastName;
this.level = level;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
|
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
@java.lang.Override
public java.lang.String toString() {
return "Author{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", level=" + level +
'}';
}
}
|
repos\tutorials-master\persistence-modules\orientdb\src\main\java\com\baeldung\orientdb\Author.java
| 1
|
请完成以下Java代码
|
private static String buildMessage(final IPricingContext pricingCtx, final int documentLineNo)
{
return buildMessage(documentLineNo,
pricingCtx.getProductId(),
pricingCtx.getPriceListId(),
pricingCtx.getPriceDate());
}
protected static String buildMessage(final int documentLineNo, final ProductId productId, final PriceListId priceListId, final LocalDate priceDate)
{
final StringBuilder sb = new StringBuilder();
if (documentLineNo > 0)
{
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append("@Line@:").append(documentLineNo);
}
if (productId != null)
{
final String productName = Services.get(IProductBL.class).getProductValueAndName(productId);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append("@M_Product_ID@:").append(productName);
}
if (priceListId != null)
{
final String priceListName = Services.get(IPriceListDAO.class).getPriceListName(priceListId);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append("@M_PriceList_ID@:").append(priceListName);
}
if (priceDate != null)
{
final DateFormat df = DisplayType.getDateFormat(DisplayType.Date);
if (sb.length() > 0)
{
sb.append(", ");
|
}
sb.append("@Date@:").append(df.format(priceDate));
}
//
sb.insert(0, "@" + AD_Message + "@ - ");
return sb.toString();
}
private static String buildMessage(final I_M_PriceList_Version plv, final int productId)
{
final StringBuilder sb = new StringBuilder("@NotFound@ @M_ProductPrice_ID@");
//
// Product
final I_M_Product product = productId > 0 ? loadOutOfTrx(productId, I_M_Product.class) : null;
sb.append("\n@M_Product_ID@: ").append(product == null ? "<" + productId + ">" : product.getName());
//
// Price List Version
sb.append("\n@M_PriceList_Version_ID@: ").append(plv == null ? "-" : plv.getName());
//
// Price List
final I_M_PriceList priceList = plv == null ? null : Services.get(IPriceListDAO.class).getById(PriceListId.ofRepoId(plv.getM_PriceList_ID()));
sb.append("\n@M_PriceList_ID@: ").append(priceList == null ? "-" : priceList.getName());
//
// Pricing System
final PricingSystemId pricingSystemId = priceList != null
? PricingSystemId.ofRepoIdOrNull(priceList.getM_PricingSystem_ID())
: null;
final String pricingSystemName = pricingSystemId != null
? Services.get(IPriceListDAO.class).getPricingSystemName(pricingSystemId)
: "-";
sb.append("\n@M_PricingSystem_ID@: ").append(pricingSystemName);
return sb.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\pricing\exceptions\ProductNotOnPriceListException.java
| 1
|
请完成以下Java代码
|
public static SecretKey generateSecretKey() {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstanceStrong();
keyGenerator.init(AES_KEY_SIZE, random);
return keyGenerator.generateKey();
}
/**
* <p>generateBase64EncodedSecretKey.</p>
*
* @return a {@link java.lang.String} object
*/
@SneakyThrows
public static String generateBase64EncodedSecretKey() {
SecretKey key = generateSecretKey();
byte[] secretKeyBytes = key.getEncoded();
return Base64.getEncoder().encodeToString(secretKeyBytes);
}
/**
* <p>getAESKeyFromPassword.</p>
*
* @param password an array of {@link char} objects
* @param saltGenerator a {@link org.jasypt.salt.SaltGenerator} object
* @param iterations a int
* @param algorithm a {@link java.lang.String} object
* @return a {@link javax.crypto.SecretKey} object
*/
@SneakyThrows
public static SecretKey getAESKeyFromPassword(char[] password, SaltGenerator saltGenerator, int iterations, String algorithm){
|
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(password, saltGenerator.generateSalt(AES_KEY_PASSWORD_SALT_LENGTH), iterations, AES_KEY_SIZE);
return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
}
/**
* <p>Constructor for SimpleGCMByteEncryptor.</p>
*
* @param config a {@link com.ulisesbocchio.jasyptspringboot.encryptor.SimpleGCMConfig} object
*/
public SimpleGCMByteEncryptor(SimpleGCMConfig config) {
this.key = Singleton.from(this::loadSecretKey, config);
this.ivGenerator = Singleton.from(config::getActualIvGenerator);
this.algorithm = config.getAlgorithm();
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimpleGCMByteEncryptor.java
| 1
|
请完成以下Java代码
|
public class HUTraceModuleInterceptor extends AbstractModuleInterceptor
{
public static final String SYSCONFIG_ENABLED = "de.metas.handlingunits.trace.interceptor.enabled";
public static final HUTraceModuleInterceptor INSTANCE = new HUTraceModuleInterceptor();
/**
* Only set for testing
*/
private HUTraceEventsService huTraceEventsService;
private HUTraceModuleInterceptor()
{
}
@Override
protected void registerInterceptors(final IModelValidationEngine engine)
{
if (!isEnabled())
{
return;
}
engine.addModelValidator(new PP_Cost_Collector());
engine.addModelValidator(new M_InOut());
engine.addModelValidator(new M_Movement());
// engine.addModelValidator(new M_ShipmentSchedule_QtyPicked()); this one is now a spring component
}
/**
* Registers a new {@link TraceHUTrxListener}.
*/
@Override
protected void onAfterInit()
{
if (!isEnabled())
{
return;
}
final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class);
huTrxBL.addListener(TraceHUTrxListener.INSTANCE);
}
/**
* Allow the {@link HUTraceEventsService} to be set from outside. Goal: allow testing without the need to fire up the spring-boot test runner.
*
* @param huTraceEventsService
*/
@VisibleForTesting
|
public void setHUTraceEventsService(@NonNull final HUTraceEventsService huTraceEventsService)
{
this.huTraceEventsService = huTraceEventsService;
}
public HUTraceEventsService getHUTraceEventsService()
{
if (huTraceEventsService != null)
{
return huTraceEventsService;
}
return Adempiere.getBean(HUTraceEventsService.class);
}
/**
* Uses {@link ISysConfigBL} to check if tracing shall be enabled. Note that the default value is false,
* because we don't want this to fire in <i>"unit"</i> tests by default.
* If you want to test against this feature, you can explicitly enable it for your test.
*
* @return
*/
public boolean isEnabled()
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final boolean enabled = sysConfigBL.getBooleanValue(SYSCONFIG_ENABLED, false, Env.getAD_Client_ID(Env.getCtx()), Env.getAD_Org_ID(Env.getCtx()));
return enabled;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\interceptor\HUTraceModuleInterceptor.java
| 1
|
请完成以下Java代码
|
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausschluß.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
@Override
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Ausschluß.
@return Exclude access to the data - if not selected Include access to the data
*/
@Override
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Schreibgeschützt.
@param IsReadOnly
Field is read only
*/
|
@Override
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Schreibgeschützt.
@return Field is read only
*/
@Override
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
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_AD_Column_Access.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static class AllocationGroupingKey
{
@NonNull ProductId productId;
@NonNull LocatorId pickFromLocatorId;
}
private static class AllocableHU
{
private final IHUStorageFactory storageFactory;
@Getter
private final I_M_HU topLevelHU;
private final ProductId productId;
private Quantity _storageQty;
private Quantity qtyAllocated;
public AllocableHU(
final IHUStorageFactory storageFactory,
final I_M_HU topLevelHU,
final ProductId productId)
{
this.storageFactory = storageFactory;
this.topLevelHU = topLevelHU;
this.productId = productId;
}
public Quantity getQtyAvailableToAllocate()
{
final Quantity qtyStorage = getStorageQty();
return qtyAllocated != null
? qtyStorage.subtract(qtyAllocated)
: qtyStorage;
}
private Quantity getStorageQty()
{
Quantity storageQty = this._storageQty;
|
if (storageQty == null)
{
storageQty = this._storageQty = storageFactory.getStorage(topLevelHU).getProductStorage(productId).getQty();
}
return storageQty;
}
public void addQtyAllocated(@NonNull final Quantity qtyAllocatedToAdd)
{
final Quantity newQtyAllocated = this.qtyAllocated != null
? this.qtyAllocated.add(qtyAllocatedToAdd)
: qtyAllocatedToAdd;
final Quantity storageQty = getStorageQty();
if (newQtyAllocated.isGreaterThan(storageQty))
{
throw new AdempiereException("Over-allocating is not allowed")
.appendParametersToMessage()
.setParameter("this.qtyAllocated", this.qtyAllocated)
.setParameter("newQtyAllocated", newQtyAllocated)
.setParameter("storageQty", storageQty);
}
this.qtyAllocated = newQtyAllocated;
}
}
private static class AllocableHUsList implements Iterable<AllocableHU>
{
private final ImmutableList<AllocableHU> hus;
private AllocableHUsList(@NonNull final ImmutableList<AllocableHU> hus) {this.hus = hus;}
@Override
public @NonNull Iterator<AllocableHU> iterator() {return hus.iterator();}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\plan\DDOrderMovePlanCreateCommand.java
| 2
|
请完成以下Java代码
|
public class Address implements Hidable {
private String city;
private String country;
private boolean hidden;
public Address(final String city, final String country, final boolean hidden) {
super();
this.city = city;
this.country = country;
this.hidden = hidden;
}
public String getCity() {
return city;
}
public void setCity(final String city) {
this.city = city;
}
public String getCountry() {
return country;
|
}
public void setCountry(final String country) {
this.country = country;
}
@Override
public boolean isHidden() {
return hidden;
}
public void setHidden(final boolean hidden) {
this.hidden = hidden;
}
}
|
repos\tutorials-master\jackson-modules\jackson-custom-conversions\src\main\java\com\baeldung\skipfields\Address.java
| 1
|
请完成以下Java代码
|
public UserOperationLogQuery entityTypeIn(String... entityTypes) {
ensureNotNull("entity types", (Object[]) entityTypes);
this.entityTypes = entityTypes;
return this;
}
public UserOperationLogQuery category(String category) {
ensureNotNull("category", category);
this.category = category;
return this;
}
public UserOperationLogQuery categoryIn(String... categories) {
ensureNotNull("categories", (Object[]) categories);
this.categories = categories;
return this;
}
public UserOperationLogQuery afterTimestamp(Date after) {
this.timestampAfter = after;
return this;
}
public UserOperationLogQuery beforeTimestamp(Date before) {
this.timestampBefore = before;
return this;
}
public UserOperationLogQuery orderByTimestamp() {
return orderBy(OperationLogQueryProperty.TIMESTAMP);
}
public long executeCount(CommandContext commandContext) {
checkQueryOk();
|
return commandContext
.getOperationLogManager()
.findOperationLogEntryCountByQueryCriteria(this);
}
public List<UserOperationLogEntry> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getOperationLogManager()
.findOperationLogEntriesByQueryCriteria(this, page);
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public UserOperationLogQuery tenantIdIn(String... tenantIds) {
ensureNotNull("tenantIds", (Object[]) tenantIds);
this.tenantIds = tenantIds;
this.isTenantIdSet = true;
return this;
}
public UserOperationLogQuery withoutTenantId() {
this.tenantIds = null;
this.isTenantIdSet = true;
return this;
}
@Override
protected boolean hasExcludingConditions() {
return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(timestampAfter, timestampBefore);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserOperationLogQueryImpl.java
| 1
|
请完成以下Java代码
|
private ConfigurationPropertyName convertName(String propertySourceName) {
try {
return ConfigurationPropertyName.adapt(propertySourceName, '_', this::processElementValue);
}
catch (Exception ex) {
return ConfigurationPropertyName.EMPTY;
}
}
private CharSequence processElementValue(CharSequence value) {
String result = value.toString().toLowerCase(Locale.ENGLISH);
return isNumber(result) ? "[" + result + "]" : result;
}
private static boolean isNumber(String string) {
return string.chars().allMatch(Character::isDigit);
}
@Override
|
public BiPredicate<ConfigurationPropertyName, ConfigurationPropertyName> getAncestorOfCheck() {
return this::isAncestorOf;
}
private boolean isAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) {
return name.isAncestorOf(candidate) || isLegacyAncestorOf(name, candidate);
}
private boolean isLegacyAncestorOf(ConfigurationPropertyName name, ConfigurationPropertyName candidate) {
if (!name.hasDashedElement()) {
return false;
}
ConfigurationPropertyName legacyCompatibleName = name.asSystemEnvironmentLegacyName();
return legacyCompatibleName != null && legacyCompatibleName.isAncestorOf(candidate);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\SystemEnvironmentPropertyMapper.java
| 1
|
请完成以下Java代码
|
public void setText(final String text)
{
messageBuf.setLength(0);
appendText(text);
}
public void appendText(final String text)
{
messageBuf.append(text);
message.setText(messageBuf.toString());
}
@Override
public Dimension getPreferredSize()
{
final Dimension d = super.getPreferredSize();
final Dimension m = getMaximumSize();
|
if (d.height > m.height || d.width > m.width)
{
final Dimension d1 = new Dimension();
d1.height = Math.min(d.height, m.height);
d1.width = Math.min(d.width, m.width);
return d1;
}
else
{
return d;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessPanel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BooleanType implements VariableType {
public static final String TYPE_NAME = "boolean";
private static final long serialVersionUID = 1L;
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
if (valueFields.getLongValue() != null) {
return valueFields.getLongValue() == 1;
}
return null;
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value == null) {
valueFields.setLongValue(null);
|
} else {
Boolean booleanValue = (Boolean) value;
if (booleanValue) {
valueFields.setLongValue(1L);
} else {
valueFields.setLongValue(0L);
}
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Boolean.class.isAssignableFrom(value.getClass()) || boolean.class.isAssignableFrom(value.getClass());
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\BooleanType.java
| 2
|
请完成以下Java代码
|
public int toInt()
{
return toOptionalInt()
.orElseThrow(() -> new AdempiereException("WindowId cannot be converted to int: " + this));
}
public int toIntOr(final int fallbackValue)
{
return toOptionalInt()
.orElse(fallbackValue);
}
private OptionalInt toOptionalInt()
{
OptionalInt valueInt = this.valueInt;
if (valueInt == null)
{
valueInt = this.valueInt = parseOptionalInt();
}
return valueInt;
}
private OptionalInt parseOptionalInt()
{
try
{
return OptionalInt.of(Integer.parseInt(value));
}
catch (final Exception ex)
{
return OptionalInt.empty();
}
}
@Nullable
public AdWindowId toAdWindowIdOrNull()
{
return AdWindowId.ofRepoIdOrNull(toIntOr(-1));
}
|
public AdWindowId toAdWindowId()
{
return AdWindowId.ofRepoId(toInt());
}
public boolean isInt()
{
return toOptionalInt().isPresent();
}
public DocumentId toDocumentId()
{
return DocumentId.of(value);
}
public static boolean equals(@Nullable final WindowId id1, @Nullable final WindowId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\WindowId.java
| 1
|
请完成以下Java代码
|
protected void addListeners(CmmnActivity activity) {
if(activity != null) {
activity.addBuiltInListener(CaseExecutionListener.START, listener);
activity.addBuiltInListener(CaseExecutionListener.MANUAL_START, listener);
activity.addBuiltInListener(CaseExecutionListener.OCCUR, listener);
}
}
public void transformHumanTask(PlanItem planItem, HumanTask humanTask, CmmnActivity activity) {
addListeners(activity);
}
public void transformProcessTask(PlanItem planItem, ProcessTask processTask, CmmnActivity activity) {
addListeners(activity);
}
public void transformCaseTask(PlanItem planItem, CaseTask caseTask, CmmnActivity activity) {
addListeners(activity);
}
|
public void transformDecisionTask(PlanItem planItem, DecisionTask decisionTask, CmmnActivity activity) {
addListeners(activity);
}
public void transformTask(PlanItem planItem, Task task, CmmnActivity activity) {
addListeners(activity);
}
public void transformStage(PlanItem planItem, Stage stage, CmmnActivity activity) {
addListeners(activity);
}
public void transformMilestone(PlanItem planItem, Milestone milestone, CmmnActivity activity) {
addListeners(activity);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\parser\MetricsCmmnTransformListener.java
| 1
|
请完成以下Java代码
|
private WorkflowLaunchersList toWorkflowLaunchersList(final List<HUConsolidationJobReference> jobReferences)
{
final PickingSlotQueuesSummary stats = getMissingStats(jobReferences);
final HUConsolidationLauncherCaptionProvider captionProvider = captionProviderFactory.newCaptionProvider();
return WorkflowLaunchersList.builder()
.launchers(jobReferences.stream()
.map(jobReference -> jobReference.withUpdatedStats(stats))
.map(jobReference -> WorkflowLauncher.builder()
.applicationId(HUConsolidationApplication.APPLICATION_ID)
.caption(captionProvider.computeCaption(jobReference))
.wfParameters(jobReference.toParams())
.startedWFProcessId(jobReference.getStartedJobId() != null
? jobReference.getStartedJobId().toWFProcessId()
: null)
.build())
.collect(ImmutableList.toImmutableList()))
.build();
}
private PickingSlotQueuesSummary getMissingStats(final List<HUConsolidationJobReference> jobReferences)
{
final ImmutableSet<PickingSlotId> pickingSlotIdsWithoutStats = jobReferences.stream()
.filter(HUConsolidationJobReference::isStatsMissing)
.flatMap(jobReference -> jobReference.getPickingSlotIds().stream())
.collect(ImmutableSet.toImmutableSet());
if (pickingSlotIdsWithoutStats.isEmpty())
|
{
return PickingSlotQueuesSummary.EMPTY;
}
return pickingSlotService.getNotEmptyQueuesSummary(PickingSlotQueueQuery.onlyPickingSlotIds(pickingSlotIdsWithoutStats));
}
//
//
//
@Value
@Builder
private static class HUConsolidationJobReferenceKey
{
@NonNull BPartnerLocationId bpartnerLocationId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\launchers\HUConsolidationWorkflowLaunchersProvider.java
| 1
|
请完成以下Java代码
|
public void resetCalculations()
{
m_actualQty = Env.ZERO;
m_actualMin = Env.ZERO;
m_actualAllocation = Env.ZERO;
// m_lastDifference = Env.ZERO;
m_maxAllocation = Env.ZERO;
} // resetCalculations
/**************************************************************************
* Get Product
* @return product
*/
public MProduct getProduct()
{
if (m_product == null)
m_product = MProduct.get(getCtx(), getM_Product_ID());
return m_product;
} // getProduct
/**
* Get Product Standard Precision
* @return standard precision
*/
public int getUOMPrecision()
{
return getProduct().getUOMPrecision();
} // getUOMPrecision
/**************************************************************************
* String Representation
* @return info
|
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MDistributionRunLine[")
.append(get_ID()).append("-")
.append(getInfo())
.append ("]");
return sb.toString ();
} // toString
/**
* Get Info
* @return info
*/
public String getInfo()
{
StringBuffer sb = new StringBuffer ();
sb.append("Line=").append(getLine())
.append (",TotalQty=").append(getTotalQty())
.append(",SumMin=").append(getActualMin())
.append(",SumQty=").append(getActualQty())
.append(",SumAllocation=").append(getActualAllocation())
.append(",MaxAllocation=").append(getMaxAllocation())
.append(",LastDiff=").append(getLastDifference());
return sb.toString ();
} // getInfo
} // MDistributionRunLine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDistributionRunLine.java
| 1
|
请完成以下Java代码
|
public class BfsDataType {
@XmlAttribute(name = "code", required = true)
protected String code;
@XmlAttribute(name = "name", required = true)
protected String name;
/**
* Gets the value of the code property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the name property.
|
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BfsDataType.java
| 1
|
请完成以下Java代码
|
public void setC_Region_ID (int C_Region_ID)
{
if (C_Region_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Region_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Region_ID, Integer.valueOf(C_Region_ID));
}
/** Get Region.
@return Identifies a geographical Region
*/
@Override
public int getC_Region_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Region_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Standard.
@param IsDefault
Default value
*/
@Override
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Standard.
@return Default value
*/
@Override
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
|
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Region.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected ProcessDefinition findNewLatestProcessDefinitionAfterRemovalOf(ProcessDefinition processDefinitionToBeRemoved) {
// The latest process definition is not necessarily the one with 'version -1' (some versions could have been deleted)
// Hence, the following logic
ProcessDefinitionQueryImpl query = new ProcessDefinitionQueryImpl();
query.processDefinitionKey(processDefinitionToBeRemoved.getKey());
if (processDefinitionToBeRemoved.getTenantId() != null
&& !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinitionToBeRemoved.getTenantId())) {
query.processDefinitionTenantId(processDefinitionToBeRemoved.getTenantId());
} else {
query.processDefinitionWithoutTenantId();
}
if (processDefinitionToBeRemoved.getVersion() > 0) {
query.processDefinitionVersionLowerThan(processDefinitionToBeRemoved.getVersion());
}
|
query.orderByProcessDefinitionVersion().desc();
query.setFirstResult(0);
query.setMaxResults(1);
List<ProcessDefinition> processDefinitions = getProcessDefinitionEntityManager().findProcessDefinitionsByQueryCriteria(query);
if (processDefinitions != null && processDefinitions.size() > 0) {
return processDefinitions.get(0);
}
return null;
}
protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return engineConfiguration.getProcessDefinitionEntityManager();
}
protected FlowableEventDispatcher getEventDispatcher() {
return engineConfiguration.getEventDispatcher();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\repository\DeploymentProcessDefinitionDeletionManagerImpl.java
| 2
|
请完成以下Java代码
|
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request)
{
final PickingSlotQRCode pickingSlotQRCode = PickingSlotQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode());
return PickingMobileApplication.mapPickingJob(
request.getWfProcess(),
pickingJob -> pickingJobRestService.allocateAndSetPickingSlot(pickingJob, pickingSlotQRCode)
);
}
@Override
public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions(@NonNull GetScannedBarcodeSuggestionsRequest request)
{
final PickingJob pickingJob = getPickingJob(request.getWfProcess());
final PickingSlotSuggestions pickingSlotSuggestions = pickingJobRestService.getPickingSlotsSuggestions(pickingJob);
return toJson(pickingSlotSuggestions);
}
private static JsonScannedBarcodeSuggestions toJson(final PickingSlotSuggestions pickingSlotSuggestions)
{
if (pickingSlotSuggestions.isEmpty())
{
return JsonScannedBarcodeSuggestions.EMPTY;
}
|
return pickingSlotSuggestions.stream()
.map(SetPickingSlotWFActivityHandler::toJson)
.collect(JsonScannedBarcodeSuggestions.collect());
}
private static JsonScannedBarcodeSuggestion toJson(final PickingSlotSuggestion pickingSlotSuggestion)
{
return JsonScannedBarcodeSuggestion.builder()
.caption(pickingSlotSuggestion.getCaption())
.detail(pickingSlotSuggestion.getDeliveryAddress())
.qrCode(pickingSlotSuggestion.getQRCode().toGlobalQRCodeJsonString())
.property1("HU")
.value1(String.valueOf(pickingSlotSuggestion.getCountHUs()))
.additionalProperty("bpartnerLocationId", BPartnerLocationId.toRepoId(pickingSlotSuggestion.getDeliveryBPLocationId())) // for testing
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickingSlotWFActivityHandler.java
| 1
|
请完成以下Java代码
|
public DocumentFieldDescriptor.Builder getSpecialField_DocumentSummary()
{
return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocumentSummary();
}
@Nullable
public Map<Characteristic, DocumentFieldDescriptor.Builder> getSpecialField_DocSatusAndDocAction()
{
return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocStatusAndDocAction();
}
private WidgetTypeStandardNumberPrecision getStandardNumberPrecision()
{
WidgetTypeStandardNumberPrecision standardNumberPrecision = this._standardNumberPrecision;
if (standardNumberPrecision == null)
{
standardNumberPrecision = this._standardNumberPrecision = WidgetTypeStandardNumberPrecision.builder()
.quantityPrecision(getPrecisionFromSysConfigs(SYSCONFIG_QUANTITY_DEFAULT_PRECISION))
.build()
.fallbackTo(WidgetTypeStandardNumberPrecision.DEFAULT);
}
return standardNumberPrecision;
}
@SuppressWarnings("SameParameterValue")
|
private OptionalInt getPrecisionFromSysConfigs(@NonNull final String sysconfigName)
{
final int precision = sysConfigBL.getIntValue(sysconfigName, -1);
return precision > 0 ? OptionalInt.of(precision) : OptionalInt.empty();
}
private boolean isSkipField(@NonNull final String fieldName)
{
switch (fieldName)
{
case FIELDNAME_AD_Org_ID:
return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_ORG_ID_IS_DISPLAYED, true);
case FIELDNAME_AD_Client_ID:
return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_CLIENT_ID_IS_DISPLAYED, true);
default:
return false;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\GridTabVOBasedDocumentEntityDescriptorFactory.java
| 1
|
请完成以下Java代码
|
public class MigrationCreate extends JavaProcess
{
private I_AD_Migration migrationFrom;
private I_AD_Migration migrationTo;
private int tableId = 0;
private int recordId = 0;
private String entityId = null;
@Override
protected void prepare()
{
ProcessInfoParameter[] params = getParametersAsArray();
for (ProcessInfoParameter p : params)
{
String para = p.getParameterName();
if (para.equals("AD_Table_ID"))
tableId = p.getParameterAsInt();
else if (para.equals("Record_ID"))
recordId = p.getParameterAsInt();
else if (para.equals("EntityType"))
entityId = (String)p.getParameter();
}
if (tableId == 0)
tableId = getTable_ID();
if (recordId == 0)
recordId = getRecord_ID();
}
/**
*
* Process to create migration from selected records
*
|
* @author Paul Bowden, Adaxa Pty Ltd
*
*/
@Override
protected String doIt() throws Exception
{
I_AD_Migration migration = InterfaceWrapperHelper.create(getCtx(), I_AD_Migration.class, get_TrxName());
MTable table = MTable.get(getCtx(), tableId);
String whereClause;
List<PO> pos;
if (recordId > 0)
{
pos = new ArrayList<>(1);
pos.add(table.getPO(recordId, get_TrxName()));
}
else
{
String where = "EntityType = ?";
pos = table.createQuery(where, get_TrxName()).list(PO.class);
}
final MFSession session = Services.get(ISessionBL.class).getCurrentSession(getCtx());
final POInfo info = POInfo.getPOInfo(getCtx(), tableId, get_TrxName());
for (PO po : pos)
{
Services.get(IMigrationLogger.class).logMigration(session, po, info, X_AD_MigrationStep.ACTION_Insert);
}
return "@OK@";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationCreate.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8088
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
usern
|
ame: root
password: 123456
mybatis:
mapper-locations:
- classpath:mapper/**/*.xml
|
repos\springboot-demo-master\security\src\main\resources\application.yaml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
class ReactiveOAuth2ResourceServerOpaqueTokenConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(ReactiveOpaqueTokenIntrospector.class)
static class OpaqueTokenIntrospectionClientConfiguration {
@Bean
@ConditionalOnProperty(name = "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri")
SpringReactiveOpaqueTokenIntrospector opaqueTokenIntrospector(OAuth2ResourceServerProperties properties) {
OAuth2ResourceServerProperties.Opaquetoken opaquetoken = properties.getOpaquetoken();
String clientId = opaquetoken.getClientId();
Assert.state(clientId != null, "'clientId' must not be null");
String clientSecret = opaquetoken.getClientSecret();
Assert.state(clientSecret != null, "'clientSecret' must not be null");
return SpringReactiveOpaqueTokenIntrospector.withIntrospectionUri(opaquetoken.getIntrospectionUri())
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
|
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(SecurityWebFilterChain.class)
static class WebSecurityConfiguration {
@Bean
@ConditionalOnBean(ReactiveOpaqueTokenIntrospector.class)
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated());
http.oauth2ResourceServer((resourceServer) -> resourceServer.opaqueToken(withDefaults()));
return http.build();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\reactive\ReactiveOAuth2ResourceServerOpaqueTokenConfiguration.java
| 2
|
请完成以下Java代码
|
public void setRV_DATEV_Export_Fact_Acct_Invoice_ID (final int RV_DATEV_Export_Fact_Acct_Invoice_ID)
{
if (RV_DATEV_Export_Fact_Acct_Invoice_ID < 1)
set_ValueNoCheck (COLUMNNAME_RV_DATEV_Export_Fact_Acct_Invoice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_RV_DATEV_Export_Fact_Acct_Invoice_ID, RV_DATEV_Export_Fact_Acct_Invoice_ID);
}
@Override
public int getRV_DATEV_Export_Fact_Acct_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_RV_DATEV_Export_Fact_Acct_Invoice_ID);
}
@Override
public void setTaxAmtSource (final @Nullable BigDecimal TaxAmtSource)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtSource, TaxAmtSource);
}
@Override
public BigDecimal getTaxAmtSource()
{
|
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtSource);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATCode (final @Nullable java.lang.String VATCode)
{
set_ValueNoCheck (COLUMNNAME_VATCode, VATCode);
}
@Override
public java.lang.String getVATCode()
{
return get_ValueAsString(COLUMNNAME_VATCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_RV_DATEV_Export_Fact_Acct_Invoice.java
| 1
|
请完成以下Java代码
|
public void setDK_DesiredDeliveryTime_From (java.sql.Timestamp DK_DesiredDeliveryTime_From)
{
set_Value (COLUMNNAME_DK_DesiredDeliveryTime_From, DK_DesiredDeliveryTime_From);
}
/** Get Gewünschte Lieferuhrzeit von.
@return Gewünschte Lieferuhrzeit von */
@Override
public java.sql.Timestamp getDK_DesiredDeliveryTime_From ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_From);
}
/** Set Gewünschte Lieferuhrzeit bis.
@param DK_DesiredDeliveryTime_To Gewünschte Lieferuhrzeit bis */
@Override
public void setDK_DesiredDeliveryTime_To (java.sql.Timestamp DK_DesiredDeliveryTime_To)
{
set_Value (COLUMNNAME_DK_DesiredDeliveryTime_To, DK_DesiredDeliveryTime_To);
}
/** Get Gewünschte Lieferuhrzeit bis.
@return Gewünschte Lieferuhrzeit bis */
@Override
public java.sql.Timestamp getDK_DesiredDeliveryTime_To ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DK_DesiredDeliveryTime_To);
}
/** Set EMail Empfänger.
@param EMail_To
EMail address to send requests to - e.g. edi@manufacturer.com
*/
@Override
public void setEMail_To (java.lang.String EMail_To)
{
set_Value (COLUMNNAME_EMail_To, EMail_To);
}
/** Get EMail Empfänger.
@return EMail address to send requests to - e.g. edi@manufacturer.com
*/
@Override
public java.lang.String getEMail_To ()
{
return (java.lang.String)get_Value(COLUMNNAME_EMail_To);
|
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_Shipper_Config.java
| 1
|
请完成以下Java代码
|
public void set(int index, Short value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Integer value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Long value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Double value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, BigDecimal value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, BigInteger value) {
jsonNode.set(index, value);
}
@Override
public void setNull(int index) {
jsonNode.setNull(index);
}
@Override
public void set(int index, FlowableJsonNode value) {
jsonNode.set(index, asJsonNode(value));
}
@Override
public void add(Short value) {
jsonNode.add(value);
}
@Override
public void add(Integer value) {
jsonNode.add(value);
}
@Override
public void add(Long value) {
jsonNode.add(value);
}
@Override
public void add(Float value) {
jsonNode.add(value);
}
@Override
public void add(Double value) {
jsonNode.add(value);
|
}
@Override
public void add(byte[] value) {
jsonNode.add(value);
}
@Override
public void add(String value) {
jsonNode.add(value);
}
@Override
public void add(Boolean value) {
jsonNode.add(value);
}
@Override
public void add(BigDecimal value) {
jsonNode.add(value);
}
@Override
public void add(BigInteger value) {
jsonNode.add(value);
}
@Override
public void add(FlowableJsonNode value) {
jsonNode.add(asJsonNode(value));
}
@Override
public void addNull() {
jsonNode.addNull();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ArrayNode.java
| 1
|
请完成以下Java代码
|
public boolean accept(File pathname)
{
return pathname.isFile() && !pathname.getName().endsWith(".bin");
}
});
if (files == null)
{
if (rootFile.isFile())
files = new File[]{rootFile};
else return;
}
}
else
{
files = new File[]{rootFile};
}
int n = 0;
int totalAddress = 0;
long start = System.currentTimeMillis();
for (File file : files)
{
if (size-- == 0) break;
if (file.isDirectory()) continue;
if (verbose) System.out.printf("正在处理%s, %d / %d\n", file.getName(), ++n, files.length);
IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(file.getAbsolutePath());
while (lineIterator.hasNext())
{
++totalAddress;
String line = lineIterator.next();
if (line.length() == 0) continue;
handler.handle(line);
}
|
}
handler.done();
if (verbose) System.out.printf("处理了 %.2f 万行,花费了 %.2f min\n", totalAddress / 10000.0, (System.currentTimeMillis() - start) / 1000.0 / 60.0);
}
/**
* 读取
* @param handler 处理逻辑
* @throws Exception
*/
public void read(LineHandler handler) throws Exception
{
read(handler, Integer.MAX_VALUE);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\EasyReader.java
| 1
|
请完成以下Java代码
|
private void send(EMail email)
{
int maxRetries = p_SMTPRetriesNo > 0 ? p_SMTPRetriesNo : 0;
int count = 0;
do
{
final EMailSentStatus emailSentStatus = email.send();
count++;
if (emailSentStatus.isSentOK())
{
return;
}
// Timeout => retry
if (emailSentStatus.isSentConnectionError() && count < maxRetries)
{
log.warn("SMTP error: {} [ Retry {}/{} ]", emailSentStatus, count, maxRetries);
|
}
else
{
throw new EMailSendException(emailSentStatus);
}
}
while (true);
}
private void setNotified(I_M_PackageLine packageLine)
{
InterfaceWrapperHelper.getPO(packageLine).set_ValueOfColumn("IsSentMailNotification", true);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\validator\ShipperTransportationMailNotification.java
| 1
|
请完成以下Java代码
|
public DataObject getDataObject(String taskId, String dataObject) {
return commandExecutor.execute(new GetTaskDataObjectCmd(taskId, dataObject));
}
@Override
public DataObject getDataObject(String taskId, String dataObjectName, String locale, boolean withLocalizationFallback) {
return commandExecutor.execute(new GetTaskDataObjectCmd(taskId, dataObjectName, locale, withLocalizationFallback));
}
@Override
public TaskBuilder createTaskBuilder() {
return new TaskBuilderImpl(commandExecutor);
}
protected IdmIdentityService getIdmIdentityService() {
|
IdmEngineConfigurationApi idmEngineConfiguration = (IdmEngineConfigurationApi) configuration.getEngineConfigurations()
.get(EngineConfigurationConstants.KEY_IDM_ENGINE_CONFIG);
IdmIdentityService idmIdentityService = null;
if (idmEngineConfiguration != null) {
idmIdentityService = idmEngineConfiguration.getIdmIdentityService();
}
return idmIdentityService;
}
@Override
public TaskCompletionBuilder createTaskCompletionBuilder() {
return new TaskCompletionBuilderImpl(commandExecutor);
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\TaskServiceImpl.java
| 1
|
请完成以下Java代码
|
public static XForwardedRemoteAddressResolver trustAll() {
return new XForwardedRemoteAddressResolver(Integer.MAX_VALUE);
}
/**
* <em>trusted</em> IP address found in the X-Forwarded-For header (when present).
* This configuration exists to prevent a malicious actor from spoofing the value of
* the X-Forwarded-For header. If you know that your gateway application is only
* accessible from a a trusted load balancer, then you can trust that the load
* balancer will append a valid client IP address to the X-Forwarded-For header, and
* should use a value of `1` for the `maxTrustedIndex`.
*
*
* Given the X-Forwarded-For value of [0.0.0.1, 0.0.0.2, 0.0.0.3]:
*
* <pre>
* maxTrustedIndex -> result
*
* [MIN_VALUE,0] -> IllegalArgumentException
* 1 -> 0.0.0.3
* 2 -> 0.0.0.2
* 3 -> 0.0.0.1
* [4, MAX_VALUE] -> 0.0.0.1
* </pre>
* @param maxTrustedIndex correlates to the number of trusted proxies expected in
* front of Spring Cloud Gateway (index starts at 1).
* @return a {@link XForwardedRemoteAddressResolver} which extracts the last
*/
public static XForwardedRemoteAddressResolver maxTrustedIndex(int maxTrustedIndex) {
Assert.isTrue(maxTrustedIndex > 0, "An index greater than 0 is required");
return new XForwardedRemoteAddressResolver(maxTrustedIndex);
}
/**
* The X-Forwarded-For header contains a comma separated list of IP addresses. This
* method parses those IP addresses into a list. If no X-Forwarded-For header is
* found, an empty list is returned. If multiple X-Forwarded-For headers are found, an
* empty list is returned out of caution.
|
* @return The parsed values of the X-Forwarded-Header.
*/
@Override
public InetSocketAddress resolve(ServerWebExchange exchange) {
List<String> xForwardedValues = extractXForwardedValues(exchange);
if (!xForwardedValues.isEmpty()) {
int index = Math.max(0, xForwardedValues.size() - maxTrustedIndex);
return new InetSocketAddress(xForwardedValues.get(index), 0);
}
return defaultRemoteIpResolver.resolve(exchange);
}
private List<String> extractXForwardedValues(ServerWebExchange exchange) {
List<String> xForwardedValues = exchange.getRequest().getHeaders().get(X_FORWARDED_FOR);
if (xForwardedValues == null || xForwardedValues.isEmpty()) {
return Collections.emptyList();
}
if (xForwardedValues.size() > 1) {
log.warn("Multiple X-Forwarded-For headers found, discarding all");
return Collections.emptyList();
}
String[] values = StringUtils.tokenizeToStringArray(xForwardedValues.get(0), ",");
if (values.length == 1 && !StringUtils.hasText(values[0])) {
return Collections.emptyList();
}
return Arrays.asList(values);
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ipresolver\XForwardedRemoteAddressResolver.java
| 1
|
请完成以下Java代码
|
public boolean isLiteralText() {
return false;
}
@Override
public String getExpressionString() {
return null;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
return obj == this;
}
@Override
public Object invoke(ELContext context, Object[] params) {
try {
return method.invoke(null, params);
} catch (IllegalAccessException e) {
throw new ELException(LocalMessages.get("error.identifier.method.access", name));
} catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e));
} catch (InvocationTargetException e) {
throw new ELException(
LocalMessages.get("error.identifier.method.invocation", name, e.getCause())
);
}
}
@Override
public MethodInfo getMethodInfo(ELContext context) {
return new MethodInfo(method.getName(), method.getReturnType(), method.getParameterTypes());
}
};
} else if (value instanceof MethodExpression) {
return (MethodExpression) value;
}
throw new MethodNotFoundException(
LocalMessages.get("error.identifier.method.notamethod", name, value.getClass())
);
}
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return getMethodExpression(bindings, context, returnType, paramTypes).getMethodInfo(context);
}
public Object invoke(
Bindings bindings,
ELContext context,
Class<?> returnType,
|
Class<?>[] paramTypes,
Object[] params
) {
return getMethodExpression(bindings, context, returnType, paramTypes).invoke(context, params);
}
@Override
public String toString() {
return name;
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name);
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public int getCardinality() {
return 0;
}
public AstNode getChild(int i) {
return null;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstIdentifier.java
| 1
|
请完成以下Java代码
|
public long getCreatedTime() {
return super.getCreatedTime();
}
@Override
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getName() {
return title;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getLink() {
String scope = (tenantId != null && tenantId.isSysTenantId()) ? "system" : "tenant"; // tenantId is null in case of export to git
if (resourceType == ResourceType.IMAGE) {
return "/api/images/" + scope + "/" + resourceKey;
} else {
return "/api/resource/" + resourceType.name().toLowerCase() + "/" + scope + "/" + resourceKey;
}
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getPublicLink() {
if (resourceType == ResourceType.IMAGE && isPublic) {
return "/api/images/public/" + getPublicResourceKey();
}
return null;
}
@JsonIgnore
|
public String getSearchText() {
return title;
}
@SneakyThrows
public <T> T getDescriptor(Class<T> type) {
return descriptor != null ? mapper.treeToValue(descriptor, type) : null;
}
public <T> void updateDescriptor(Class<T> type, UnaryOperator<T> updater) {
T descriptor = getDescriptor(type);
descriptor = updater.apply(descriptor);
setDescriptorValue(descriptor);
}
@JsonIgnore
public void setDescriptorValue(Object value) {
this.descriptor = value != null ? mapper.valueToTree(value) : null;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\TbResourceInfo.java
| 1
|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Use_ID()));
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set UseDate.
@param UseDate UseDate */
public void setUseDate (Timestamp UseDate)
{
set_Value (COLUMNNAME_UseDate, UseDate);
}
|
/** Get UseDate.
@return UseDate */
public Timestamp getUseDate ()
{
return (Timestamp)get_Value(COLUMNNAME_UseDate);
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
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_A_Asset_Use.java
| 1
|
请完成以下Java代码
|
public void setTotalTaxBaseAmt (final @Nullable BigDecimal TotalTaxBaseAmt)
{
set_Value (COLUMNNAME_TotalTaxBaseAmt, TotalTaxBaseAmt);
}
@Override
public BigDecimal getTotalTaxBaseAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalTaxBaseAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVat (final @Nullable BigDecimal TotalVat)
{
set_Value (COLUMNNAME_TotalVat, TotalVat);
}
@Override
public BigDecimal getTotalVat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalVatWithSurchargeAmt (final BigDecimal TotalVatWithSurchargeAmt)
{
set_ValueNoCheck (COLUMNNAME_TotalVatWithSurchargeAmt, TotalVatWithSurchargeAmt);
}
@Override
public BigDecimal getTotalVatWithSurchargeAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalVatWithSurchargeAmt);
|
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_v.java
| 1
|
请完成以下Java代码
|
public OrderId retrieveOriginalContractOrder(@NonNull final OrderId orderId)
{
OrderId ancestor = retrieveLinkedFollowUpContractOrder(orderId);
if (ancestor != null)
{
final OrderId nextAncestor = retrieveOriginalContractOrder(ancestor);
if (nextAncestor != null)
{
ancestor = nextAncestor;
}
}
return orderId;
}
/**
* Builds up a list of contract orders based on column <code>I_C_Order.COLUMNNAME_Ref_FollowupOrder_ID</code>.
*/
private void buildAllContractOrderList(@NonNull final OrderId orderId, @NonNull final Set<OrderId> contractOrderIds)
{
final I_C_Order order = InterfaceWrapperHelper.load(orderId, I_C_Order.class);
final OrderId nextAncestorId = OrderId.ofRepoIdOrNull(order.getRef_FollowupOrder_ID());
if (nextAncestorId != null)
{
contractOrderIds.add(nextAncestorId);
buildAllContractOrderList(nextAncestorId, contractOrderIds);
}
}
public I_C_Flatrate_Term retrieveTopExtendedTerm(@NonNull final I_C_Flatrate_Term term)
{
I_C_Flatrate_Term nextTerm = term.getC_FlatrateTerm_Next();
if (nextTerm != null)
{
nextTerm = retrieveTopExtendedTerm(nextTerm);
}
return nextTerm == null ? term : nextTerm;
}
|
@Nullable
public OrderId getContractOrderId(@NonNull final I_C_Flatrate_Term term)
{
if (term.getC_OrderLine_Term_ID() <= 0)
{
return null;
}
final IOrderDAO orderRepo = Services.get(IOrderDAO.class);
final de.metas.interfaces.I_C_OrderLine ol = orderRepo.getOrderLineById(term.getC_OrderLine_Term_ID());
if (ol == null)
{
return null;
}
return OrderId.ofRepoId(ol.getC_Order_ID());
}
public boolean isContractSalesOrder(@NonNull final OrderId orderId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_OrderLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId)
.addNotNull(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID)
.create()
.anyMatch();
}
public void save(@NonNull final I_C_Order order)
{
InterfaceWrapperHelper.save(order);
}
public void setOrderContractStatusAndSave(@NonNull final I_C_Order order, @NonNull final String contractStatus)
{
order.setContractStatus(contractStatus);
save(order);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\ContractOrderService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addAfter(relativePropertySourceName, original);
}
}
/**
* <p>replace.</p>
*
* @param name a {@link java.lang.String} object
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void replace(String name, PropertySource<?> propertySource) {
if(isAllowed(propertySource)) {
if(copy.getPropertySources().contains(name)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().replace(name, original);
}
}
}
/**
|
* <p>remove.</p>
*
* @param name a {@link java.lang.String} object
* @return a {@link org.springframework.core.env.PropertySource} object
*/
public PropertySource<?> remove(String name) {
return copy.getPropertySources().remove(name);
}
/**
* <p>get.</p>
*
* @return a {@link org.springframework.core.env.ConfigurableEnvironment} object
*/
public ConfigurableEnvironment get() {
return copy;
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\configuration\EnvCopy.java
| 2
|
请完成以下Java代码
|
public static void vavrParallelStreamAccess() {
System.out.println("Vavr Stream Concurrent Modification");
System.out.println("====================================");
Stream<Integer> vavrStream = Stream.ofAll(intList);
// intList.add(5);
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
// Stream<Integer> wrapped = Stream.ofAll(intArray);
// intArray[2] = 5;
// wrapped.forEach(i -> System.out.println("Vavr looped " + i));
}
public static void jdkFlatMapping() {
System.out.println("Java flatMapping");
System.out.println("====================================");
java.util.stream.Stream.of(42).flatMap(i -> java.util.stream.Stream.generate(() -> {
System.out.println("nested call");
return 42;
})).findAny();
}
public static void vavrFlatMapping() {
System.out.println("Vavr flatMapping");
System.out.println("====================================");
Stream.of(42)
.flatMap(i -> Stream.continually(() -> {
System.out.println("nested call");
return 42;
}))
.get(0);
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
|
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
}
|
repos\tutorials-master\vavr-modules\vavr\src\main\java\com\baeldung\samples\java\vavr\VavrSampler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private boolean extractGenericZoomOrigin(
@NonNull final String tableName,
@Nullable final String keyColumnName)
{
if (keyColumnName != null)
{
final IADTableDAO adTableDAO = Services.get(IADTableDAO.class);
return adTableDAO.getMinimalColumnInfo(tableName, keyColumnName).isGenericZoomOrigin();
}
return false;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("tableName", tableName)
.add("recordId", recordId)
.add("AD_Window_ID", adWindowId)
.toString();
}
@Override
public Properties getCtx()
{
return ctx;
}
@Override
public String getTrxName()
{
return ITrx.TRXNAME_ThreadInherited;
}
@Override
public AdWindowId getAD_Window_ID()
{
return adWindowId;
}
@Override
public int getAD_Table_ID()
{
return adTableId;
|
}
@Override
public String getKeyColumnNameOrNull()
{
return keyColumnName;
}
@Override
public int getRecord_ID()
{
return recordId;
}
@Override
public boolean isSingleKeyRecord()
{
return keyColumnName != null;
}
@Override
public Evaluatee createEvaluationContext()
{
return evaluationContext;
}
@Override
public boolean hasField(final String columnName)
{
return document.hasField(columnName);
}
@Override
public Object getFieldValue(final String columnName)
{
return document.getFieldView(columnName).getValue();
}
@Override
public boolean getFieldValueAsBoolean(final String columnName)
{
return document.getFieldView(columnName).getValueAsBoolean();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\service\WebuiDocumentReferencesService.java
| 2
|
请完成以下Java代码
|
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public String getImplementationType() {
return implementationTypeAttribute.getValue(this);
}
public void setImplementationType(String implementationType) {
implementationTypeAttribute.setValue(this, implementationType);
}
public Collection<InputDecisionParameter> getInputs() {
return inputCollection.get(this);
}
public Collection<OutputDecisionParameter> getOutputs() {
return outputCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Decision.class, CMMN_ELEMENT_DECISION)
.extendsType(CmmnElement.class)
|
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Decision>() {
public Decision newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
implementationTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPLEMENTATION_TYPE)
.defaultValue("http://www.omg.org/spec/CMMN/DecisionType/Unspecified")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputCollection = sequenceBuilder.elementCollection(InputDecisionParameter.class)
.build();
outputCollection = sequenceBuilder.elementCollection(OutputDecisionParameter.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionImpl.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (email == null ? 0 : email.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 User user = (User) obj;
if (!email.equals(user.email)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [id=").append(id).append(", username=").append(username).append(", email=").append(email).append(", roles=").append(roles).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\model\User.java
| 1
|
请完成以下Java代码
|
public static PrivilegeEntityManager getPrivilegeEntityManager() {
return getPrivilegeEntityManager(getCommandContext());
}
public static PrivilegeEntityManager getPrivilegeEntityManager(CommandContext commandContext) {
return getIdmEngineConfiguration(commandContext).getPrivilegeEntityManager();
}
public static PrivilegeMappingEntityManager getPrivilegeMappingEntityManager() {
return getPrivilegeMappingEntityManager(getCommandContext());
}
public static PrivilegeMappingEntityManager getPrivilegeMappingEntityManager(CommandContext commandContext) {
return getIdmEngineConfiguration(commandContext).getPrivilegeMappingEntityManager();
}
public static TokenEntityManager getTokenEntityManager() {
return getTokenEntityManager(getCommandContext());
}
|
public static TokenEntityManager getTokenEntityManager(CommandContext commandContext) {
return getIdmEngineConfiguration(commandContext).getTokenEntityManager();
}
public static IdentityInfoEntityManager getIdentityInfoEntityManager() {
return getIdentityInfoEntityManager(getCommandContext());
}
public static IdentityInfoEntityManager getIdentityInfoEntityManager(CommandContext commandContext) {
return getIdmEngineConfiguration(commandContext).getIdentityInfoEntityManager();
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\util\CommandContextUtil.java
| 1
|
请完成以下Java代码
|
public TableColumnResource getResource()
{
return resource;
}
public final Builder asNewBuilder()
{
return builder()
.setFrom(this);
}
@Override
public int hashCode()
{
if (hashcode == 0)
{
hashcode = new HashcodeBuilder()
.append(31) // seed
.append(resource)
.append(accesses)
.toHashcode();
}
return hashcode;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
final TableColumnPermission other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(resource, other.resource)
.append(accesses, other.accesses)
.isEqual();
}
@Override
public String toString()
{
return getClass().getSimpleName() + "["
+ resource
+ ", " + accesses
+ "]";
}
@Override
public boolean hasAccess(final Access access)
{
return accesses.contains(access);
}
@Override
public Permission mergeWith(final Permission permissionFrom)
{
final TableColumnPermission columnPermissionFrom = checkCompatibleAndCast(permissionFrom);
return asNewBuilder()
.addAccesses(columnPermissionFrom.accesses)
.build();
}
public int getAD_Table_ID()
{
return resource.getAD_Table_ID();
}
public int getAD_Column_ID()
{
return resource.getAD_Column_ID();
}
public static class Builder
{
private TableColumnResource resource;
private final Set<Access> accesses = new LinkedHashSet<>();
public TableColumnPermission build()
|
{
return new TableColumnPermission(this);
}
public Builder setFrom(final TableColumnPermission columnPermission)
{
setResource(columnPermission.getResource());
setAccesses(columnPermission.accesses);
return this;
}
public Builder setResource(final TableColumnResource resource)
{
this.resource = resource;
return this;
}
public final Builder addAccess(final Access access)
{
accesses.add(access);
return this;
}
public final Builder removeAccess(final Access access)
{
accesses.remove(access);
return this;
}
public final Builder setAccesses(final Set<Access> acceses)
{
accesses.clear();
accesses.addAll(acceses);
return this;
}
public final Builder addAccesses(final Set<Access> acceses)
{
accesses.addAll(acceses);
return this;
}
public final Builder removeAllAccesses()
{
accesses.clear();
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermission.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<I_AD_InfoColumn> retrieveQueryColumns(final I_AD_InfoWindow infoWindow)
{
final List<I_AD_InfoColumn> list = new ArrayList<I_AD_InfoColumn>();
for (final I_AD_InfoColumn infoColumn : retrieveInfoColumns(infoWindow))
{
if (!infoColumn.isActive())
{
continue;
}
if (!infoColumn.isQueryCriteria())
{
continue;
}
list.add(infoColumn);
}
Collections.sort(list, new Comparator<I_AD_InfoColumn>()
{
@Override
public int compare(final I_AD_InfoColumn o1, final I_AD_InfoColumn o2)
{
return o1.getParameterSeqNo() - o2.getParameterSeqNo();
}
});
return list;
}
@Override
public List<I_AD_InfoColumn> retrieveDisplayedColumns(final I_AD_InfoWindow infoWindow)
{
final List<I_AD_InfoColumn> list = new ArrayList<I_AD_InfoColumn>();
for (final I_AD_InfoColumn infoColumn : retrieveInfoColumns(infoWindow))
{
if (!infoColumn.isActive())
{
continue;
}
if (!infoColumn.isDisplayed())
{
continue;
}
list.add(infoColumn);
}
Collections.sort(list, new Comparator<I_AD_InfoColumn>()
|
{
@Override
public int compare(final I_AD_InfoColumn o1, final I_AD_InfoColumn o2)
{
return o1.getSeqNo() - o2.getSeqNo();
}
});
return list;
}
@Override
@Cached(cacheName = I_AD_InfoWindow.Table_Name + "#by#" + I_AD_InfoWindow.COLUMNNAME_ShowInMenu)
public List<I_AD_InfoWindow> retrieveInfoWindowsInMenu(@CacheCtx final Properties ctx)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_InfoWindow.class, ctx, ITrx.TRXNAME_None)
.addCompareFilter(I_AD_InfoWindow.COLUMNNAME_AD_InfoWindow_ID, CompareQueryFilter.Operator.NOT_EQUAL, 540008) // FIXME: hardcoded "Info Partner"
.addCompareFilter(I_AD_InfoWindow.COLUMNNAME_AD_InfoWindow_ID, CompareQueryFilter.Operator.NOT_EQUAL, 540009) // FIXME: hardcoded "Info Product"
.addEqualsFilter(I_AD_InfoWindow.COLUMNNAME_IsActive, true)
.addEqualsFilter(I_AD_InfoWindow.COLUMNNAME_ShowInMenu, true)
.addOnlyContextClientOrSystem()
//
.orderBy()
.addColumn(I_AD_InfoWindow.COLUMNNAME_AD_InfoWindow_ID)
.endOrderBy()
//
.create()
.list(I_AD_InfoWindow.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\ADInfoWindowDAO.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getCategory() {
return category;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getEngineVersion() {
return engineVersion;
}
public String getDerivedFrom() {
return derivedFrom;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
|
}
public String getProcessDefinitionKeyLike() {
return processDefinitionKeyLike;
}
public String getCategoryLike() {
return categoryLike;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getParentDeploymentIdLike() {
return parentDeploymentIdLike;
}
public List<String> getParentDeploymentIds() {
return parentDeploymentIds;
}
public boolean isLatest() {
return latest;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DeploymentQueryImpl.java
| 1
|
请完成以下Java代码
|
public String getNewState() {
return PlanItemInstanceState.COMPLETED;
}
@Override
public String getLifeCycleTransition() {
return PlanItemTransition.COMPLETE;
}
@Override
public boolean isEvaluateRepetitionRule() {
return true;
}
@Override
protected boolean shouldAggregateForSingleInstance() {
return true;
}
@Override
protected boolean shouldAggregateForMultipleInstances() {
return true;
}
@Override
protected void internalExecute() {
if (isStage(planItemInstanceEntity)) {
// terminate any remaining child plan items (e.g. in enabled / available state), but don't complete them as it might lead
// into wrong behavior resulting from it (e.g. triggering some follow-up actions on that completion event) and it will leave
// such implicitly completed plan items in complete state, although they were never explicitly completed
exitChildPlanItemInstances(PlanItemTransition.COMPLETE, null, null);
// create stage ended with completion state event
FlowableEventDispatcher eventDispatcher = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableCmmnEventBuilder.createStageEndedEvent(getCaseInstance(), planItemInstanceEntity,
|
FlowableCaseStageEndedEvent.ENDING_STATE_COMPLETED), EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG);
}
}
planItemInstanceEntity.setEndedTime(getCurrentTime(commandContext));
planItemInstanceEntity.setCompletedTime(planItemInstanceEntity.getEndedTime());
CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceCompleted(planItemInstanceEntity);
}
@Override
protected Map<String, String> getAsyncLeaveTransitionMetadata() {
Map<String, String> metadata = new HashMap<>();
metadata.put(OperationSerializationMetadata.FIELD_PLAN_ITEM_INSTANCE_ID, planItemInstanceEntity.getId());
return metadata;
}
@Override
public String getOperationName() {
return "[Complete plan item]";
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\CompletePlanItemInstanceOperation.java
| 1
|
请完成以下Java代码
|
public class OutgoingProducer {
private static final String TOPIC_NAME = "outgoing-topic";
private final KafkaTemplate<String, OutgoingPayloadDto> kafkaTemplate;
@AsyncPublisher(
operation = @AsyncOperation(
channelName = TOPIC_NAME,
description = "More details for the outgoing topic",
headers = @AsyncOperation.Headers(
schemaName = "SpringKafkaDefaultHeadersOutgoingPayloadDto",
values = {
// this header is generated by Spring by default
@AsyncOperation.Headers.Header(
name = DEFAULT_CLASSID_FIELD_NAME,
|
description = "Spring Type Id Header",
value = "com.baeldung.boot.documentation.springwolf.dto.OutgoingPayloadDto"
),
}
)
)
)
@KafkaAsyncOperationBinding
public void publish(OutgoingPayloadDto payload) {
log.info("Publishing new message: {}", payload.toString());
kafkaTemplate.send(TOPIC_NAME, payload);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-documentation\src\main\java\com\baeldung\boot\documentation\springwolf\adapter\outgoing\OutgoingProducer.java
| 1
|
请完成以下Java代码
|
public class WriteExampleBean extends CsvBean {
private String colA;
private String colB;
private String colC;
public WriteExampleBean(String colA, String colB, String colC) {
this.colA = colA;
this.colB = colB;
this.colC = colC;
}
public String getColA() {
return colA;
}
public void setColA(String colA) {
this.colA = colA;
}
|
public String getColB() {
return colB;
}
public void setColB(String colB) {
this.colB = colB;
}
public String getColC() {
return colC;
}
public void setColC(String colC) {
this.colC = colC;
}
@Override
public String toString() {
return colA + ',' + colB + "," + colC;
}
}
|
repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\beans\WriteExampleBean.java
| 1
|
请完成以下Java代码
|
private class Cleaner implements Runnable {
@Override
public void run() {
try {
Collection<Registration> allRegs = new ArrayList<>();
try {
lock.readLock().lock();
allRegs.addAll(regsByEp.values());
} finally {
lock.readLock().unlock();
}
for (Registration reg : allRegs) {
if (!reg.isAlive()) {
// force de-registration
Deregistration removedRegistration = removeRegistration(reg.getId());
expirationListener.registrationExpired(removedRegistration.getRegistration(),
removedRegistration.getObservations());
}
|
}
} catch (Exception e) {
log.warn("Unexpected Exception while registration cleaning", e);
}
}
}
// boolean remove(Object key, Object value) exist only since java8
// So this method is here only while we want to support java 7
protected <K, V> boolean removeFromMap(Map<K, V> map, K key, V value) {
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbInMemoryRegistrationStore.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
SpringApplication app = new SpringApplication(BookstoreApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
|
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\BookstoreApp.java
| 1
|
请完成以下Java代码
|
public PublicKeyCredentialRequestOptionsBuilder timeout(Duration timeout) {
Assert.notNull(timeout, "timeout cannot be null");
this.timeout = timeout;
return this;
}
/**
* Sets the {@link #getRpId()} property.
* @param rpId the rpId property
* @return the {@link PublicKeyCredentialRequestOptionsBuilder}
*/
public PublicKeyCredentialRequestOptionsBuilder rpId(String rpId) {
this.rpId = rpId;
return this;
}
/**
* Sets the {@link #getAllowCredentials()} property
* @param allowCredentials the allowed credentials
* @return the {@link PublicKeyCredentialRequestOptionsBuilder}
*/
public PublicKeyCredentialRequestOptionsBuilder allowCredentials(
List<PublicKeyCredentialDescriptor> allowCredentials) {
Assert.notNull(allowCredentials, "allowCredentials cannot be null");
this.allowCredentials = allowCredentials;
return this;
}
/**
* Sets the {@link #getUserVerification()} property.
* @param userVerification the user verification
* @return the {@link PublicKeyCredentialRequestOptionsBuilder}
*/
public PublicKeyCredentialRequestOptionsBuilder userVerification(UserVerificationRequirement userVerification) {
this.userVerification = userVerification;
return this;
}
/**
* Sets the {@link #getExtensions()} property
* @param extensions the extensions
* @return the {@link PublicKeyCredentialRequestOptionsBuilder}
*/
public PublicKeyCredentialRequestOptionsBuilder extensions(AuthenticationExtensionsClientInputs extensions) {
this.extensions = extensions;
return this;
}
|
/**
* Allows customizing the {@link PublicKeyCredentialRequestOptionsBuilder}
* @param customizer the {@link Consumer} used to customize the builder
* @return the {@link PublicKeyCredentialRequestOptionsBuilder}
*/
public PublicKeyCredentialRequestOptionsBuilder customize(
Consumer<PublicKeyCredentialRequestOptionsBuilder> customizer) {
customizer.accept(this);
return this;
}
/**
* Builds a new {@link PublicKeyCredentialRequestOptions}
* @return a new {@link PublicKeyCredentialRequestOptions}
*/
public PublicKeyCredentialRequestOptions build() {
if (this.challenge == null) {
this.challenge = Bytes.random();
}
return new PublicKeyCredentialRequestOptions(this.challenge, this.timeout, this.rpId, this.allowCredentials,
this.userVerification, this.extensions);
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialRequestOptions.java
| 1
|
请完成以下Java代码
|
public class FilterManager extends AbstractManager {
public Filter createNewFilter(String resourceType) {
checkAuthorization(CREATE, FILTER, ANY);
return new FilterEntity(resourceType);
}
public Filter insertOrUpdateFilter(Filter filter) {
AbstractQuery<?, ?> query = filter.getQuery();
query.validate(StoredQueryValidator.get());
if (filter.getId() == null) {
checkAuthorization(CREATE, FILTER, ANY);
getDbEntityManager().insert((FilterEntity) filter);
createDefaultAuthorizations(filter);
}
else {
checkAuthorization(UPDATE, FILTER, filter.getId());
getDbEntityManager().merge((FilterEntity) filter);
}
return filter;
}
public void deleteFilter(String filterId) {
checkAuthorization(DELETE, FILTER, filterId);
FilterEntity filter = findFilterByIdInternal(filterId);
ensureNotNull("No filter found for filter id '" + filterId + "'", "filter", filter);
// delete all authorizations for this filter id
deleteAuthorizations(FILTER, filterId);
// delete the filter itself
getDbEntityManager().delete(filter);
}
|
public FilterEntity findFilterById(String filterId) {
ensureNotNull("Invalid filter id", "filterId", filterId);
checkAuthorization(READ, FILTER, filterId);
return findFilterByIdInternal(filterId);
}
protected FilterEntity findFilterByIdInternal(String filterId) {
return getDbEntityManager().selectById(FilterEntity.class, filterId);
}
@SuppressWarnings("unchecked")
public List<Filter> findFiltersByQueryCriteria(FilterQueryImpl filterQuery) {
configureQuery(filterQuery, FILTER);
return getDbEntityManager().selectList("selectFilterByQueryCriteria", filterQuery);
}
public long findFilterCountByQueryCriteria(FilterQueryImpl filterQuery) {
configureQuery(filterQuery, FILTER);
return (Long) getDbEntityManager().selectOne("selectFilterCountByQueryCriteria", filterQuery);
}
// authorization utils /////////////////////////////////
protected void createDefaultAuthorizations(Filter filter) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newFilter(filter));
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\FilterManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CreditPassTransactionData implements TransactionData
{
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private String gender;
private String streetFull;
private String zip;
private String city;
private String country;
|
private String bankRoutingCode;
private String accountNr;
private String iban;
private String creditCardNr;
private String creditCardType;
private String email;
private String phoneNr;
private String companyName;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\model\CreditPassTransactionData.java
| 2
|
请完成以下Java代码
|
protected HistoryManager getHistoryManager() {
return getProcessEngineConfiguration().getHistoryManager();
}
protected DeploymentEntityManager getDeploymentEntityManager() {
return getProcessEngineConfiguration().getDeploymentEntityManager();
}
protected ResourceEntityManager getResourceEntityManager() {
return getProcessEngineConfiguration().getResourceEntityManager();
}
protected ByteArrayEntityManager getByteArrayEntityManager() {
return getProcessEngineConfiguration().getByteArrayEntityManager();
}
protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionEntityManager();
}
protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionInfoEntityManager();
}
protected ModelEntityManager getModelEntityManager() {
return getProcessEngineConfiguration().getModelEntityManager();
}
protected ExecutionEntityManager getExecutionEntityManager() {
return getProcessEngineConfiguration().getExecutionEntityManager();
}
protected ActivityInstanceEntityManager getActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getActivityInstanceEntityManager();
|
}
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_K_Source[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description URL.
@param DescriptionURL
URL for the description
*/
public void setDescriptionURL (String DescriptionURL)
{
set_Value (COLUMNNAME_DescriptionURL, DescriptionURL);
}
/** Get Description URL.
@return URL for the description
*/
public String getDescriptionURL ()
{
return (String)get_Value(COLUMNNAME_DescriptionURL);
}
/** Set Knowledge Source.
@param K_Source_ID
Source of a Knowledge Entry
*/
public void setK_Source_ID (int K_Source_ID)
{
if (K_Source_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Source_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Source_ID, Integer.valueOf(K_Source_ID));
}
/** Get Knowledge Source.
@return Source of a Knowledge Entry
*/
|
public int getK_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Source_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());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Source.java
| 1
|
请完成以下Java代码
|
public void registerHandler(IIterateResultHandler handler)
{
handlerSupport.registerListener(handler);
}
@Override
public List<IIterateResultHandler> getRegisteredHandlers()
{
return handlerSupport.getRegisteredHandlers();
}
@Override
public boolean isHandlerSignaledToStop()
{
return handlerSupport.isHandlerSignaledToStop();
|
}
@Override
public String toString()
{
return "IterateResult [queueItemsToProcess.size()=" + queueItemsToProcess.size()
+ ", queueItemsToDelete.size()=" + queueItemsToDelete.size()
+ ", size=" + size
+ ", tableName2Record.size()=" + tableName2Record.size()
+ ", dlmPartitionId2Record.size()=" + dlmPartitionId2Record.size()
+ ", iterator=" + iterator
+ ", ctxAware=" + ctxAware
+ ", partition=" + partition + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\CreatePartitionIterateResult.java
| 1
|
请完成以下Java代码
|
private void setUOM(@NonNull final I_C_Flatrate_Term contract, @NonNull final ProductId productId)
{
final UomId uomId = Services.get(IProductBL.class).getStockUOMId(productId);
contract.setC_UOM_ID(uomId.getRepoId());
}
private void setPlannedQtyPerUnit(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getQty() != null && importRecord.getQty().intValue() > 0)
{
contract.setPlannedQtyPerUnit(importRecord.getQty());
}
}
private void setEndDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getEndDate() != null)
{
contract.setEndDate(importRecord.getEndDate());
}
}
private void setMasterStartdDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getMasterStartDate() != null)
{
contract.setMasterStartDate(importRecord.getMasterStartDate());
}
}
private void setMasterEnddDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getMasterEndDate() != null)
{
contract.setMasterEndDate(importRecord.getMasterEndDate());
}
}
private boolean isEndedContract(@NonNull final I_I_Flatrate_Term importRecord)
|
{
final Timestamp contractEndDate = importRecord.getEndDate();
final Timestamp today = SystemTime.asDayTimestamp();
return contractEndDate != null && today.after(contractEndDate);
}
private void endContractIfNeeded(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (isEndedContract(importRecord))
{
contract.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_Quit);
contract.setNoticeDate(contract.getEndDate());
contract.setIsAutoRenew(false);
contract.setProcessed(true);
contract.setDocAction(X_C_Flatrate_Term.DOCACTION_None);
contract.setDocStatus(X_C_Flatrate_Term.DOCSTATUS_Completed);
}
}
private void setTaxCategoryAndIsTaxIncluded(@NonNull final I_C_Flatrate_Term newTerm)
{
final IPricingResult pricingResult = calculateFlatrateTermPrice(newTerm);
newTerm.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingResult.getTaxCategoryId()));
newTerm.setIsTaxIncluded(pricingResult.isTaxIncluded());
}
private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm)
{
return FlatrateTermPricing.builder()
.termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID()))
.qty(newTerm.getPlannedQtyPerUnit())
.term(newTerm)
.priceDate(TimeUtil.asLocalDate(newTerm.getStartDate()))
.build()
.computeOrThrowEx();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImporter.java
| 1
|
请完成以下Java代码
|
public void setAD_Preference_ID (int AD_Preference_ID)
{
if (AD_Preference_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Preference_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Preference_ID, Integer.valueOf(AD_Preference_ID));
}
/** Get Preference.
@return Personal Value Preference
*/
public int getAD_Preference_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Preference_ID);
if (ii == null)
return 0;
return ii.intValue();
}
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_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (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_AD_Window getAD_Window() throws RuntimeException
{
return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name)
.getPO(getAD_Window_ID(), get_TrxName()); }
/** Set Window.
@param AD_Window_ID
Data entry or display window
*/
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
else
|
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Window.
@return Data entry or display window
*/
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Attribute.
@param Attribute Attribute */
public void setAttribute (String Attribute)
{
set_Value (COLUMNNAME_Attribute, Attribute);
}
/** Get Attribute.
@return Attribute */
public String getAttribute ()
{
return (String)get_Value(COLUMNNAME_Attribute);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getAttribute());
}
/** 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_AD_Preference.java
| 1
|
请完成以下Java代码
|
public void addEngineConfiguration(String engineKey, String scopeType, AbstractEngineConfiguration engineConfiguration) {
if (engineConfigurations == null) {
engineConfigurations = new HashMap<>();
}
engineConfigurations.put(engineKey, engineConfiguration);
engineConfigurations.put(scopeType, engineConfiguration);
}
public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public void setCommandExecutor(CommandExecutor commandExecutor) {
this.commandExecutor = commandExecutor;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public boolean isUseClassForNameClassLoading() {
return useClassForNameClassLoading;
}
public void setUseClassForNameClassLoading(boolean useClassForNameClassLoading) {
this.useClassForNameClassLoading = useClassForNameClassLoading;
}
public Clock getClock() {
return clock;
}
public void setClock(Clock clock) {
this.clock = clock;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
|
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
// getters and setters
// //////////////////////////////////////////////////////
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception;
}
public boolean isReused() {
return reused;
}
public void setReused(boolean reused) {
this.reused = reused;
}
public Object getResult() {
return resultStack.pollLast();
}
public void setResult(Object result) {
resultStack.add(result);
}
public long getStartTime() {
return startTime;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\interceptor\CommandContext.java
| 1
|
请完成以下Java代码
|
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("Hosts: %s", config.getPatterns());
}
};
}
public static class Config {
private List<String> patterns = new ArrayList<>();
public List<String> getPatterns() {
|
return patterns;
}
public Config setPatterns(List<String> patterns) {
this.patterns = patterns;
return this;
}
@Override
public String toString() {
return new ToStringCreator(this).append("patterns", patterns).toString();
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HostRoutePredicateFactory.java
| 1
|
请完成以下Java代码
|
public long getContactNumber() {
return contactNumber;
}
public void setContactNumber(long contactNumber) {
this.contactNumber = contactNumber;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
|
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
|
repos\tutorials-master\core-java-modules\core-java-reflection\src\main\java\com\baeldung\reflection\access\privatefields\Person.java
| 1
|
请完成以下Java代码
|
public IHUAssignmentBuilder setM_LU_HU(final I_M_HU luHU)
{
this.luHU = luHU;
return this;
}
@Override
public IHUAssignmentBuilder setM_TU_HU(final I_M_HU tuHU)
{
this.tuHU = tuHU;
return this;
}
@Override
public IHUAssignmentBuilder setVHU(final I_M_HU vhu)
{
this.vhu = vhu;
return this;
}
@Override
public IHUAssignmentBuilder setQty(final BigDecimal qty)
{
this.qty = qty;
return this;
}
@Override
public IHUAssignmentBuilder setIsTransferPackingMaterials(final boolean isTransferPackingMaterials)
{
this.isTransferPackingMaterials = isTransferPackingMaterials;
return this;
}
@Override
public IHUAssignmentBuilder setIsActive(final boolean isActive)
{
this.isActive = isActive;
return this;
}
@Override
public boolean isActive()
{
return isActive;
}
@Override
public I_M_HU_Assignment getM_HU_Assignment()
{
return assignment;
}
@Override
public boolean isNewAssignment()
{
return InterfaceWrapperHelper.isNew(assignment);
}
@Override
public IHUAssignmentBuilder initializeAssignment(final Properties ctx, final String trxName)
{
final I_M_HU_Assignment assignment = InterfaceWrapperHelper.create(ctx, I_M_HU_Assignment.class, trxName);
setAssignmentRecordToUpdate(assignment);
return this;
}
|
@Override
public IHUAssignmentBuilder setTemplateForNewRecord(final I_M_HU_Assignment assignmentRecord)
{
this.assignment = newInstance(I_M_HU_Assignment.class);
return updateFromRecord(assignmentRecord);
}
@Override
public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord)
{
this.assignment = assignmentRecord;
return updateFromRecord(assignmentRecord);
}
private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord)
{
setTopLevelHU(assignmentRecord.getM_HU());
setM_LU_HU(assignmentRecord.getM_LU_HU());
setM_TU_HU(assignmentRecord.getM_TU_HU());
setVHU(assignmentRecord.getVHU());
setQty(assignmentRecord.getQty());
setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials());
setIsActive(assignmentRecord.isActive());
return this;
}
@Override
public I_M_HU_Assignment build()
{
Check.assumeNotNull(model, "model not null");
Check.assumeNotNull(topLevelHU, "topLevelHU not null");
Check.assumeNotNull(assignment, "assignment not null");
TableRecordCacheLocal.setReferencedValue(assignment, model);
assignment.setM_HU(topLevelHU);
assignment.setM_LU_HU(luHU);
assignment.setM_TU_HU(tuHU);
assignment.setVHU(vhu);
assignment.setQty(qty);
assignment.setIsTransferPackingMaterials(isTransferPackingMaterials);
assignment.setIsActive(isActive);
InterfaceWrapperHelper.save(assignment);
return assignment;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_DistributionList[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Distribution List.
@param M_DistributionList_ID
Distribution Lists allow to distribute products to a selected list of partners
*/
public void setM_DistributionList_ID (int M_DistributionList_ID)
{
if (M_DistributionList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, Integer.valueOf(M_DistributionList_ID));
}
/** Get Distribution List.
@return Distribution Lists allow to distribute products to a selected list of partners
*/
public int getM_DistributionList_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Total Ratio.
@param RatioTotal
Total of relative weight in a distribution
*/
public void setRatioTotal (BigDecimal RatioTotal)
{
set_Value (COLUMNNAME_RatioTotal, RatioTotal);
}
/** Get Total Ratio.
@return Total of relative weight in a distribution
*/
public BigDecimal getRatioTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RatioTotal);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionList.java
| 1
|
请完成以下Java代码
|
public PageData<TenantId> findTenantsIds(PageLink pageLink) {
return DaoUtil.pageToPageData(tenantRepository.findTenantsIds(DaoUtil.toPageable(pageLink))).mapData(TenantId::fromUUID);
}
@Override
public EntityType getEntityType() {
return EntityType.TENANT;
}
@Override
public List<TenantId> findTenantIdsByTenantProfileId(TenantProfileId tenantProfileId) {
return tenantRepository.findTenantIdsByTenantProfileId(tenantProfileId.getId()).stream()
.map(TenantId::fromUUID)
.collect(Collectors.toList());
}
|
@Override
public Tenant findTenantByName(TenantId tenantId, String name) {
return DaoUtil.getData(tenantRepository.findFirstByTitle(name));
}
@Override
public List<Tenant> findTenantsByIds(UUID tenantId, List<UUID> tenantIds) {
return DaoUtil.convertDataList(tenantRepository.findTenantsByIdIn(tenantIds));
}
@Override
public List<TenantFields> findNextBatch(UUID id, int batchSize) {
return tenantRepository.findNextBatch(id, Limit.of(batchSize));
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\tenant\JpaTenantDao.java
| 1
|
请完成以下Java代码
|
public ELContext createElContext(VariableContext variableContext) {
ensureInitialized();
ProcessEngineElContext elContext = new ProcessEngineElContext(functionMapper, elResolver);
elContext.putContext(ExpressionFactory.class, expressionFactory);
elContext.putContext(VariableContext.class, variableContext);
return elContext;
}
protected ProcessEngineElContext createElContext(VariableScope variableScope) {
ensureInitialized();
ProcessEngineElContext elContext = new ProcessEngineElContext(functionMapper, elResolver);
elContext.putContext(ExpressionFactory.class, expressionFactory);
if (variableScope != null) {
elContext.putContext(VariableScope.class, variableScope);
}
return elContext;
}
protected void ensureInitialized() {
if (!initialized) {
synchronized (this) {
if (!initialized) {
elResolver = createElResolver();
functionMapper = createFunctionMapper();
parsingElContext = new ProcessEngineElContext(functionMapper);
initialized = true;
}
}
}
}
protected ELResolver createElResolver() {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(new VariableScopeElResolver());
elResolver.add(new VariableContextElResolver());
elResolver.add(new MockElResolver());
if (beans != null) {
// ACT-1102: Also expose all beans in configuration when using standalone
// engine, not
// in spring-context
elResolver.add(new ReadOnlyMapELResolver(beans));
}
elResolver.add(new ProcessApplicationElResolverDelegate());
|
elResolver.add(new ArrayELResolver());
elResolver.add(new ListELResolver());
elResolver.add(new MapELResolver());
elResolver.add(new ProcessApplicationBeanElResolverDelegate());
return elResolver;
}
protected FunctionMapper createFunctionMapper() {
FunctionMapper functionMapper = new FunctionMapper() {
@Override
public Method resolveFunction(String prefix, String localName) {
String fullName = localName;
if (prefix != null && !prefix.trim().isEmpty()) {
fullName = prefix + ":" + localName;
}
return functions.get(fullName);
}
};
return functionMapper;
}
@Override
public ElProvider toElProvider() {
if (elProvider == null) {
synchronized (this) {
if (elProvider == null) {
elProvider = createElProvider();
}
}
}
return elProvider;
}
protected ElProvider createElProvider() {
return new ProcessEngineJuelElProvider(this);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\JuelExpressionManager.java
| 1
|
请完成以下Java代码
|
public <T> void onRetry(Attempt<T> attempt) {
// 第几次重试,(注意:第一次重试其实是第一次调用)
System.out.print("[retry]time=" + attempt.getAttemptNumber());
// 距离第一次重试的延迟
System.out.print(",delay=" + attempt.getDelaySinceFirstAttempt());
// 重试结果: 是异常终止, 还是正常返回
System.out.print(",hasException=" + attempt.hasException());
System.out.print(",hasResult=" + attempt.hasResult());
// 是什么原因导致异常
if (attempt.hasException()) {
System.out.print(",causeBy=" + attempt.getExceptionCause().toString());
|
} else {
// 正常返回时的结果
System.out.print(",result=" + attempt.getResult());
}
// bad practice: 增加了额外的异常处理代码
try {
T result = attempt.get();
System.out.print(",rude get=" + result);
} catch (ExecutionException e) {
System.err.println("this attempt produce exception." + e.getCause().toString());
}
System.out.println();
}
}
|
repos\spring-boot-student-master\spring-boot-student-guava-retrying\src\main\java\com\xiaolyuh\retrylistener\MyRetryListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PageBean<RpTradePaymentRecord> listPaymentRecordPage(PageParam pageParam, PaymentOrderQueryParam paymentOrderQueryParam) {
Map<String , Object> paramMap = new HashMap<String , Object>();
paramMap.put("merchantNo", paymentOrderQueryParam.getMerchantNo());//商户编号
paramMap.put("merchantName", paymentOrderQueryParam.getMerchantName());//商户名称
paramMap.put("merchantOrderNo", paymentOrderQueryParam.getMerchantOrderNo());//商户订单号
paramMap.put("fundIntoType", paymentOrderQueryParam.getFundIntoType());//资金流入类型
paramMap.put("merchantOrderNo", paymentOrderQueryParam.getOrderDateBegin());//订单开始时间
paramMap.put("merchantOrderNo", paymentOrderQueryParam.getOrderDateEnd());//订单结束时间
paramMap.put("payTypeName", paymentOrderQueryParam.getPayTypeName());//支付类型
paramMap.put("payWayName", paymentOrderQueryParam.getPayWayName());//支付类型
paramMap.put("status", paymentOrderQueryParam.getStatus());//支付状态
if (paymentOrderQueryParam.getOrderDateBegin() != null){
paramMap.put("orderDateBegin", paymentOrderQueryParam.getOrderDateBegin());//支付状态
}
if (paymentOrderQueryParam.getOrderDateEnd() != null){
paramMap.put("orderDateEnd", paymentOrderQueryParam.getOrderDateEnd());//支付状态
}
return rpTradePaymentRecordDao.listPage(pageParam,paramMap);
}
/**
* 获取交易流水报表
*
* @param merchantNo
* @return
|
*/
public List<Map<String, String>> getPaymentReport(String merchantNo){
return rpTradePaymentRecordDao.getPaymentReport(merchantNo);
}
/**
* 获取交易方式报表
*
* @param merchantNo
* @return
*/
public List<Map<String, String>> getPayWayReport(String merchantNo){
return rpTradePaymentRecordDao.getPayWayReport(merchantNo);
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\service\impl\RpTradePaymentQueryServiceImpl.java
| 2
|
请完成以下Java代码
|
public OrgId getOrgId() {return getShipFrom().getOrgId();}
public PriceListId getPriceListId() {return pricingSystemAndListId.getPriceListId();}
public CurrencyId getCurrencyId() {return currency.getId();}
public String getCurrencySymbol(final String adLanguage) {return currency.getSymbol().translate(adLanguage);}
public CurrencyPrecision getCurrencyPrecision() {return currency.getPrecision();}
public boolean isCashJournalOpen() {return cashJournalId != null;}
@NonNull
public POSCashJournalId getCashJournalIdNotNull()
{
if (cashJournalId == null)
{
throw new AdempiereException("No open journals found");
}
return cashJournalId;
}
|
public POSTerminal openingCashJournal(@NonNull final POSCashJournalId cashJournalId)
{
if (this.cashJournalId != null)
{
throw new AdempiereException("Cash journal already open");
}
return toBuilder()
.cashJournalId(cashJournalId)
.build();
}
public POSTerminal closingCashJournal(@NonNull final Money cashEndingBalance)
{
cashEndingBalance.assertCurrencyId(currency.getId());
return toBuilder()
.cashJournalId(null)
.cashLastBalance(cashEndingBalance)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSTerminal.java
| 1
|
请完成以下Java代码
|
public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) {
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).fetch();
}
@Override
public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) {
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).fetch();
}
@Override
public int findMaxAge() {
|
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).select(person.age.max()).fetchFirst();
}
@Override
public Map<String, Integer> findMaxAgeByName() {
final JPAQueryFactory query = new JPAQueryFactory(JPQLTemplates.DEFAULT, em);
final QPerson person = QPerson.person;
return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age)));
}
}
|
repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\dao\PersonDaoImpl.java
| 1
|
请完成以下Java代码
|
public IHUAssignmentBuilder setIsActive(final boolean isActive)
{
this.isActive = isActive;
return this;
}
@Override
public boolean isActive()
{
return isActive;
}
@Override
public I_M_HU_Assignment getM_HU_Assignment()
{
return assignment;
}
@Override
public boolean isNewAssignment()
{
return InterfaceWrapperHelper.isNew(assignment);
}
@Override
public IHUAssignmentBuilder initializeAssignment(final Properties ctx, final String trxName)
{
final I_M_HU_Assignment assignment = InterfaceWrapperHelper.create(ctx, I_M_HU_Assignment.class, trxName);
setAssignmentRecordToUpdate(assignment);
return this;
}
@Override
public IHUAssignmentBuilder setTemplateForNewRecord(final I_M_HU_Assignment assignmentRecord)
{
this.assignment = newInstance(I_M_HU_Assignment.class);
return updateFromRecord(assignmentRecord);
}
@Override
public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord)
{
this.assignment = assignmentRecord;
return updateFromRecord(assignmentRecord);
}
private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord)
{
setTopLevelHU(assignmentRecord.getM_HU());
setM_LU_HU(assignmentRecord.getM_LU_HU());
setM_TU_HU(assignmentRecord.getM_TU_HU());
setVHU(assignmentRecord.getVHU());
setQty(assignmentRecord.getQty());
setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials());
setIsActive(assignmentRecord.isActive());
|
return this;
}
@Override
public I_M_HU_Assignment build()
{
Check.assumeNotNull(model, "model not null");
Check.assumeNotNull(topLevelHU, "topLevelHU not null");
Check.assumeNotNull(assignment, "assignment not null");
TableRecordCacheLocal.setReferencedValue(assignment, model);
assignment.setM_HU(topLevelHU);
assignment.setM_LU_HU(luHU);
assignment.setM_TU_HU(tuHU);
assignment.setVHU(vhu);
assignment.setQty(qty);
assignment.setIsTransferPackingMaterials(isTransferPackingMaterials);
assignment.setIsActive(isActive);
InterfaceWrapperHelper.save(assignment);
return assignment;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java
| 1
|
请完成以下Java代码
|
public void deleteVariableInstanceByTask(TaskEntity task) {
List<VariableInstanceEntity> variableInstances = task.variableStore.getVariables();
for (VariableInstanceEntity variableInstance: variableInstances) {
variableInstance.delete();
}
}
public long findVariableInstanceCountByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery) {
configureQuery(variableInstanceQuery);
return (Long) getDbEntityManager().selectOne("selectVariableInstanceCountByQueryCriteria", variableInstanceQuery);
}
@SuppressWarnings("unchecked")
public List<VariableInstance> findVariableInstanceByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery, Page page) {
configureQuery(variableInstanceQuery);
|
return getDbEntityManager().selectList("selectVariableInstanceByQueryCriteria", variableInstanceQuery, page);
}
protected void configureQuery(VariableInstanceQueryImpl query) {
getAuthorizationManager().configureVariableInstanceQuery(query);
getTenantManager().configureQuery(query);
}
@SuppressWarnings("unchecked")
public List<VariableInstanceEntity> findVariableInstancesByBatchId(String batchId) {
Map<String, String> parameters = Collections.singletonMap("batchId", batchId);
return getDbEntityManager().selectList("selectVariableInstancesByBatchId", parameters);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int delete(Long id) {
return productCategoryMapper.deleteByPrimaryKey(id);
}
@Override
public PmsProductCategory getItem(Long id) {
return productCategoryMapper.selectByPrimaryKey(id);
}
@Override
public int updateNavStatus(List<Long> ids, Integer navStatus) {
PmsProductCategory productCategory = new PmsProductCategory();
productCategory.setNavStatus(navStatus);
PmsProductCategoryExample example = new PmsProductCategoryExample();
example.createCriteria().andIdIn(ids);
return productCategoryMapper.updateByExampleSelective(productCategory, example);
}
@Override
public int updateShowStatus(List<Long> ids, Integer showStatus) {
PmsProductCategory productCategory = new PmsProductCategory();
productCategory.setShowStatus(showStatus);
PmsProductCategoryExample example = new PmsProductCategoryExample();
example.createCriteria().andIdIn(ids);
return productCategoryMapper.updateByExampleSelective(productCategory, example);
}
@Override
|
public List<PmsProductCategoryWithChildrenItem> listWithChildren() {
return productCategoryDao.listWithChildren();
}
/**
* 根据分类的parentId设置分类的level
*/
private void setCategoryLevel(PmsProductCategory productCategory) {
//没有父分类时为一级分类
if (productCategory.getParentId() == 0) {
productCategory.setLevel(0);
} else {
//有父分类时选择根据父分类level设置
PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId());
if (parentCategory != null) {
productCategory.setLevel(parentCategory.getLevel() + 1);
} else {
productCategory.setLevel(0);
}
}
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductCategoryServiceImpl.java
| 2
|
请完成以下Java代码
|
public void setIsIncludeEmpty (boolean IsIncludeEmpty)
{
set_Value (COLUMNNAME_IsIncludeEmpty, Boolean.valueOf(IsIncludeEmpty));
}
/** Get inkl. "leer"-Eintrag.
@return Legt fest, ob die Dimension einen dezidierten "Leer" Eintrag enthalten soll
*/
@Override
public boolean isIncludeEmpty ()
{
Object oo = get_Value(COLUMNNAME_IsIncludeEmpty);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set inkl. "sonstige"-Eintrag.
@param IsIncludeOtherGroup
Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll
*/
@Override
public void setIsIncludeOtherGroup (boolean IsIncludeOtherGroup)
{
set_Value (COLUMNNAME_IsIncludeOtherGroup, Boolean.valueOf(IsIncludeOtherGroup));
}
/** Get inkl. "sonstige"-Eintrag.
@return Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll
*/
@Override
public boolean isIncludeOtherGroup ()
{
Object oo = get_Value(COLUMNNAME_IsIncludeOtherGroup);
if (oo != null)
{
|
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec.java
| 1
|
请完成以下Java代码
|
private @Nullable Object resolvePrincipal(MethodParameter parameter, @Nullable Object principal) {
AuthenticationPrincipal authPrincipal = findMethodAnnotation(parameter);
String expressionToParse = authPrincipal.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(principal);
context.setVariable("this", principal);
context.setBeanResolver(this.beanResolver);
Expression expression = this.parser.parseExpression(expressionToParse);
principal = expression.getValue(context);
}
if (isInvalidType(parameter, principal)) {
if (authPrincipal.errorOnInvalidType()) {
throw new ClassCastException(principal + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return principal;
}
private boolean isInvalidType(MethodParameter parameter, @Nullable Object principal) {
if (principal == null) {
return false;
}
Class<?> typeToCheck = parameter.getParameterType();
boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType());
if (isParameterPublisher) {
ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
Class<?> genericType = resolvableType.resolveGeneric(0);
if (genericType == null) {
return false;
}
typeToCheck = genericType;
}
return !ClassUtils.isAssignable(typeToCheck, principal.getClass());
}
/**
* Configure AuthenticationPrincipal template resolution
* <p>
* By default, this value is <code>null</code>, which indicates that templates should
* not be resolved.
* @param templateDefaults - whether to resolve AuthenticationPrincipal templates
* parameters
* @since 6.4
*/
public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) {
this.useAnnotationTemplate = templateDefaults != null;
this.scanner = SecurityAnnotationScanners.requireUnique(AuthenticationPrincipal.class, templateDefaults);
|
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* {@link MethodParameter}
* @param parameter the {@link MethodParameter} to search for an {@link Annotation}
* @return the {@link Annotation} that was found or null.
*/
private @Nullable AuthenticationPrincipal findMethodAnnotation(MethodParameter parameter) {
if (this.useAnnotationTemplate) {
return this.scanner.scan(parameter.getParameter());
}
AuthenticationPrincipal annotation = parameter.getParameterAnnotation(this.annotationType);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType);
if (annotation != null) {
return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize();
}
}
return null;
}
}
|
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\handler\invocation\reactive\AuthenticationPrincipalArgumentResolver.java
| 1
|
请完成以下Java代码
|
public final String getLockedWhereClause(final @NonNull Class<?> modelClass, final @NonNull String joinColumnNameFQ, @NonNull final LockOwner lockOwner)
{
return getLockedWhereClauseAllowNullLock(modelClass, joinColumnNameFQ, lockOwner);
}
@Override
public final <T> IQueryBuilder<T> getLockedRecordsQueryBuilder(final Class<T> modelClass, final Object contextProvider)
{
final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(modelClass);
final String joinColumnNameFQ = InterfaceWrapperHelper.getTableName(modelClass) + "." + keyColumnName;
final String lockedRecordsSQL = getLockedWhereClauseAllowNullLock(modelClass, joinColumnNameFQ, null);
// note: don't specify a particular ordering; leave that freedom to the caller if this method
return Services.get(IQueryBL.class).createQueryBuilder(modelClass, contextProvider)
.addOnlyActiveRecordsFilter()
// .addOnlyContextClientOrSystem() // avoid applying context client because in some cases context is not available
.filter(TypedSqlQueryFilter.of(lockedRecordsSQL));
}
@Override
@NonNull
public final <T> List<T> retrieveAndLockMultipleRecords(@NonNull final IQuery<T> query, @NonNull final Class<T> clazz)
{
final ILockCommand lockCommand = new LockCommand(this)
.setOwner(LockOwner.NONE);
final ImmutableList.Builder<T> lockedModelsCollector = ImmutableList.builder();
final List<T> models = query.list(clazz);
if (models == null || models.isEmpty())
{
return ImmutableList.of();
}
for (final T model : models)
{
final TableRecordReference record = TableRecordReference.of(model);
if (lockRecord(lockCommand, record))
|
{
lockedModelsCollector.add(model);
}
}
final ImmutableList<T> lockedModels = lockedModelsCollector.build();
if (lockedModels.size() != models.size())
{
logger.warn("*** retrieveAndLockMultipleRecords: not all retrieved records could be locked! expectedLockedSize: {}, actualLockedSize: {}"
, models.size(), lockedModels.size());
}
return lockedModels;
}
public <T> IQuery<T> addNotLockedClause(final IQuery<T> query)
{
return retrieveNotLockedQuery(query);
}
/**
* @return <code>true</code> if the given <code>allowAdditionalLocks</code> is <code>FOR_DIFFERENT_OWNERS</code>.
*/
protected static boolean isAllowMultipleOwners(final AllowAdditionalLocks allowAdditionalLocks)
{
return allowAdditionalLocks == AllowAdditionalLocks.FOR_DIFFERENT_OWNERS;
}
protected abstract <T> IQuery<T> retrieveNotLockedQuery(IQuery<T> query);
protected abstract String getLockedWhereClauseAllowNullLock(@NonNull final Class<?> modelClass, @NonNull final String joinColumnNameFQ, @Nullable final LockOwner lockOwner);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\AbstractLockDatabase.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BookLogic {
@Autowired
private BookRepository bookRepository;
public List<BookReview> getBooksUsingOffset(String rating) {
OffsetScrollPosition offset = ScrollPosition.offset();
Window<BookReview> bookReviews = bookRepository.findFirst5ByBookRating(rating, offset);
List<BookReview> bookReviewsResult = new ArrayList<>();
do {
bookReviews.forEach(bookReviewsResult::add);
bookReviews = bookRepository.findFirst5ByBookRating(rating, (OffsetScrollPosition) bookReviews.positionAt(bookReviews.size() - 1));
} while (!bookReviews.isEmpty() && bookReviews.hasNext());
return bookReviewsResult;
}
public List<BookReview> getBooksUsingOffSetFilteringAndWindowIterator(String rating) {
|
WindowIterator<BookReview> bookReviews = WindowIterator.of(position -> bookRepository.findFirst5ByBookRating("3.5", (OffsetScrollPosition) position))
.startingAt(ScrollPosition.offset());
List<BookReview> bookReviewsResult = new ArrayList<>();
bookReviews.forEachRemaining(bookReviewsResult::add);
return bookReviewsResult;
}
public List<BookReview> getBooksUsingKeySetFiltering(String rating) {
WindowIterator<BookReview> bookReviews = WindowIterator.of(position -> bookRepository.findFirst5ByBookRating(rating, (KeysetScrollPosition) position))
.startingAt(ScrollPosition.keyset());
List<BookReview> bookReviewsResult = new ArrayList<>();
bookReviews.forEachRemaining(bookReviewsResult::add);
return bookReviewsResult;
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\scrollapi\service\BookLogic.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PersistenceJNDIConfig {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.hibernate.cache.model");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() throws NamingException {
return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url"));
}
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
|
return new JpaTransactionManager(emf);
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false");
return hibernateProperties;
}
}
|
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\spring\PersistenceJNDIConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomerRestController {
private CustomerService customerService;
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired
public CustomerRestController(CustomerService customerService) {
this.customerService = customerService;
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer) {
Customer customerCreated = customerService.createCustomer(customer);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(customerCreated.getId())
.toUri();
return ResponseEntity.created(location)
.build();
}
@PatchMapping(path = "/{id}", consumes = "application/json-patch+json")
public ResponseEntity<Customer> updateCustomer(@PathVariable String id, @RequestBody JsonPatch patch) {
try {
Customer customer = customerService.findCustomer(id)
.orElseThrow(CustomerNotFoundException::new);
Customer customerPatched = applyPatchToCustomer(patch, customer);
customerService.updateCustomer(customerPatched);
|
return ResponseEntity.ok(customerPatched);
} catch (CustomerNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.build();
} catch (JsonPatchException | JsonProcessingException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.build();
}
}
private Customer applyPatchToCustomer(JsonPatch patch, Customer targetCustomer) throws JsonPatchException, JsonProcessingException {
JsonNode patched = patch.apply(objectMapper.convertValue(targetCustomer, JsonNode.class));
return objectMapper.treeToValue(patched, Customer.class);
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\web\controller\customer\CustomerRestController.java
| 2
|
请完成以下Java代码
|
public class OrderLine {
private final Product product;
private final int quantity;
public OrderLine(Product product, int quantity) {
super();
this.product = product;
this.quantity = quantity;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OrderLine other = (OrderLine) obj;
if (product == null) {
if (other.product != null) {
return false;
}
} else if (!product.equals(other.product)) {
return false;
}
if (quantity != other.quantity) {
return false;
}
return true;
}
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((product == null) ? 0 : product.hashCode());
result = prime * result + quantity;
return result;
}
@Override
public String toString() {
return "OrderLine [product=" + product + ", quantity=" + quantity + "]";
}
Money cost() {
return product.getPrice()
.multipliedBy(quantity);
}
Product getProduct() {
return product;
}
int getQuantity() {
return quantity;
}
}
|
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\OrderLine.java
| 1
|
请完成以下Java代码
|
public class CamundaBpmRestInitializer implements ServletContextInitializer {
private static final Logger log = LoggerFactory.getLogger(CamundaBpmRestInitializer.class);
private static final EnumSet<DispatcherType> DISPATCHER_TYPES = EnumSet.of(DispatcherType.REQUEST);
private ServletContext servletContext;
private JerseyApplicationPath applicationPath;
private final CamundaBpmProperties properties;
public CamundaBpmRestInitializer(JerseyApplicationPath applicationPath, CamundaBpmProperties properties) {
this.applicationPath = applicationPath;
this.properties = properties;
}
@Override
public void onStartup(ServletContext servletContext) {
this.servletContext = servletContext;
properties.getRestApi().getFetchAndLock().getInitParams().forEach(servletContext::setInitParameter);
String restApiPathPattern = applicationPath.getUrlMapping();
registerFilter("EmptyBodyFilter", EmptyBodyFilter.class, restApiPathPattern);
registerFilter("CacheControlFilter", CacheControlFilter.class, restApiPathPattern);
}
|
private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass, final String... urlPatterns) {
return registerFilter(filterName, filterClass, null, urlPatterns);
}
private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass, final Map<String, String> initParameters,
final String... urlPatterns) {
FilterRegistration filterRegistration = servletContext.getFilterRegistration(filterName);
if (filterRegistration == null) {
filterRegistration = servletContext.addFilter(filterName, filterClass);
filterRegistration.addMappingForUrlPatterns(DISPATCHER_TYPES, true, urlPatterns);
if (initParameters != null) {
filterRegistration.setInitParameters(initParameters);
}
log.debug("Filter {} for URL {} registered.", filterName, urlPatterns);
}
return filterRegistration;
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-rest\src\main\java\org\camunda\bpm\spring\boot\starter\rest\CamundaBpmRestInitializer.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventSubscriptionEntity other = (EventSubscriptionEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (executionId != null) {
referenceIdAndClass.put(executionId, ExecutionEntity.class);
}
|
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventType=" + eventType
+ ", eventName=" + eventName
+ ", executionId=" + executionId
+ ", processInstanceId=" + processInstanceId
+ ", activityId=" + activityId
+ ", tenantId=" + tenantId
+ ", configuration=" + configuration
+ ", revision=" + revision
+ ", created=" + created
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\EventSubscriptionEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "accounts_seq")
@SequenceGenerator(name = "accounts_seq", sequenceName = "accounts_seq", allocationSize = 1)
@Column(name = "user_id")
private int userId;
private String username;
private String password;
private String email;
private Timestamp createdOn;
private Timestamp lastLogin;
@OneToOne
@JoinColumn(name = "permissions_id")
private Permission permission;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
|
public void setLastLogin(Timestamp lastLogin) {
this.lastLogin = lastLogin;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
@Override
public String toString() {
return "Account{" + "userId=" + userId + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", createdOn=" + createdOn + ", lastLogin=" + lastLogin + ", permission=" + permission + '}';
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\countrows\entity\Account.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Date getCompleteTime() {
return completeTime;
}
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
public String getIsRefund() {
return isRefund;
}
public void setIsRefund(String isRefund) {
this.isRefund = isRefund == null ? null : isRefund.trim();
}
|
public Short getRefundTimes() {
return refundTimes;
}
public void setRefundTimes(Short refundTimes) {
this.refundTimes = refundTimes;
}
public BigDecimal getSuccessRefundAmount() {
return successRefundAmount;
}
public void setSuccessRefundAmount(BigDecimal successRefundAmount) {
this.successRefundAmount = successRefundAmount;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
| 2
|
请完成以下Java代码
|
private ProcessPreconditionsResolution.ProcessCaptionMapper captionMapper(@Nullable final Amount invoicedAmtDiff)
{
if (invoicedAmtDiff == null || invoicedAmtDiff.isZero())
{
return null;
}
else
{
return originalProcessCaption -> TranslatableStrings.builder()
.append(originalProcessCaption)
.append(" (Diff: ").append(invoicedAmtDiff).append(")")
.build();
}
}
protected String doIt()
{
final CreateMatchInvoiceRequest request = createMatchInvoiceRequest().orElseThrow();
orderCostService.createMatchInvoice(request);
invalidateView();
return MSG_OK;
}
|
private ExplainedOptional<CreateMatchInvoiceRequest> createMatchInvoiceRequest()
{
final ImmutableSet<InOutCostId> selectedInOutCostIds = getSelectedInOutCostIds();
if (selectedInOutCostIds.isEmpty())
{
return ExplainedOptional.emptyBecause("No selection");
}
return ExplainedOptional.of(
CreateMatchInvoiceRequest.builder()
.invoiceAndLineId(getView().getInvoiceLineId())
.inoutCostIds(selectedInOutCostIds)
.build());
}
private ImmutableSet<InOutCostId> getSelectedInOutCostIds()
{
final ImmutableList<InOutCostRow> rows = getSelectedRows();
return rows.stream().map(InOutCostRow::getInoutCostId).collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsView_CreateMatchInv.java
| 1
|
请完成以下Java代码
|
public InvoiceCandidateRow build()
{
return new InvoiceCandidateRow(this);
}
public Builder setC_Invoice_Candidate_ID(int C_Invoice_Candidate_ID)
{
this.C_Invoice_Candidate_ID = C_Invoice_Candidate_ID;
return this;
}
public Builder setBPartnerName(String BPartnerName)
{
this.BPartnerName = BPartnerName;
return this;
}
public Builder setDocumentDate(Date documentDate)
{
this.documentDate = documentDate;
return this;
}
/**
* task 09643: separate accounting date from the transaction date
*
* @param dateAcct
* @return
*/
public Builder setDateAcct(Date dateAcct)
{
this.dateAcct = dateAcct;
return this;
}
public Builder setDateToInvoice(Date dateToInvoice)
{
this.dateToInvoice = dateToInvoice;
return this;
}
public Builder setDateInvoiced(Date dateInvoiced)
{
this.dateInvoiced = dateInvoiced;
return this;
}
public Builder setNetAmtToInvoice(BigDecimal netAmtToInvoice)
{
|
this.netAmtToInvoice = netAmtToInvoice;
return this;
}
public Builder setNetAmtInvoiced(BigDecimal netAmtInvoiced)
{
this.netAmtInvoiced = netAmtInvoiced;
return this;
}
public Builder setDiscount(BigDecimal discount)
{
this.discount = discount;
return this;
}
public Builder setCurrencyISOCode(String currencyISOCode)
{
this.currencyISOCode = currencyISOCode;
return this;
}
public Builder setInvoiceRuleName(String invoiceRuleName)
{
this.invoiceRuleName = invoiceRuleName;
return this;
}
public Builder setHeaderAggregationKey(String headerAggregationKey)
{
this.headerAggregationKey = headerAggregationKey;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidateRow.java
| 1
|
请完成以下Java代码
|
public AcctSchema getById(@NonNull final AcctSchemaId acctSchemaId)
{
final AcctSchema acctSchema = acctSchemas.get(acctSchemaId);
if (acctSchema == null)
{
throw new AdempiereException("No accounting schema found for " + acctSchemaId);
}
return acctSchema;
}
public List<AcctSchema> getByClientId(@NonNull final ClientId clientId, @Nullable final AcctSchemaId primaryAcctSchemaId)
{
final ImmutableList.Builder<AcctSchema> result = ImmutableList.builder();
// Primary accounting schema shall be returned first
if (primaryAcctSchemaId != null)
{
result.add(getById(primaryAcctSchemaId));
}
for (final AcctSchema acctSchema : acctSchemas.values())
{
if (acctSchema.getId().equals(primaryAcctSchemaId))
{
continue;
}
|
if (clientId.equals(acctSchema.getClientId()))
{
result.add(acctSchema);
}
}
return result.build();
}
public List<AcctSchema> getByChartOfAccountsId(@NonNull final ChartOfAccountsId chartOfAccountsId)
{
return acctSchemas.values()
.stream()
.filter(acctSchema -> ChartOfAccountsId.equals(acctSchema.getChartOfAccountsId(), chartOfAccountsId))
.collect(ImmutableList.toImmutableList());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AcctSchemaDAO.java
| 1
|
请完成以下Java代码
|
public void run()
{
while (!stop)
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final boolean enabled = sysConfigBL.getBooleanValue(SYSCONFIG_Enabled, false, Env.getAD_Client_ID(Env.getCtx()));
if (enabled)
{
try
{
checkImplementationVersion();
}
catch (Exception e)
{
log.error("Error", e);
}
}
//
// Sleep
int checkIntervalMin = sysConfigBL.getIntValue(SYSCONFIG_CheckInterval, DEFAULT_CheckInterval, Env.getAD_Client_ID(Env.getCtx()));
try
{
synchronized (checker)
{
checker.wait(checkIntervalMin * 60 * 1000); // minutes
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
private Logger log = LogManager.getLogger(getClass());
private Checker checker = null;
@Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
if (Ini.isSwingClient())
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final boolean enabled = sysConfigBL.getBooleanValue(SYSCONFIG_Enabled, false, Env.getAD_Client_ID(Env.getCtx()));
if (enabled)
{
try
{
checkImplementationVersion();
}
catch (Exception e)
{
log.error("Error", e);
}
}
checker = new Checker();
final Thread thread = new Thread(checker, Checker.class.getCanonicalName());
thread.start();
}
}
/**
*
*/
private final void checkImplementationVersion()
{
final String clientVersion = Adempiere.getImplementationVersion();
Check.assumeNotNull(clientVersion, "Adempiere.getImplementationVersion() is not null");
if (clientVersion.endsWith(Adempiere.CLIENT_VERSION_UNPROCESSED)
|| clientVersion.endsWith(Adempiere.CLIENT_VERSION_LOCAL_BUILD))
{
log.info("Adempiere ImplementationVersion=" + clientVersion + "! Not checking against DB");
return;
}
final String newVersion = Services.get(ISystemBL.class).get().getLastBuildInfo();
log.info("Build DB=" + newVersion);
log.info("Build Cl=" + clientVersion);
// Identical DB version
|
if (clientVersion != null && clientVersion.equals(newVersion))
{
return;
}
final String title = org.compiere.Adempiere.getName() + " " + Services.get(IMsgBL.class).getMsg(Env.getCtx(), MSG_ErrorMessage, true);
// Client version {} is available (current version is {}).
String msg = Services.get(IMsgBL.class).getMsg(Env.getCtx(), MSG_ErrorMessage); // complete message
msg = MessageFormat.format(msg, new Object[] { clientVersion, newVersion });
JOptionPane.showMessageDialog(null,
msg,
title,
JOptionPane.ERROR_MESSAGE);
Env.exitEnv(1);
}
@Override
public void beforeLogout(final MFSession session)
{
if (checker == null)
{
return; // nothing to do
}
// stop the checker
checker.stop = true;
synchronized (checker)
{
checker.notify();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\clientupdate\ClientUpdateValidator.java
| 1
|
请完成以下Java代码
|
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roleNames = new HashSet<>();
Set<String> permissions = new HashSet<>();
principals.forEach(p -> {
try {
Set<String> roles = getRoleNamesForUser(null, (String) p);
roleNames.addAll(roles);
permissions.addAll(getPermissions(null, null,roles));
} catch (SQLException e) {
e.printStackTrace();
}
});
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
info.setStringPermissions(permissions);
return info;
}
@Override
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
if(!roles.containsKey(username)) {
throw new SQLException("username not found!");
}
|
return roles.get(username);
}
@Override
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {
for (String role : roleNames) {
if (!perm.containsKey(role)) {
throw new SQLException("role not found!");
}
}
Set<String> finalSet = new HashSet<>();
for (String role : roleNames) {
finalSet.addAll(perm.get(role));
}
return finalSet;
}
}
|
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\intro\MyCustomRealm.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: demo-producer-application
cloud:
# Spring Cloud Stream 配置项,对应 BindingServiceProperties 类
stream:
# Binder 配置项,对应 BinderProperties Map
# binders:
# Binding 配置项,对应 BindingProperties Map
bindings:
demo01-output:
destination: DEMO-TOPIC-01 # 目的地。这里使用 Kafka Topic
content-type: application/json # 内容格式。这里使用 JSON
# Producer 配置项,对应 ProducerProperties 类
producer:
partition-key-expression: payload['id'] # 分区 key 表达式。该表达式基于 Spring EL,从消息中获得分区 key。
# Spring Cloud Stream Kafka 配置项
kafka:
# Kafka Binder 配置项,对应 KafkaBinderConfigurationProperties 类
binder:
brokers: 1
|
27.0.0.1:9092 # 指定 Kafka Broker 地址,可以设置多个,以逗号分隔
# Kafka 自定义 Binding 配置项,对应 KafkaBindingProperties Map
bindings:
demo01-output:
# Kafka Producer 配置项,对应 KafkaProducerProperties 类
producer:
sync: true # 是否同步发送消息,默认为 false 异步。
server:
port: 18080
|
repos\SpringBoot-Labs-master\labx-11-spring-cloud-stream-kafka\labx-11-sc-stream-kafka-producer-partitioning\src\main\resources\application.yml
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.