instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class RestApiController {
private static final Logger LOG = LoggerFactory.getLogger(RestApiController.class);
private final ClientService clientService;
private final HttpSession httpSession;
private final HttpServletRequest requestInjected;
public RestApiController(@Autowired ClientService clientService,
@Autowired HttpSession httpSession,
@Autowired HttpServletRequest requestInjected) {
LOG.info("creating ...");
this.clientService = clientService;
this.httpSession = httpSession;
this.requestInjected = requestInjected;
}
@PostConstruct
private void init() {
LOG.info("init ...");
}
@GetMapping(path = "/print-default")
public String printDefault(String message, HttpServletRequest request) {
LOG.info("printDefault: {}, {}", httpSession.getId(), request.getRequestURI());
return clientService.printDefault(message);
}
@GetMapping(path = "/print-err")
public String printStdErr(String message, HttpServletRequest request) {
LOG.info("printStdErr: {} {}", httpSession.getId(), request.getRequestURI());
return clientService.printStdErr(message);
}
@GetMapping(path = "/print-out")
public String printStdOut(String message, HttpServletRequest request) {
LOG.info("printStdOut: {} {}", httpSession.getId(), request.getRequestURI());
return clientService.printStdOut(message);
}
|
@GetMapping(path = "/data")
public String getData(HttpServletRequest request) {
LOG.info("getData: {} {} {}", httpSession.getId(), request.getRequestURI(), requestInjected.getRequestURI());
return clientService.getData();
}
@GetMapping(path = "/data-prototype")
public String getDataPrototype(HttpServletRequest request) {
LOG.info("getDataPrototype: {} {} {}", httpSession.getId(), request.getRequestURI(), requestInjected.getRequestURI());
return clientService.getDataPrototype();
}
@PreDestroy
private void shutdown() {
LOG.info("##destroy.");
}
}
|
repos\spring-examples-java-17\spring-di\src\main\java\itx\examples\springboot\di\controllers\RestApiController.java
| 2
|
请完成以下Java代码
|
public HttpStatus getHttpStatus() {
return this.httpStatus;
}
/**
* Return the scope.
* @return the scope
*/
public String getScope() {
return this.scope;
}
private static boolean isDescriptionValid(String description) {
// @formatter:off
return description == null || description.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}
private static boolean isErrorCodeValid(String errorCode) {
// @formatter:off
return errorCode.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}
|
private static boolean isErrorUriValid(String errorUri) {
return errorUri == null || errorUri.chars()
.allMatch((c) -> c == 0x21 || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
}
private static boolean isScopeValid(String scope) {
// @formatter:off
return scope == null || scope.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}
private static boolean withinTheRangeOf(int c, int min, int max) {
return c >= min && c <= max;
}
}
|
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\BearerTokenError.java
| 1
|
请完成以下Java代码
|
private ViewFilterParameterLookupEvaluationCtx createFilterParameterLookupContext(@NonNull final ViewId viewId)
{
return ViewFilterParameterLookupEvaluationCtx.builder()
.viewId(viewId)
//.viewSize(-1)
.userSessionCtx(userSession.toEvaluatee())
.build();
}
private JSONViewResult toJSONCardsViewResult(
final int boardId,
final ViewResult viewResult,
final JSONOptions jsonOpts,
Predicate<Integer> cardIdFilter)
{
final String adLanguage = jsonOpts.getAdLanguage();
final List<Integer> cardIds = viewResult.getRowIds()
.stream()
|
.filter(DocumentId::isInt).map(DocumentId::toInt)
.filter(cardIdFilter)
.collect(ImmutableList.toImmutableList());
final List<JSONBoardCard> jsonCards = boardsRepo.retrieveCardCandidates(boardId, cardIds)
.stream()
.map(card -> JSONBoardCard.of(card, adLanguage))
.sorted(FixedOrderByKeyComparator.notMatchedAtTheEnd(cardIds, JSONBoardCard::getCardId))
.collect(ImmutableList.toImmutableList());
return JSONViewResult.of(viewResult, jsonCards, jsonOpts);
}
private JSONViewResult toJSONCardsViewResult(final IView view, final JSONOptions jsonOpts)
{
final ViewResult viewResult = ViewResult.ofView(view);
final IViewRowOverrides rowOverrides = ViewRowOverridesHelper.getViewRowOverrides(view);
return JSONViewResult.of(viewResult, rowOverrides, jsonOpts, ViewRowCommentsSummary.EMPTY);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\board\BoardRestController.java
| 1
|
请完成以下Java代码
|
protected UserQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createUserQuery();
}
@Override
protected void applyFilters(UserQuery query) {
if (id != null) {
query.userId(id);
}
if(idIn != null) {
query.userIdIn(idIn);
}
if (firstName != null) {
query.userFirstName(firstName);
}
if (firstNameLike != null) {
query.userFirstNameLike(firstNameLike);
}
if (lastName != null) {
query.userLastName(lastName);
}
if (lastNameLike != null) {
query.userLastNameLike(lastNameLike);
}
if (email != null) {
query.userEmail(email);
}
if (emailLike != null) {
query.userEmailLike(emailLike);
}
if (memberOfGroup != null) {
query.memberOfGroup(memberOfGroup);
}
|
if (potentialStarter != null) {
query.potentialStarter(potentialStarter);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(UserQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_USER_ID_VALUE)) {
query.orderByUserId();
} else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) {
query.orderByUserFirstName();
} else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) {
query.orderByUserLastName();
} else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) {
query.orderByUserEmail();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserQueryDto.java
| 1
|
请完成以下Java代码
|
public void setB_TopicCategory_ID (int B_TopicCategory_ID)
{
if (B_TopicCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, Integer.valueOf(B_TopicCategory_ID));
}
/** Get Topic Category.
@return Auction Topic Category
*/
public int getB_TopicCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_B_TopicType getB_TopicType() throws RuntimeException
{
return (I_B_TopicType)MTable.get(getCtx(), I_B_TopicType.Table_Name)
.getPO(getB_TopicType_ID(), get_TrxName()); }
/** Set Topic Type.
@param B_TopicType_ID
Auction Topic Type
*/
public void setB_TopicType_ID (int B_TopicType_ID)
{
if (B_TopicType_ID < 1)
set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, Integer.valueOf(B_TopicType_ID));
}
/** Get Topic Type.
@return Auction Topic Type
*/
public int getB_TopicType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicType_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
/** 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 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_B_TopicCategory.java
| 1
|
请完成以下Java代码
|
public String getRuleId() {
return ruleId;
}
public Integer getRuleOrder() {
return ruleOrder;
}
public String getVariableName() {
return variableName;
}
public String getErrorMessage() {
return errorMessage;
}
public Date getCreateTime() {
return createTime;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricDecisionOutputInstanceDto fromHistoricDecisionOutputInstance(HistoricDecisionOutputInstance historicDecisionOutputInstance) {
HistoricDecisionOutputInstanceDto dto = new HistoricDecisionOutputInstanceDto();
dto.id = historicDecisionOutputInstance.getId();
|
dto.decisionInstanceId = historicDecisionOutputInstance.getDecisionInstanceId();
dto.clauseId = historicDecisionOutputInstance.getClauseId();
dto.clauseName = historicDecisionOutputInstance.getClauseName();
dto.ruleId = historicDecisionOutputInstance.getRuleId();
dto.ruleOrder = historicDecisionOutputInstance.getRuleOrder();
dto.variableName = historicDecisionOutputInstance.getVariableName();
dto.createTime = historicDecisionOutputInstance.getCreateTime();
dto.removalTime = historicDecisionOutputInstance.getRemovalTime();
dto.rootProcessInstanceId = historicDecisionOutputInstance.getRootProcessInstanceId();
if(historicDecisionOutputInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, historicDecisionOutputInstance.getTypedValue());
}
else {
dto.errorMessage = historicDecisionOutputInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(historicDecisionOutputInstance.getTypeName());
}
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionOutputInstanceDto.java
| 1
|
请完成以下Java代码
|
public class AD_Column_CopySelectedToTable extends JavaProcess
{
private int p_AD_Table_ID = -1;
private String p_EntityType = null;
private boolean p_IsTest = false;
@Override
protected void prepare()
{
for (final ProcessInfoParameter para : getParametersAsArray())
{
String name = para.getParameterName();
if (para.getParameter() == null)
{
continue;
}
else if (name.equals("AD_Table_ID"))
{
p_AD_Table_ID = para.getParameterAsInt();
}
else if (name.equals("EntityType"))
{
p_EntityType = para.getParameterAsString();
}
else if (name.equals("IsTest"))
{
p_IsTest = para.getParameterAsBoolean();
}
}
}
@Override
@RunOutOfTrx
protected String doIt()
{
final CopyColumnsResult result = CopyColumnsProducer.newInstance()
.setLogger(this)
.setTargetTable(getTargetTable())
.setSourceColumns(getSourceColumns())
.setEntityType(p_EntityType)
|
.setDryRun(p_IsTest)
.create();
//
return "" + result;
}
protected I_AD_Table getTargetTable()
{
if (p_AD_Table_ID <= 0)
{
throw new AdempiereException("@NotFound@ @AD_Table_ID@ " + p_AD_Table_ID);
}
final I_AD_Table targetTable = InterfaceWrapperHelper.create(getCtx(), p_AD_Table_ID, I_AD_Table.class, get_TrxName());
return targetTable;
}
protected List<I_AD_Column> getSourceColumns()
{
final IQueryFilter<I_AD_Column> selectedColumnsFilter = getProcessInfo().getQueryFilterOrElseFalse();
final IQueryBuilder<I_AD_Column> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_AD_Column.class, this)
.filter(selectedColumnsFilter);
queryBuilder.orderBy()
.addColumn(I_AD_Column.COLUMNNAME_AD_Table_ID)
.addColumn(I_AD_Column.COLUMNNAME_AD_Column_ID);
return queryBuilder
.create()
.list(I_AD_Column.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\AD_Column_CopySelectedToTable.java
| 1
|
请完成以下Java代码
|
public void setSubProducerBPartner_Value (final @Nullable java.lang.String SubProducerBPartner_Value)
{
set_Value (COLUMNNAME_SubProducerBPartner_Value, SubProducerBPartner_Value);
}
@Override
public java.lang.String getSubProducerBPartner_Value()
{
return get_ValueAsString(COLUMNNAME_SubProducerBPartner_Value);
}
@Override
public void setTE (final @Nullable java.lang.String TE)
{
set_Value (COLUMNNAME_TE, TE);
}
@Override
public java.lang.String getTE()
{
return get_ValueAsString(COLUMNNAME_TE);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setWarehouseLocatorIdentifier (final @Nullable java.lang.String WarehouseLocatorIdentifier)
{
set_Value (COLUMNNAME_WarehouseLocatorIdentifier, WarehouseLocatorIdentifier);
}
@Override
public java.lang.String getWarehouseLocatorIdentifier()
{
return get_ValueAsString(COLUMNNAME_WarehouseLocatorIdentifier);
}
@Override
public void setWarehouseValue (final @Nullable java.lang.String WarehouseValue)
{
set_Value (COLUMNNAME_WarehouseValue, WarehouseValue);
}
@Override
public java.lang.String getWarehouseValue()
{
return get_ValueAsString(COLUMNNAME_WarehouseValue);
}
@Override
public void setX (final @Nullable java.lang.String X)
{
set_Value (COLUMNNAME_X, X);
|
}
@Override
public java.lang.String getX()
{
return get_ValueAsString(COLUMNNAME_X);
}
@Override
public void setX1 (final @Nullable java.lang.String X1)
{
set_Value (COLUMNNAME_X1, X1);
}
@Override
public java.lang.String getX1()
{
return get_ValueAsString(COLUMNNAME_X1);
}
@Override
public void setY (final @Nullable java.lang.String Y)
{
set_Value (COLUMNNAME_Y, Y);
}
@Override
public java.lang.String getY()
{
return get_ValueAsString(COLUMNNAME_Y);
}
@Override
public void setZ (final @Nullable java.lang.String Z)
{
set_Value (COLUMNNAME_Z, Z);
}
@Override
public java.lang.String getZ()
{
return get_ValueAsString(COLUMNNAME_Z);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Inventory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<SysPermissionDataRule> queryPermissionDataRules(String username,String permissionId) {
List<String> idsList = this.baseMapper.queryDataRuleIds(username, permissionId);
// 代码逻辑说明: 数据权限失效问题处理--------------------
if(idsList==null || idsList.size()==0) {
return null;
}
Set<String> set = new HashSet<String>();
for (String ids : idsList) {
if(oConvertUtils.isEmpty(ids)) {
continue;
}
String[] arr = ids.split(",");
for (String id : arr) {
if(oConvertUtils.isNotEmpty(id) && !set.contains(id)) {
set.add(id);
}
}
}
if(set.size()==0) {
return null;
}
return this.baseMapper.selectList(new QueryWrapper<SysPermissionDataRule>().in("id", set).eq("status",CommonConstant.STATUS_1));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void savePermissionDataRule(SysPermissionDataRule sysPermissionDataRule) {
this.save(sysPermissionDataRule);
SysPermission permission = sysPermissionMapper.selectById(sysPermissionDataRule.getPermissionId());
boolean flag = permission != null && (permission.getRuleFlag() == null || permission.getRuleFlag().equals(CommonConstant.RULE_FLAG_0));
if(flag) {
permission.setRuleFlag(CommonConstant.RULE_FLAG_1);
sysPermissionMapper.updateById(permission);
}
|
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deletePermissionDataRule(String dataRuleId) {
SysPermissionDataRule dataRule = this.baseMapper.selectById(dataRuleId);
if(dataRule!=null) {
this.removeById(dataRuleId);
Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<SysPermissionDataRule>().eq(SysPermissionDataRule::getPermissionId, dataRule.getPermissionId()));
//注:同一个事务中删除后再查询是会认为数据已被删除的 若事务回滚上述删除无效
if(count==null || count==0) {
SysPermission permission = sysPermissionMapper.selectById(dataRule.getPermissionId());
if(permission!=null && permission.getRuleFlag().equals(CommonConstant.RULE_FLAG_1)) {
permission.setRuleFlag(CommonConstant.RULE_FLAG_0);
sysPermissionMapper.updateById(permission);
}
}
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysPermissionDataRuleImpl.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
|
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
|
repos\Spring-Boot-Advanced-Projects-main\springboot-crud-hibernate-example\src\main\java\net\alanbinu\springboot\model\Product.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Boolean isDefaultPackagingUnit() {
return defaultPackagingUnit;
}
public void setDefaultPackagingUnit(Boolean defaultPackagingUnit) {
this.defaultPackagingUnit = defaultPackagingUnit;
}
public PackagingUnit archived(Boolean archived) {
this.archived = archived;
return this;
}
/**
* Kennzeichen ob Verpackungseinheit archiviert ist, d. h. nicht mehr im Warenkorb ausgewählt werden kann
* @return archived
**/
@Schema(example = "false", description = "Kennzeichen ob Verpackungseinheit archiviert ist, d. h. nicht mehr im Warenkorb ausgewählt werden kann")
public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PackagingUnit packagingUnit = (PackagingUnit) o;
return Objects.equals(this.unit, packagingUnit.unit) &&
Objects.equals(this.quantity, packagingUnit.quantity) &&
Objects.equals(this.pcn, packagingUnit.pcn) &&
Objects.equals(this.defaultPackagingUnit, packagingUnit.defaultPackagingUnit) &&
Objects.equals(this.archived, packagingUnit.archived);
}
@Override
public int hashCode() {
return Objects.hash(unit, quantity, pcn, defaultPackagingUnit, archived);
}
@Override
public String toString() {
|
StringBuilder sb = new StringBuilder();
sb.append("class PackagingUnit {\n");
sb.append(" unit: ").append(toIndentedString(unit)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n");
sb.append(" defaultPackagingUnit: ").append(toIndentedString(defaultPackagingUnit)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\PackagingUnit.java
| 2
|
请完成以下Java代码
|
public @NonNull String getHandledTableName()
{
return I_DD_Order.Table_Name;
}
@Override
public StandardDocumentReportType getStandardDocumentReportType()
{
return StandardDocumentReportType.DISTRIBUTION_ORDER;
}
@Override
public @NonNull DocumentReportInfo getDocumentReportInfo(
@NonNull final TableRecordReference recordRef,
@Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse)
{
final DDOrderId ddOrderId = recordRef.getIdAssumingTableName(I_DD_Order.Table_Name, DDOrderId::ofRepoId);
final I_DD_Order ddOrder = ddOrderLowLevelService.getById(ddOrderId);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(ddOrder.getC_BPartner_ID());
final I_C_BPartner bpartner = util.getBPartnerById(bpartnerId);
final DocTypeId docTypeId = extractDocTypeId(ddOrder);
final I_C_DocType docType = util.getDocTypeById(docTypeId);
final ClientId clientId = ClientId.ofRepoId(ddOrder.getAD_Client_ID());
final PrintFormatId printFormatId = CoalesceUtil.coalesceSuppliers(
() -> adPrintFormatToUseId,
() -> util.getBPartnerPrintFormats(bpartnerId).getPrintFormatIdByDocTypeId(docTypeId).orElse(null),
() -> PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID()),
() -> util.getDefaultPrintFormats(clientId).getDistributionOrderPrintFormatId());
if (printFormatId == null)
{
throw new AdempiereException("@NotFound@ @AD_PrintFormat_ID@");
}
final Language language = util.getBPartnerLanguage(bpartner).orElse(null);
final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder()
.adTableId(recordRef.getAdTableId())
.bpartnerId(bpartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, ddOrder.getC_BPartner_Location_ID()))
.docTypeId(docTypeId)
.onlyCopiesGreaterZero(true)
.build();
|
return DocumentReportInfo.builder()
.recordRef(TableRecordReference.of(I_DD_Order.Table_Name, ddOrderId))
.reportProcessId(util.getReportProcessIdByPrintFormatId(printFormatId))
.copies(util.getDocumentCopies(docType, bpPrintFormatQuery))
.documentNo(ddOrder.getDocumentNo())
.bpartnerId(bpartnerId)
.docTypeId(docTypeId)
.language(language)
.build();
}
private DocTypeId extractDocTypeId(@NonNull final I_DD_Order ddOrder)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(ddOrder.getC_DocType_ID());
if (docTypeId != null)
{
return docTypeId;
}
throw new AdempiereException("No document type set");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\DistributionOrderDocumentReportAdvisor.java
| 1
|
请完成以下Java代码
|
public class RoleVoter implements AccessDecisionVoter<Object> {
private String rolePrefix = "ROLE_";
public String getRolePrefix() {
return this.rolePrefix;
}
/**
* Allows the default role prefix of <code>ROLE_</code> to be overridden. May be set
* to an empty value, although this is usually not desirable.
* @param rolePrefix the new prefix
*/
public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix());
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object
* @return always <code>true</code>
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
if (authentication == null) {
return ACCESS_DENIED;
}
int result = ACCESS_ABSTAIN;
Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
for (ConfigAttribute attribute : attributes) {
|
if (this.supports(attribute)) {
result = ACCESS_DENIED;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
return authentication.getAuthorities();
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\RoleVoter.java
| 1
|
请完成以下Java代码
|
public Double getDoubleValue() {
JsonNode doubleNode = node.path("doubleValue");
if (doubleNode.isNumber()) {
return doubleNode.doubleValue();
}
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
throw new UnsupportedOperationException("Not supported to set double value");
}
@Override
public byte[] getBytes() {
throw new UnsupportedOperationException("Not supported to get bytes");
}
|
@Override
public void setBytes(byte[] bytes) {
throw new UnsupportedOperationException("Not supported to set bytes");
}
@Override
public Object getCachedValue() {
throw new UnsupportedOperationException("Not supported to set get cached value");
}
@Override
public void setCachedValue(Object cachedValue) {
throw new UnsupportedOperationException("Not supported to set cached value");
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java
| 1
|
请完成以下Java代码
|
public class Product {
@Parsed(field = "product_no")
private String productNumber;
@Parsed
private String description;
@Parsed(field = "unit_price")
private float unitPrice;
public String getProductNumber() {
return productNumber;
}
public void setProductNumber(String productNumber) {
this.productNumber = productNumber;
}
public String getDescription() {
return description;
}
|
public void setDescription(String description) {
this.description = description;
}
public float getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(float unitPrice) {
this.unitPrice = unitPrice;
}
@Override
public String toString() {
return "Product [Product Number: " + productNumber + ", Description: " + description + ", Unit Price: " + unitPrice + "]";
}
}
|
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\univocity\model\Product.java
| 1
|
请完成以下Java代码
|
private void loadPreference(final int adUserId)
{
if (adUserId < 0)
{
return;
}
final Properties ctx = createDAOCtx();
final Map<String, I_AD_Preference> preferencesMap = retrievePreferencesMap(ctx, adUserId);
final Properties props = new Properties();
for (int i = 0; i < PROPERTIES.length; i++)
{
final String attribute = PROPERTIES[i];
String value = DEFAULT_VALUES[i];
final I_AD_Preference preference = preferencesMap.get(attribute);
if (preference != null)
{
value = preference.getValue();
}
props.setProperty(attribute, value);
}
m_AD_User_ID = adUserId;
this.props = props;
}
public void loadPreference(final Properties ctx)
{
final int adUserId = Env.getAD_User_ID(ctx);
loadPreference(adUserId);
}
/**
* Set Property
*
* @param key Key
* @param value Value
*/
public void setProperty(final String key, final String value)
{
if (props == null)
{
props = new Properties();
}
if (value == null)
{
props.setProperty(key, "");
}
else
{
props.setProperty(key, value);
}
}
/**
* Set Property
*
* @param key Key
* @param value Value
*/
public void setProperty(final String key, final Boolean value)
{
setProperty(key, DisplayType.toBooleanString(value));
}
/**
* Set Property
*
* @param key Key
* @param value Value
*/
public void setProperty(final String key, final int value)
{
setProperty(key, String.valueOf(value));
}
/**
* Get Property
*
* @param key Key
* @return Value
*/
public String getProperty(final String key)
{
if (key == null)
|
{
return "";
}
if (props == null)
{
return "";
}
final String value = props.getProperty(key, "");
if (Check.isEmpty(value))
{
return "";
}
return value;
}
/**
* Get Property as Boolean
*
* @param key Key
* @return Value
*/
public boolean isPropertyBool(final String key)
{
final String value = getProperty(key);
return DisplayType.toBooleanNonNull(value, false);
}
public void updateContext(final Properties ctx)
{
Env.setContext(ctx, "#ShowTrl", true);
Env.setContext(ctx, "#ShowAdvanced", true);
Env.setAutoCommit(ctx, isPropertyBool(P_AUTO_COMMIT));
Env.setAutoNew(ctx, isPropertyBool(P_AUTO_NEW));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserPreference.java
| 1
|
请完成以下Java代码
|
public void setTaxID (final java.lang.String TaxID)
{
set_ValueNoCheck (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_ValueNoCheck (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
|
return get_ValueAsString(COLUMNNAME_Title);
}
@Override
public void setValue (final java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Header_v.java
| 1
|
请完成以下Java代码
|
public CashAccountType2 getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link CashAccountType2 }
*
*/
public void setTp(CashAccountType2 value) {
this.tp = value;
}
/**
* Gets the value of the ccy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCcy() {
return ccy;
}
/**
* Sets the value of the ccy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
|
public void setCcy(String value) {
this.ccy = value;
}
/**
* Gets the value of the nm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNm() {
return nm;
}
/**
* Sets the value of the nm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNm(String value) {
this.nm = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashAccount16.java
| 1
|
请完成以下Java代码
|
public Object getValue() {
return value;
}
public ValueType getType() {
// no type
return null;
}
@Override
public String toString() {
return "Untyped value '"+value+"', isTransient = " + isTransient;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
result = prime * result + (isTransient ? 1 : 0);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
|
return false;
UntypedValueImpl other = (UntypedValueImpl) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
if (isTransient != other.isTransient()) {
return false;
}
return true;
}
@Override
public boolean isTransient() {
return isTransient;
}
public void setTransient(boolean isTransient) {
this.isTransient = isTransient;
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\UntypedValueImpl.java
| 1
|
请完成以下Java代码
|
public class JsonExternalIds
{
public ExternalId toExternalIdOrNull(@Nullable final JsonExternalId jsonExternalId)
{
if (jsonExternalId == null)
{
return null;
}
return ExternalId.of(jsonExternalId.getValue());
}
public ExternalId toExternalId(@NonNull final JsonExternalId jsonExternalId)
{
return ExternalId.of(jsonExternalId.getValue());
}
public ImmutableList<ExternalId> toExternalIds(@NonNull final Collection<JsonExternalId> externalLineIds)
{
return externalLineIds
.stream()
.map(JsonExternalIds::toExternalId)
.collect(ImmutableList.toImmutableList());
}
public JsonExternalId of(@NonNull final ExternalId externalId)
{
return JsonExternalId.of(externalId.getValue());
}
public JsonExternalId ofOrNull(@Nullable final ExternalId externalId)
{
if (externalId == null)
{
|
return null;
}
return JsonExternalId.of(externalId.getValue());
}
public boolean equals(@Nullable final JsonExternalId id1, @Nullable final JsonExternalId id2)
{
return Objects.equals(id1, id2);
}
public static boolean isEqualTo(
@Nullable final JsonExternalId jsonExternalId,
@Nullable final ExternalId externalId)
{
if (jsonExternalId == null && externalId == null)
{
return true;
}
if (jsonExternalId == null ^ externalId == null)
{
return false; // one is null, the other one isn't
}
return Objects.equals(jsonExternalId.getValue(), externalId.getValue());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\JsonExternalIds.java
| 1
|
请完成以下Java代码
|
public String toString() {
return toJson();
}
private String escape(String value) {
StringBuilder builder = new StringBuilder();
builder.append("\"");
for (char c : value.toCharArray()) {
if (c == '\'') builder.append("\\'");
else if (c == '\"') builder.append("\\\"");
else if (c == '\r') builder.append("\\r");
else if (c == '\n') builder.append("\\n");
else if (c == '\t') builder.append("\\t");
else if (c < 32 || c >= 127) builder.append(String.format("\\u%04x", (int) c));
else builder.append(c);
}
builder.append("\"");
return builder.toString();
}
/**
* Creates builder to build {@link ProcessVariableValue}.
* @return created builder
*/
public static ITypeStage builder() {
return new Builder();
}
/**
* Definition of a stage for staged builder.
*/
public interface ITypeStage {
/**
* Builder method for type parameter.
* @param type field to set
* @return builder
*/
public IValueStage type(String type);
}
/**
* Definition of a stage for staged builder.
*/
public interface IValueStage {
/**
* Builder method for value parameter.
|
* @param value field to set
* @return builder
*/
public IBuildStage value(String value);
}
/**
* Definition of a stage for staged builder.
*/
public interface IBuildStage {
/**
* Builder method of the builder.
* @return built class
*/
public ProcessVariableValue build();
}
/**
* Builder to build {@link ProcessVariableValue}.
*/
public static final class Builder implements ITypeStage, IValueStage, IBuildStage {
private String type;
private String value;
private Builder() {}
@Override
public IValueStage type(String type) {
this.type = type;
return this;
}
@Override
public IBuildStage value(String value) {
this.value = value;
return this;
}
@Override
public ProcessVariableValue build() {
return new ProcessVariableValue(this);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessVariableValue.java
| 1
|
请完成以下Java代码
|
public class FilesAPI {
//
private String member_id;
private String member_type;
public FilesAPI(String member_id, String member_type) {
this.member_id = member_id;
this.member_type = member_type;
}
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
|
public String getMember_type() {
return member_type;
}
public void setMember_type(String member_type) {
this.member_type = member_type;
}
@Override
public String toString() {
return "FilesAPI{" +
"member_id='" + member_id + '\'' +
", member_type='" + member_type + '\'' +
'}';
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSourceCode\SpringGradle\src\main\java\com\example\demo\aspera\FilesAPI.java
| 1
|
请完成以下Java代码
|
public boolean isAnyRecordProcessed(@NonNull final Set<OLCandId> olCandIds)
{
return queryBL.createQueryBuilder(I_C_OLCand.class)
.addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, olCandIds)
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, true)
.create()
.anyMatch();
}
public int deleteRecords(@NonNull final Set<OLCandId> olCandIds)
{
return queryBL.createQueryBuilder(I_C_OLCand.class)
.addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, olCandIds)
.create()
.delete();
}
public int deleteUnprocessedRecords(@NonNull final IQueryFilter<I_C_OLCand> queryFilter)
|
{
return queryBL.createQueryBuilder(I_C_OLCand.class)
.addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false)
.filter(queryFilter)
.create()
.delete();
}
public void assignAsyncBatchId(@NonNull final Set<OLCandId> olCandIds, @NonNull final AsyncBatchId asyncBatchId)
{
final ICompositeQueryUpdater<I_C_OLCand> updater = queryBL.createCompositeQueryUpdater(I_C_OLCand.class)
.addSetColumnValue(I_C_OLCand.COLUMNNAME_C_Async_Batch_ID, asyncBatchId.getRepoId());
queryBL.createQueryBuilder(I_C_OLCand.class)
.addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, olCandIds)
.create()
.update(updater);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\impl\OLCandDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Double getExceedCount() {
return exceedCount;
}
public ServerFlowConfig setExceedCount(Double exceedCount) {
this.exceedCount = exceedCount;
return this;
}
public Double getMaxOccupyRatio() {
return maxOccupyRatio;
}
public ServerFlowConfig setMaxOccupyRatio(Double maxOccupyRatio) {
this.maxOccupyRatio = maxOccupyRatio;
return this;
}
public Integer getIntervalMs() {
return intervalMs;
}
public ServerFlowConfig setIntervalMs(Integer intervalMs) {
this.intervalMs = intervalMs;
return this;
}
public Integer getSampleCount() {
|
return sampleCount;
}
public ServerFlowConfig setSampleCount(Integer sampleCount) {
this.sampleCount = sampleCount;
return this;
}
public Double getMaxAllowedQps() {
return maxAllowedQps;
}
public ServerFlowConfig setMaxAllowedQps(Double maxAllowedQps) {
this.maxAllowedQps = maxAllowedQps;
return this;
}
@Override
public String toString() {
return "ServerFlowConfig{" +
"namespace='" + namespace + '\'' +
", exceedCount=" + exceedCount +
", maxOccupyRatio=" + maxOccupyRatio +
", intervalMs=" + intervalMs +
", sampleCount=" + sampleCount +
", maxAllowedQps=" + maxAllowedQps +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\config\ServerFlowConfig.java
| 2
|
请完成以下Java代码
|
public class C_Invoice_Candidate_Agg implements ModelValidator
{
private int m_AD_Client_ID = -1;
@Override
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public void initialize(ModelValidationEngine engine, MClient client)
{
if (client != null)
m_AD_Client_ID = client.getAD_Client_ID();
engine.addModelChange(I_C_Invoice_Candidate_Agg.Table_Name, this);
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
return null;
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{
if (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE)
|
{
if (po.is_ValueChanged(I_C_Invoice_Candidate_Agg.COLUMNNAME_Classname))
{
final I_C_Invoice_Candidate_Agg icAgg = InterfaceWrapperHelper.create(po, I_C_Invoice_Candidate_Agg.class);
Services.get(IAggregationBL.class).evalClassName(icAgg);
}
// Note: we invalidate *every* candidate, so there is no need to use the different IInvoiceCandidateHandler implementations.
final IInvoiceCandDAO invoiceCandDB = Services.get(IInvoiceCandDAO.class);
invoiceCandDB.invalidateAllCands(po.getCtx(), po.get_TrxName());
}
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_Invoice_Candidate_Agg.java
| 1
|
请完成以下Java代码
|
public I_PA_Goal getPA_Goal() throws RuntimeException
{
return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name)
.getPO(getPA_Goal_ID(), get_TrxName()); }
/** Set Goal.
@param PA_Goal_ID
Performance Goal
*/
public void setPA_Goal_ID (int PA_Goal_ID)
{
if (PA_Goal_ID < 1)
set_Value (COLUMNNAME_PA_Goal_ID, null);
else
set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID));
}
/** Get Goal.
@return Performance Goal
*/
public int getPA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID);
if (ii == null)
|
return 0;
return ii.intValue();
}
/** Set ZUL File Path.
@param ZulFilePath
Absolute path to zul file
*/
public void setZulFilePath (String ZulFilePath)
{
set_Value (COLUMNNAME_ZulFilePath, ZulFilePath);
}
/** Get ZUL File Path.
@return Absolute path to zul file
*/
public String getZulFilePath ()
{
return (String)get_Value(COLUMNNAME_ZulFilePath);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_DashboardContent.java
| 1
|
请完成以下Java代码
|
public CostSegmentAndElement withProductIdAndCostingLevel(final ProductId productId, final CostingLevel costingLevel)
{
return new CostSegmentAndElement(
getCostSegment().withProductIdAndCostingLevel(productId, costingLevel),
getCostElementId());
}
public CostSegment toCostSegment()
{
return getCostSegment();
}
public AcctSchemaId getAcctSchemaId()
{
return getCostSegment().getAcctSchemaId();
}
public CostTypeId getCostTypeId()
{
return getCostSegment().getCostTypeId();
}
public CostingLevel getCostingLevel() {return getCostSegment().getCostingLevel();}
public ClientId getClientId()
{
return getCostSegment().getClientId();
}
|
public OrgId getOrgId()
{
return getCostSegment().getOrgId();
}
public ProductId getProductId()
{
return getCostSegment().getProductId();
}
public AttributeSetInstanceId getAttributeSetInstanceId()
{
return getCostSegment().getAttributeSetInstanceId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostSegmentAndElement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
Map<String, Object> params = new HashMap<>(2);
params.put("scopeIds", createSafeInValuesList(scopeIds));
params.put("scopeType", scopeType);
// Using HistoricVariableInstanceEntity as the entity, because the deletion order of the ByteArrayEntity is after the HistoricVariableInstanceEntity
getDbSqlSession().delete("bulkDeleteBytesForHistoricVariableInstancesForScopeIdsAndScopeType", params, HistoricVariableInstanceEntity.class);
getDbSqlSession().delete("bulkDeleteHistoricVariableInstancesForScopeIdsAndScopeType", params, HistoricVariableInstanceEntity.class);
}
@Override
public void deleteHistoricVariableInstancesForNonExistingProcessInstances() {
// Using HistoricVariableInstanceEntity as the entity, because the deletion order of the ByteArrayEntity is after the HistoricVariableInstanceEntity
getDbSqlSession().delete("bulkDeleteBytesForHistoricVariableInstancesForNonExistingProcessInstances", null, HistoricVariableInstanceEntity.class);
getDbSqlSession().delete("bulkDeleteHistoricVariableInstancesForNonExistingProcessInstances", null, HistoricVariableInstanceEntity.class);
|
}
@Override
public void deleteHistoricVariableInstancesForNonExistingCaseInstances() {
// Using HistoricVariableInstanceEntity as the entity, because the deletion order of the ByteArrayEntity is after the HistoricVariableInstanceEntity
getDbSqlSession().delete("bulkDeleteBytesForHistoricVariableInstancesForNonExistingCaseInstances", null, HistoricVariableInstanceEntity.class);
getDbSqlSession().delete("bulkDeleteHistoricVariableInstancesForNonExistingCaseInstances", null, HistoricVariableInstanceEntity.class);
}
@Override
protected IdGenerator getIdGenerator() {
return variableServiceConfiguration.getIdGenerator();
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\data\impl\MybatisHistoricVariableInstanceDataManager.java
| 2
|
请完成以下Java代码
|
public ImmutableSet<HuId> getVHUIdsByDocumentRef(@NonNull final HUReservationDocRef documentRef)
{
return getByDocumentRef(documentRef).map(HUReservation::getVhuIds).orElseGet(ImmutableSet::of);
}
public ImmutableList<HUReservationEntry> getEntriesByVHUIds(@NonNull final Collection<HuId> vhuIds)
{
return huReservationRepository.getEntriesByVHUIds(vhuIds);
}
public boolean isAnyOfVHUIdsReserved(@NonNull final Collection<HuId> vhuIds)
{
return !huReservationRepository.getEntriesByVHUIds(vhuIds).isEmpty();
}
@Builder(builderMethodName = "prepareHUQuery", builderClassName = "AvailableHUQueryBuilder")
private IHUQueryBuilder createHUQuery(
@NonNull final WarehouseId warehouseId,
@NonNull final ProductId productId,
@NonNull final BPartnerId bpartnerId,
@Nullable final AttributeSetInstanceId asiId,
@Nullable final HUReservationDocRef reservedToDocumentOrNotReservedAtAll)
{
final Set<WarehouseId> pickingWarehouseIds = warehousesRepo.getWarehouseIdsOfSamePickingGroup(warehouseId);
final IHUQueryBuilder huQuery = handlingUnitsDAO
.createHUQueryBuilder()
.addOnlyInWarehouseIds(pickingWarehouseIds)
.addOnlyWithProductId(productId)
.addHUStatusToInclude(X_M_HU.HUSTATUS_Active);
// ASI
if (asiId != null)
{
final ImmutableAttributeSet attributeSet = asiBL.getImmutableAttributeSetById(asiId);
huQuery.addOnlyWithAttributeValuesMatchingPartnerAndProduct(bpartnerId, productId, attributeSet);
huQuery.allowSqlWhenFilteringAttributes(isAllowSqlWhenFilteringHUAttributes());
}
// Reservation
if (reservedToDocumentOrNotReservedAtAll == null)
{
huQuery.setExcludeReserved();
}
else
{
huQuery.setExcludeReservedToOtherThan(reservedToDocumentOrNotReservedAtAll);
}
return huQuery;
|
}
// FIXME: move it to AttributeDAO
@Deprecated
public boolean isAllowSqlWhenFilteringHUAttributes()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AllowSqlWhenFilteringHUAttributes, true);
}
public void transferReservation(
@NonNull final HUReservationDocRef from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> vhuIds)
{
huReservationRepository.transferReservation(ImmutableSet.of(from), to, vhuIds);
}
public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to)
{
final Set<HuId> vhuIds = ImmutableSet.of();
huReservationRepository.transferReservation(from, to, vhuIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationService.java
| 1
|
请完成以下Java代码
|
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
/**
* VariantGroup AD_Reference_ID=540490
* Reference name: VariantGroup
*/
public static final int VARIANTGROUP_AD_Reference_ID=540490;
/** 01 = 01 */
public static final String VARIANTGROUP_01 = "01";
/** 02 = 02 */
public static final String VARIANTGROUP_02 = "02";
/** 03 = 03 */
|
public static final String VARIANTGROUP_03 = "03";
/** 04 = 04 */
public static final String VARIANTGROUP_04 = "04";
/** 05 = 05 */
public static final String VARIANTGROUP_05 = "05";
/** 06 = 06 */
public static final String VARIANTGROUP_06 = "06";
/** 07 = 07 */
public static final String VARIANTGROUP_07 = "07";
/** 08 = 08 */
public static final String VARIANTGROUP_08 = "08";
/** 09 = 09 */
public static final String VARIANTGROUP_09 = "09";
@Override
public void setVariantGroup (final @Nullable java.lang.String VariantGroup)
{
set_Value (COLUMNNAME_VariantGroup, VariantGroup);
}
@Override
public java.lang.String getVariantGroup()
{
return get_ValueAsString(COLUMNNAME_VariantGroup);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOMLine.java
| 1
|
请完成以下Java代码
|
private ModelAndView handleIllegalArgument(IllegalArgumentException ex,
final HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
final String accept = request.getHeader(HttpHeaders.ACCEPT);
response.sendError(HttpServletResponse.SC_CONFLICT);
response.setHeader("ContentType", accept);
final ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("error", prepareErrorResponse(accept));
return modelAndView;
}
/** Prepares error object based on the provided accept type.
* @param accept The Accept header present in the request.
* @return The response to return
* @throws JsonProcessingException
*/
private String prepareErrorResponse(String accept) throws JsonProcessingException {
|
final Map<String, String> error = new HashMap<>();
error.put("Error", "Application specific error message");
final String response;
if(MediaType.APPLICATION_JSON_VALUE.equals(accept)) {
response = new ObjectMapper().writeValueAsString(error);
} else {
response = new XmlMapper().writeValueAsString(error);
}
return response;
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\error\RestResponseStatusExceptionResolver.java
| 1
|
请完成以下Java代码
|
public void onException(Throwable throwable) {
// 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
log.info( "async send fail" );
}
} );
}
/**
* 顺序消息
*/
public void sendOrderlyMsg() {
//根据指定的hashKey按顺序发送
for (int i = 0; i < 1000; i++) {
String orderId = "biz_" + i % 10;
// 分区顺序消息中区分不同分区的关键字段,Sharding Key与普通消息的key是完全不同的概念。
// 全局顺序消息,该字段可以设置为任意非空字符串。
String shardingKey = String.valueOf( orderId );
try {
SendResult sendResult = rocketMQTemplate.syncSendOrderly( "Topic-Order", "send order msg".getBytes(), shardingKey );
// 发送消息,只要不抛异常就是成功。
if (sendResult != null) {
System.out.println( new Date() + " Send mq message success . msgId is:" + sendResult.getMsgId() );
}
} catch (Exception e) {
// 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
System.out.println( new Date() + " Send mq message failed" );
e.printStackTrace();
}
}
}
/**
* 延时消息
*/
public void sendDelayMsg() {
|
rocketMQTemplate.syncSend( "Topic-Delay",
MessageBuilder.withPayload( "Hello MQ".getBytes() ).build(),
3000,
//设置延时等级3,这个消息将在10s之后发送(现在只支持固定的几个时间,详看delayTimeLevel)
//messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
3 );
}
/**
* 批量消息
*/
public void sendBatchMsg(List<Message> messages) {
rocketMQTemplate.syncSend( "springboot-rocketmq", messages );
}
/**
* 事务消息
*/
public void sendTransactionMsg(){
TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
"Topic-Tx:TagA",
MessageBuilder.withPayload( "Hello MQ transaction===".getBytes() ).build(),
null );
SendStatus sendStatus = transactionSendResult.getSendStatus();
LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
System.out.println( new Date() + " Send mq message status "+ sendStatus +" , localTransactionState "+ localTransactionState );
}
}
|
repos\SpringBootLearning-master (1)\springboot-rocketmq-message\src\main\java\com\itwolfed\msg\Producer.java
| 1
|
请完成以下Java代码
|
private static JsonResponseIncoterms toJson(@Nullable final Incoterms incoterms)
{
if (incoterms == null)
{
return null;
}
return JsonResponseIncoterms.builder()
.metasfreshId(JsonMetasfreshId.of(incoterms.getId().getRepoId()))
.name(incoterms.getName())
.value(incoterms.getValue())
.build();
}
@NonNull
private JsonProductBPartner toJsonProductBPartner(final I_C_BPartner_Product record)
{
return JsonProductBPartner.builder()
.bpartnerId(JsonMetasfreshId.of(record.getC_BPartner_ID()))
.productId(JsonMetasfreshId.of(record.getM_Product_ID()))
//
.productNo(record.getProductNo())
.productName(record.getProductName())
.productDescription(record.getProductDescription())
.productCategory(record.getProductCategory())
//
.ean(record.getUPC())
//
.vendor(record.isUsedForVendor())
.currentVendor(record.isUsedForVendor() && record.isCurrentVendor())
.customer(record.isUsedForCustomer())
//
.leadTimeInDays(record.getDeliveryTime_Promised())
//
.excludedFromSale(record.isExcludedFromSale())
.exclusionFromSaleReason(record.getExclusionFromSaleReason())
|
.excludedFromPurchase(record.isExcludedFromPurchase())
.exclusionFromPurchaseReason(record.getExclusionFromPurchaseReason())
//
.build();
}
private static JsonResponseBPBankAccount toJson(@NonNull final BPartnerBankAccount bankAccount)
{
final JsonMetasfreshId metasfreshId = JsonMetasfreshId.of(bankAccount.getIdNotNull().getRepoId());
final JsonMetasfreshId metasfreshBPartnerId = JsonMetasfreshId.of(bankAccount.getIdNotNull().getBpartnerId().getRepoId());
final JsonMetasfreshId currencyId = JsonMetasfreshId.of(CurrencyId.toRepoId(bankAccount.getCurrencyId()));
final JsonChangeInfo jsonChangeInfo = createJsonChangeInfo(bankAccount.getChangeLog(), BANK_ACCOUNT_FIELD_MAP);
return JsonResponseBPBankAccount.builder()
.metasfreshId(metasfreshId)
.metasfreshBPartnerId(metasfreshBPartnerId)
.currencyId(currencyId)
.iban(bankAccount.getIban())
.active(bankAccount.isActive())
.accountName(bankAccount.getAccountName())
.accountStreet(bankAccount.getAccountStreet())
.accountZip(bankAccount.getAccountZip())
.accountCity(bankAccount.getAccountCity())
.accountCountry(bankAccount.getAccountCountry())
.changeInfo(jsonChangeInfo)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\bpartnercomposite\JsonRetrieverService.java
| 1
|
请完成以下Java代码
|
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWaitingTime (final int WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
|
@Override
public int getWaitingTime()
{
return get_ValueAsInt(COLUMNNAME_WaitingTime);
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node.java
| 1
|
请完成以下Java代码
|
class PickingSlotUtils
{
public static boolean isAvailableForBPartnerAndLocation(
@NonNull final I_M_PickingSlot pickingSlot,
final BPartnerId bpartnerId,
@Nullable final BPartnerLocationId bpartnerLocationId)
{
//
// General use Picking Slot, accept it right away
if (isAvailableForAnyBPartner(pickingSlot))
{
return true;
}
//
// Check if is available for BPartner
if (!isAvailableForBPartnerId(pickingSlot, bpartnerId))
{
return false;
}
//
// Check BPartner Location
final BPartnerLocationId pickingSlotBPartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID(), pickingSlot.getC_BPartner_Location_ID());
// Any BP Location Picking Slot
if (pickingSlotBPartnerLocationId == null)
{
// accept any location
}
// Picking slot specific for BP Location
else
{
if (bpartnerLocationId == null)
{
// no particular location was requested, accept it
}
else if (BPartnerLocationId.equals(bpartnerLocationId, pickingSlotBPartnerLocationId))
{
// same BP Location, accept it
}
else
{
// not same BP Location, don't accept it
return false;
}
}
// If we reach this point, we passed all validation rules
return true;
}
public static boolean isAvailableForAnyBPartner(@NonNull final I_M_PickingSlot pickingSlot)
{
final BPartnerId pickingSlotBPartnerId = extractBPartnerId(pickingSlot);
return pickingSlotBPartnerId == null
&& pickingSlot.getM_Picking_Job_ID() <= 0;
}
public static boolean isAvailableForBPartnerId(@NonNull final I_M_PickingSlot pickingSlot, @Nullable final BPartnerId bpartnerId)
{
//
// General use Picking Slot, accept it right away
if (isAvailableForAnyBPartner(pickingSlot))
{
return true;
}
//
// Check BPartner
final BPartnerId pickingSlotBPartnerId = extractBPartnerId(pickingSlot);
// Any BPartner Picking Slot
|
if (pickingSlotBPartnerId == null)
{
// accept any partner
}
// Picking slot specific for BP
else
{
if (bpartnerId == null)
{
// no particular partner was requested, (i.e. M_HU_PI_Item_Product does not have a BP set), accept it
}
else if (BPartnerId.equals(bpartnerId, pickingSlotBPartnerId))
{
// same BP, accept it
}
else
{
// not same BP, don't accept it
return false;
}
}
// If we reach this point, we passed all validation rules
return true;
}
@Nullable
private static BPartnerId extractBPartnerId(final @NonNull I_M_PickingSlot pickingSlot)
{
return BPartnerId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PickingSlotUtils.java
| 1
|
请完成以下Java代码
|
void execute() {
GraphQlClient graphQlClient = null;
String document = "";
// tag::execute[]
Mono<Project> projectMono = graphQlClient.document(document)
.execute()
.map((response) -> {
if (!response.isValid()) {
// Request failure... <1>
}
ClientResponseField field = response.field("project");
if (field.getValue() == null) {
if (field.getErrors().isEmpty()) {
// Optional field set to null... <2>
|
}
else {
// Field failure... <3>
}
}
return field.toEntity(Project.class); // <4>
});
// end::execute[]
}
record Project() {
}
}
|
repos\spring-graphql-main\spring-graphql-docs\src\main\java\org\springframework\graphql\docs\client\requests\execute\Execute.java
| 1
|
请完成以下Java代码
|
public LocalDate getOrderDate() {
return orderDate;
}
public void setOrderDate(LocalDate orderDate) {
this.orderDate = orderDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCustomerName() {
|
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\fetchandrefresh\Order.java
| 1
|
请完成以下Java代码
|
protected String createServiceUrl(HttpServletRequest request, HttpServletResponse response) {
return WebUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null,
this.serviceProperties.getArtifactParameter(), this.encodeServiceUrlWithSessionId);
}
/**
* Constructs the Url for Redirection to the CAS server. Default implementation relies
* on the CAS client to do the bulk of the work.
* @param serviceUrl the service url that should be included.
* @return the redirect url. CANNOT be NULL.
*/
protected String createRedirectUrl(String serviceUrl) {
return CommonUtils.constructRedirectUrl(this.loginUrl, this.serviceProperties.getServiceParameter(), serviceUrl,
this.serviceProperties.isSendRenew(), false);
}
/**
* Template method for you to do your own pre-processing before the redirect occurs.
* @param request the HttpServletRequest
* @param response the HttpServletResponse
*/
protected void preCommence(HttpServletRequest request, HttpServletResponse response) {
}
/**
* The enterprise-wide CAS login URL. Usually something like
* <code>https://www.mycompany.com/cas/login</code>.
* @return the enterprise-wide CAS login URL
*/
public final @Nullable String getLoginUrl() {
return this.loginUrl;
}
public final ServiceProperties getServiceProperties() {
return this.serviceProperties;
}
public final void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
|
public final void setServiceProperties(ServiceProperties serviceProperties) {
this.serviceProperties = serviceProperties;
}
/**
* Sets whether to encode the service url with the session id or not.
* @param encodeServiceUrlWithSessionId whether to encode the service url with the
* session id or not.
*/
public final void setEncodeServiceUrlWithSessionId(boolean encodeServiceUrlWithSessionId) {
this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId;
}
/**
* Sets whether to encode the service url with the session id or not.
* @return whether to encode the service url with the session id or not.
*
*/
protected boolean getEncodeServiceUrlWithSessionId() {
return this.encodeServiceUrlWithSessionId;
}
/**
* Sets the {@link RedirectStrategy} to use
* @param redirectStrategy the {@link RedirectStrategy} to use
* @since 6.3
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy;
}
}
|
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasAuthenticationEntryPoint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrderLineItems
{
public static final String SERIALIZED_NAME_ITEM_ID = "itemId";
@SerializedName(SERIALIZED_NAME_ITEM_ID)
private String itemId;
public static final String SERIALIZED_NAME_LINE_ITEM_ID = "lineItemId";
@SerializedName(SERIALIZED_NAME_LINE_ITEM_ID)
private String lineItemId;
public OrderLineItems itemId(String itemId)
{
this.itemId = itemId;
return this;
}
/**
* The unique identifier of the eBay listing associated with the order.
*
* @return itemId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The unique identifier of the eBay listing associated with the order.")
public String getItemId()
{
return itemId;
}
public void setItemId(String itemId)
{
this.itemId = itemId;
}
public OrderLineItems lineItemId(String lineItemId)
{
this.lineItemId = lineItemId;
return this;
}
/**
* The unique identifier of the line item within the order. The lineItemId value is created once the buyer actually purchases the item, or if there is a commitment to buy (such as an auction that is won by the buyer, an accepted Best Offer, or other situation that does not require immediate payment from the buyer).
*
* @return lineItemId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The unique identifier of the line item within the order. The lineItemId value is created once the buyer actually purchases the item, or if there is a commitment to buy (such as an auction that is won by the buyer, an accepted Best Offer, or other situation that does not require immediate payment from the buyer).")
public String getLineItemId()
{
return lineItemId;
}
public void setLineItemId(String lineItemId)
{
this.lineItemId = lineItemId;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
|
}
OrderLineItems orderLineItems = (OrderLineItems)o;
return Objects.equals(this.itemId, orderLineItems.itemId) &&
Objects.equals(this.lineItemId, orderLineItems.lineItemId);
}
@Override
public int hashCode()
{
return Objects.hash(itemId, lineItemId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class OrderLineItems {\n");
sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n");
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\OrderLineItems.java
| 2
|
请完成以下Java代码
|
private MInvoice createInvoice(MRMA rma)
{
int docTypeId = getInvoiceDocTypeId(rma.get_ID());
if (docTypeId == -1)
{
throw new IllegalStateException("Could not get invoice document type for Vendor RMA");
}
MInvoice invoice = new MInvoice(getCtx(), 0, get_TrxName());
invoice.setRMA(rma);
Services.get(IInvoiceBL.class).setDocTypeTargetIdAndUpdateDescription(invoice, docTypeId);
if (!invoice.save())
{
throw new IllegalStateException("Could not create invoice");
}
return invoice;
}
private MInvoiceLine[] createInvoiceLines(MRMA rma, MInvoice invoice)
{
ArrayList<MInvoiceLine> invLineList = new ArrayList<>();
MRMALine rmaLines[] = rma.getLines(true);
for (MRMALine rmaLine : rmaLines)
{
if (rmaLine.getM_InOutLine_ID() == 0)
{
throw new IllegalStateException("No customer return line - RMA = "
+ rma.getDocumentNo() + ", Line = " + rmaLine.getLine());
}
MInvoiceLine invLine = new MInvoiceLine(invoice);
invLine.setRMALine(rmaLine);
if (!invLine.save())
{
throw new IllegalStateException("Could not create invoice line");
}
|
invLineList.add(invLine);
}
MInvoiceLine invLines[] = new MInvoiceLine[invLineList.size()];
invLineList.toArray(invLines);
return invLines;
}
private void generateInvoice(int M_RMA_ID)
{
MRMA rma = new MRMA(getCtx(), M_RMA_ID, get_TrxName());
MInvoice invoice = createInvoice(rma);
MInvoiceLine invoiceLines[] = createInvoiceLines(rma, invoice);
if (invoiceLines.length == 0)
{
log.warn("No invoice lines created: M_RMA_ID="
+ M_RMA_ID + ", M_Invoice_ID=" + invoice.get_ID());
}
StringBuffer processMsg = new StringBuffer(invoice.getDocumentNo());
if (!invoice.processIt(p_docAction))
{
processMsg.append(" (NOT Processed)");
log.warn("Invoice Processing failed: " + invoice + " - " + invoice.getProcessMsg());
}
if (!invoice.save())
{
throw new IllegalStateException("Could not update invoice");
}
// Add processing information to process log
addLog(invoice.getC_Invoice_ID(), invoice.getDateInvoiced(), null, processMsg.toString());
m_created++;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\process\InvoiceGenerateRMA.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static BPartnerInfo ofLocationAndContact(
@NonNull final BPartnerLocationAndCaptureId bpartnerLocationAndCaptureId,
@Nullable final BPartnerContactId contactId)
{
return builder()
.bpartnerId(bpartnerLocationAndCaptureId.getBpartnerId())
.bpartnerLocationId(bpartnerLocationAndCaptureId.getBpartnerLocationId())
.locationId(bpartnerLocationAndCaptureId.getLocationCaptureId())
.contactId(contactId)
.build();
}
public static boolean equals(@Nullable final BPartnerInfo o1, @Nullable final BPartnerInfo o2)
{
return Objects.equals(o1, o2);
}
public DocumentLocation toDocumentLocation()
{
return DocumentLocation.builder()
.bpartnerId(bpartnerId)
.bpartnerLocationId(bpartnerLocationId)
.contactId(contactId)
.locationId(locationId)
.build();
}
public BPartnerInfo withLocationId(@Nullable final LocationId locationId)
{
|
return !LocationId.equals(this.locationId, locationId)
? toBuilder().locationId(locationId).build()
: this;
}
public BPartnerInfo withContactId(@Nullable final BPartnerContactId contactId)
{
return !BPartnerContactId.equals(this.contactId, contactId)
? toBuilder().contactId(contactId).build()
: this;
}
public BPartnerLocationAndCaptureId toBPartnerLocationAndCaptureId()
{
if (bpartnerLocationId == null)
{
throw new AdempiereException("Cannot convert " + this + " to " + BPartnerLocationAndCaptureId.class.getSimpleName() + " because bpartnerLocationId is null");
}
return BPartnerLocationAndCaptureId.of(bpartnerLocationId, locationId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerInfo.java
| 2
|
请完成以下Java代码
|
public class PlainQueryBuilderDAO extends AbstractQueryBuilderDAO
{
@Override
protected <T> IQuery<T> createQuery(final QueryBuildContext<T> queryBuildCtx,
final ISqlQueryFilter sqlFilters,
final IQueryFilter<T> nonSqlFilters)
{
final Class<T> modelClass = queryBuildCtx.getModelClass();
final String tableName = queryBuildCtx.getModelTableName();
final Properties ctx = queryBuildCtx.getCtx();
final String trxName = queryBuildCtx.getTrxName();
final POJOQuery<T> query = new POJOQuery<>(ctx, modelClass, tableName, trxName)
.setOrderBy(queryBuildCtx.getQueryOrderBy())
.setLimit(queryBuildCtx.getQueryLimit())
.setOnlySelection(queryBuildCtx.getQueryOnlySelectionId())
.setOptions(queryBuildCtx.getQueryOptions());
//
// Add the SQL filters
if (sqlFilters != null)
{
if (sqlFilters instanceof IQueryFilter)
{
@SuppressWarnings("unchecked")
final IQueryFilter<T> sqlFiltersCasted = (IQueryFilter<T>)sqlFilters;
query.addFilter(sqlFiltersCasted);
}
else
{
throw new AdempiereException("Sql filter could not be converted to regular filter: " + sqlFilters);
}
}
//
// Add the non-SQL filters
if (nonSqlFilters != null)
{
|
query.addFilter(nonSqlFilters);
}
return query;
}
@Override
protected <T> IPair<ISqlQueryFilter, IQueryFilter<T>> extractSqlAndNonSqlFilters(IQueryFilter<T> filter)
{
// NOTE: SQL filters are not supported in Plain DAO
final ISqlQueryFilter sqlFilters = null;
final IQueryFilter<T> nonSqlFilters = filter;
return ImmutablePair.of(sqlFilters, nonSqlFilters);
}
@Override
public <T> String getSql(final Properties ctx, final ICompositeQueryFilter<T> filter, final List<Object> sqlParamsOut)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\PlainQueryBuilderDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<DREFE1> getDREFE1() {
if (drefe1 == null) {
drefe1 = new ArrayList<DREFE1>();
}
return this.drefe1;
}
/**
* Gets the value of the dtaxi1 property.
*
* @return
* possible object is
* {@link DTAXI1 }
*
*/
public DTAXI1 getDTAXI1() {
return dtaxi1;
}
/**
* Sets the value of the dtaxi1 property.
*
* @param value
* allowed object is
* {@link DTAXI1 }
*
*/
public void setDTAXI1(DTAXI1 value) {
this.dtaxi1 = value;
}
/**
* Gets the value of the dalch1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
|
* This is why there is not a <CODE>set</CODE> method for the dalch1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDALCH1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DALCH1 }
*
*
*/
public List<DALCH1> getDALCH1() {
if (dalch1 == null) {
dalch1 = new ArrayList<DALCH1>();
}
return this.dalch1;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\DETAILXrech.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
|
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\models\AppUser.java
| 1
|
请完成以下Java代码
|
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Relative Period.
@param RelativePeriod
Period offset (0 is current)
*/
public void setRelativePeriod (BigDecimal RelativePeriod)
{
set_Value (COLUMNNAME_RelativePeriod, RelativePeriod);
}
/** Get Relative Period.
@return Period offset (0 is current)
*/
public BigDecimal getRelativePeriod ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativePeriod);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
|
*/
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element
*/
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportColumn.java
| 1
|
请完成以下Java代码
|
public GrpcClient getClient() {
return this.client;
}
public Class<?> getTargetClazz() {
return this.targetClazz;
}
public BeanDefinition getTargetBeanDefinition() {
return this.targetBeanDefinition;
}
public int getConstructorArgumentIndex() {
return this.constructorArgumentIndex;
}
}
|
public List<Registry> getRegistries() {
return this.injections;
}
public GrpcClientConstructorInjection add(final Registry injection) {
this.injections.add(injection);
return this;
}
public boolean isEmpty() {
return this.injections.isEmpty();
}
}
|
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\inject\GrpcClientConstructorInjection.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<Object> getDictDetailMaps(@RequestParam String dictName){
String[] names = dictName.split("[,,]");
Map<String, List<DictDetailDto>> dictMap = new HashMap<>(16);
for (String name : names) {
dictMap.put(name, dictDetailService.getDictByName(name));
}
return new ResponseEntity<>(dictMap, HttpStatus.OK);
}
@Log("新增字典详情")
@ApiOperation("新增字典详情")
@PostMapping
@PreAuthorize("@el.check('dict:add')")
public ResponseEntity<Object> createDictDetail(@Validated @RequestBody DictDetail resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
dictDetailService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
|
}
@Log("修改字典详情")
@ApiOperation("修改字典详情")
@PutMapping
@PreAuthorize("@el.check('dict:edit')")
public ResponseEntity<Object> updateDictDetail(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){
dictDetailService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除字典详情")
@ApiOperation("删除字典详情")
@DeleteMapping(value = "/{id}")
@PreAuthorize("@el.check('dict:del')")
public ResponseEntity<Object> deleteDictDetail(@PathVariable Long id){
dictDetailService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DictDetailController.java
| 1
|
请完成以下Java代码
|
public InputStream getBinaryDataAsStream(final I_AD_Archive archive)
{
return archiveStorageFactory.getArchiveStorage(archive).getBinaryDataAsStream(archive);
}
@Override
public Optional<AdArchive> getLastArchive(
@NonNull final TableRecordReference reference)
{
return getLastArchiveRecord(reference).map(this::toAdArchive);
}
@Override
public Optional<I_AD_Archive> getLastArchiveRecord(
@NonNull final TableRecordReference reference)
{
final IArchiveDAO archiveDAO = Services.get(IArchiveDAO.class);
final List<I_AD_Archive> lastArchives = archiveDAO.retrieveLastArchives(Env.getCtx(), reference, QueryLimit.ONE);
if (lastArchives.isEmpty())
{
return Optional.empty();
}
else
{
return Optional.of(lastArchives.get(0));
}
}
@Override
public Optional<Resource> getLastArchiveBinaryData(
|
@NonNull final TableRecordReference reference)
{
return getLastArchive(reference).map(AdArchive::getArchiveDataAsResource);
}
@Override
public void updatePrintedRecords(final ImmutableSet<ArchiveId> ids, final UserId userId)
{
archiveDAO.updatePrintedRecords(ids, userId);
}
private AdArchive toAdArchive(final I_AD_Archive record)
{
return AdArchive.builder()
.id(ArchiveId.ofRepoId(record.getAD_Archive_ID()))
.archiveData(getBinaryData(record))
.contentType(getContentType(record))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveBL.java
| 1
|
请完成以下Java代码
|
public void dbSchemaPrune() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
if (isHistoryTablePresent() && !processEngineConfiguration.isDbHistoryUsed()) {
dbSchemaDropHistory();
}
if (isIdentityTablePresent() && !processEngineConfiguration.isDbIdentityUsed()) {
dbSchemaDropIdentity();
}
if (isCmmnTablePresent() && !processEngineConfiguration.isCmmnEnabled()) {
dbSchemaDropCmmn();
}
if (isCmmnHistoryTablePresent() && (!processEngineConfiguration.isCmmnEnabled() || !processEngineConfiguration.isDbHistoryUsed())) {
dbSchemaDropCmmnHistory();
}
if (isDmnTablePresent() && !processEngineConfiguration.isDmnEnabled()) {
dbSchemaDropDmn();
}
if(isDmnHistoryTablePresent() && (!processEngineConfiguration.isDmnEnabled() || !processEngineConfiguration.isDbHistoryUsed())) {
dbSchemaDropDmnHistory();
}
}
public abstract boolean isEngineTablePresent();
public abstract boolean isHistoryTablePresent();
public abstract boolean isIdentityTablePresent();
public abstract boolean isCmmnTablePresent();
public abstract boolean isCmmnHistoryTablePresent();
public abstract boolean isDmnTablePresent();
public abstract boolean isDmnHistoryTablePresent();
public void dbSchemaUpdate() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
if (!isEngineTablePresent()) {
dbSchemaCreateEngine();
}
if (!isHistoryTablePresent() && processEngineConfiguration.isDbHistoryUsed()) {
dbSchemaCreateHistory();
}
if (!isIdentityTablePresent() && processEngineConfiguration.isDbIdentityUsed()) {
dbSchemaCreateIdentity();
}
if (!isCmmnTablePresent() && processEngineConfiguration.isCmmnEnabled()) {
dbSchemaCreateCmmn();
}
if (!isCmmnHistoryTablePresent() && processEngineConfiguration.isCmmnEnabled() && processEngineConfiguration.isDbHistoryUsed()) {
|
dbSchemaCreateCmmnHistory();
}
if (!isDmnTablePresent() && processEngineConfiguration.isDmnEnabled()) {
dbSchemaCreateDmn();
}
if(!isDmnHistoryTablePresent() && processEngineConfiguration.isDmnEnabled() && processEngineConfiguration.isDbHistoryUsed()) {
dbSchemaCreateDmnHistory();
}
}
public List<String> getTableNamesPresent() {
return Collections.emptyList();
}
public void addEntityLoadListener(EntityLoadListener listener) {
this.listeners.add(listener);
}
protected void fireEntityLoaded(Object result) {
if(result != null && result instanceof DbEntity) {
DbEntity entity = (DbEntity) result;
for (EntityLoadListener entityLoadListener : listeners) {
entityLoadListener.onEntityLoaded(entity);
}
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\AbstractPersistenceSession.java
| 1
|
请完成以下Java代码
|
public void registerListener()
{
eventBusRegistry.registerGlobalEventListener(BPartnerProductStatsEventSender.TOPIC_InOut, this);
eventBusRegistry.registerGlobalEventListener(BPartnerProductStatsEventSender.TOPIC_Invoice, this);
}
@Override
public void onEvent(final IEventBus eventBus, final Event event)
{
final String topicName = eventBus.getTopic().getName();
statsRepoAccessLock.lock();
try
{
if (BPartnerProductStatsEventSender.TOPIC_InOut.getName().equals(topicName))
{
statsEventHandler.handleInOutChangedEvent(BPartnerProductStatsEventSender.extractInOutChangedEvent(event));
|
}
else if (BPartnerProductStatsEventSender.TOPIC_Invoice.getName().equals(topicName))
{
statsEventHandler.handleInvoiceChangedEvent(BPartnerProductStatsEventSender.extractInvoiceChangedEvent(event));
}
else
{
logger.warn("Ignore unknown event {} got on topic={}", event, topicName);
}
}
finally
{
statsRepoAccessLock.unlock();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStatsEventListener.java
| 1
|
请完成以下Java代码
|
public boolean isJson()
{
return contentType != null && contentType.includes(MediaType.APPLICATION_JSON);
}
public String getBodyAsString()
{
if (body == null)
{
return null;
}
else if (isJson())
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(body);
}
catch (JsonProcessingException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
|
}
else if (body instanceof String)
{
return (String)body;
}
else if (body instanceof byte[])
{
return new String((byte[])body, charset);
}
else
{
return body.toString();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiResponse.java
| 1
|
请完成以下Java代码
|
public void bpmnError(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) {
Map<String, TypedValueField> typeValueDtoMap = typedValues.serializeVariables(variables);
BpmnErrorRequestDto payload = new BpmnErrorRequestDto(workerId, errorCode, errorMessage, typeValueDtoMap);
String resourcePath = BPMN_ERROR_RESOURCE_PATH.replace("{id}", taskId);
String resourceUrl = getBaseUrl() + resourcePath;
engineInteraction.postRequest(resourceUrl, payload, Void.class);
}
public void extendLock(String taskId, long newDuration) {
ExtendLockRequestDto payload = new ExtendLockRequestDto(workerId, newDuration);
String resourcePath = EXTEND_LOCK_RESOURCE_PATH.replace("{id}", taskId);
String resourceUrl = getBaseUrl() + resourcePath;
engineInteraction.postRequest(resourceUrl, payload, Void.class);
}
public byte[] getLocalBinaryVariable(String variableName, String executionId) {
String resourcePath = getBaseUrl() + GET_BINARY_VARIABLE
.replace(ID_PATH_PARAM, executionId)
.replace(NAME_PATH_PARAM, variableName);
return engineInteraction.getRequest(resourcePath);
}
|
public String getBaseUrl() {
return urlResolver.getBaseUrl();
}
public String getWorkerId() {
return workerId;
}
public void setTypedValues(TypedValues typedValues) {
this.typedValues = typedValues;
}
public boolean isUsePriority() {
return usePriority;
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineClient.java
| 1
|
请完成以下Java代码
|
public static void duplicateConsumerClientID() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-consumer");
props.put("group.id", "test-group");
props.put("key.deserializer", StringDeserializer.class);
props.put("value.deserializer", StringDeserializer.class);
// Simulating concurrent client creation by multiple threads
for (int i = 0; i < 3; i++) {
new Thread(() -> {
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
}).start();
}
}
public void duplicateProducerClientID() throws Exception {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
// Attempting to create another producer using same client.id
KafkaProducer<String, String> producer2 = new KafkaProducer<>(props);
}
public static void unclosedProducerAndReinitialize() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
// Attempting to reinitialize without proper close
producer1 = new KafkaProducer<>(props);
}
}
class MyMBean implements DynamicMBean {
@Override
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
return null;
}
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
}
|
@Override
public AttributeList getAttributes(String[] attributes) {
return null;
}
@Override
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
@Override
public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
return null;
}
@Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[0];
MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
MBeanOperationInfo[] operations = new MBeanOperationInfo[0];
MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[0];
return new MBeanInfo(MyMBean.class.getName(), "My MBean", attributes, constructors, operations, notifications);
}
}
|
repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\kafkaexception\SimulateInstanceAlreadyExistsException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static final class Builder {
private boolean observeRequests;
private boolean observeAuthentications;
private boolean observeAuthorizations;
Builder(boolean observeRequests, boolean observeAuthentications, boolean observeAuthorizations) {
this.observeRequests = observeRequests;
this.observeAuthentications = observeAuthentications;
this.observeAuthorizations = observeAuthorizations;
}
public Builder shouldObserveRequests(boolean excludeFilters) {
this.observeRequests = excludeFilters;
return this;
}
|
public Builder shouldObserveAuthentications(boolean excludeAuthentications) {
this.observeAuthentications = excludeAuthentications;
return this;
}
public Builder shouldObserveAuthorizations(boolean excludeAuthorizations) {
this.observeAuthorizations = excludeAuthorizations;
return this;
}
public SecurityObservationSettings build() {
return new SecurityObservationSettings(this.observeRequests, this.observeAuthentications,
this.observeAuthorizations);
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\observation\SecurityObservationSettings.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getTradeAmount() {
return tradeAmount;
}
public void setTradeAmount(BigDecimal tradeAmount) {
this.tradeAmount = tradeAmount;
}
public BigDecimal getBankTradeAmount() {
return bankTradeAmount;
}
public void setBankTradeAmount(BigDecimal bankTradeAmount) {
this.bankTradeAmount = bankTradeAmount;
}
public BigDecimal getRefundAmount() {
return refundAmount;
}
public void setRefundAmount(BigDecimal refundAmount) {
this.refundAmount = refundAmount;
}
public BigDecimal getBankRefundAmount() {
return bankRefundAmount;
}
public void setBankRefundAmount(BigDecimal bankRefundAmount) {
this.bankRefundAmount = bankRefundAmount;
}
public BigDecimal getBankFee() {
return bankFee;
}
public void setBankFee(BigDecimal bankFee) {
this.bankFee = bankFee;
}
public String getOrgCheckFilePath() {
return orgCheckFilePath;
}
public void setOrgCheckFilePath(String orgCheckFilePath) {
this.orgCheckFilePath = orgCheckFilePath == null ? null : orgCheckFilePath.trim();
}
public String getReleaseCheckFilePath() {
return releaseCheckFilePath;
}
public void setReleaseCheckFilePath(String releaseCheckFilePath) {
this.releaseCheckFilePath = releaseCheckFilePath == null ? null : releaseCheckFilePath.trim();
}
public String getReleaseStatus() {
return releaseStatus;
|
}
public void setReleaseStatus(String releaseStatus) {
this.releaseStatus = releaseStatus == null ? null : releaseStatus.trim();
}
public BigDecimal getFee() {
return fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public String getCheckFailMsg() {
return checkFailMsg;
}
public void setCheckFailMsg(String checkFailMsg) {
this.checkFailMsg = checkFailMsg;
}
public String getBankErrMsg() {
return bankErrMsg;
}
public void setBankErrMsg(String bankErrMsg) {
this.bankErrMsg = bankErrMsg;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckBatch.java
| 2
|
请完成以下Java代码
|
public void markAllAsReadByUserId(final UserId adUserId)
{
retrieveNotesByUserId(adUserId)
.create()
.update(this::markAsReadNoSave);
}
private I_AD_Note retrieveAD_Note(final int adNoteId)
{
Check.assumeGreaterThanZero(adNoteId, "adNoteId");
return InterfaceWrapperHelper.loadOutOfTrx(adNoteId, I_AD_Note.class);
}
@Override
public boolean deleteById(final int notificationId)
{
final I_AD_Note notificationPO = retrieveAD_Note(notificationId);
if (notificationPO == null)
{
return false;
}
deleteNotification(notificationPO);
return true;
}
@Override
public void deleteByUserAndTableRecordRef(final @NonNull UserId adUserId, final @NonNull TableRecordReference tableRecordReference)
{
retrieveNotesByUserId(adUserId)
.addEqualsFilter(I_AD_Note.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId())
.addEqualsFilter(I_AD_Note.COLUMNNAME_Record_ID, tableRecordReference.getRecord_ID())
.create()
.delete(false);
|
}
@Override
public void deleteAllByUserId(final UserId adUserId)
{
retrieveNotesByUserId(adUserId)
.create()
.list()
.forEach(this::deleteNotification);
}
private void deleteNotification(final I_AD_Note notificationPO)
{
notificationPO.setProcessed(false);
InterfaceWrapperHelper.delete(notificationPO);
}
@Override
public int getUnreadCountByUserId(final UserId adUserId)
{
return retrieveNotesByUserId(adUserId)
.addEqualsFilter(I_AD_Note.COLUMN_Processed, false)
.create()
.count();
}
@Override
public int getTotalCountByUserId(final UserId adUserId)
{
return retrieveNotesByUserId(adUserId)
.create()
.count();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationRepository.java
| 1
|
请完成以下Java代码
|
public class MyConfiguration__BeanDefinitions {
/**
* Get the bean definition for 'myConfiguration'.
*/
public static BeanDefinition getMyConfigurationBeanDefinition() {
Class<?> beanType = MyConfiguration.class;
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType);
beanDefinition.setInstanceSupplier(MyConfiguration::new);
return beanDefinition;
}
/**
* Get the bean instance supplier for 'myBean'.
*/
|
private static BeanInstanceSupplier<MyBean> getMyBeanInstanceSupplier() {
return BeanInstanceSupplier.<MyBean>forFactoryMethod(MyConfiguration.class, "myBean")
.withGenerator((registeredBean) -> registeredBean.getBeanFactory().getBean(MyConfiguration.class).myBean());
}
/**
* Get the bean definition for 'myBean'.
*/
public static BeanDefinition getMyBeanBeanDefinition() {
Class<?> beanType = MyBean.class;
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType);
beanDefinition.setInstanceSupplier(getMyBeanInstanceSupplier());
return beanDefinition;
}
}
|
repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\packaging\nativeimage\introducinggraalvmnativeimages\understandingaotprocessing\sourcecodegeneration\MyConfiguration__BeanDefinitions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class InvoiceFooters {
@XmlElement(name = "InvoiceFooter")
protected List<InvoiceFooterType> invoiceFooter;
/**
* Gets the value of the invoiceFooter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the invoiceFooter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInvoiceFooter().add(newItem);
* </pre>
*
*
* <p>
|
* Objects of the following type(s) are allowed in the list
* {@link InvoiceFooterType }
*
*
*/
public List<InvoiceFooterType> getInvoiceFooter() {
if (invoiceFooter == null) {
invoiceFooter = new ArrayList<InvoiceFooterType>();
}
return this.invoiceFooter;
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICExtensionType.java
| 2
|
请完成以下Java代码
|
public long findHistoricVariableInstanceCountByQueryCriteria(
HistoricVariableInstanceQueryImpl historicProcessVariableQuery
) {
return historicVariableInstanceDataManager.findHistoricVariableInstanceCountByQueryCriteria(
historicProcessVariableQuery
);
}
@Override
public List<HistoricVariableInstance> findHistoricVariableInstancesByQueryCriteria(
HistoricVariableInstanceQueryImpl historicProcessVariableQuery,
Page page
) {
return historicVariableInstanceDataManager.findHistoricVariableInstancesByQueryCriteria(
historicProcessVariableQuery,
page
);
}
@Override
public HistoricVariableInstanceEntity findHistoricVariableInstanceByVariableInstanceId(String variableInstanceId) {
return historicVariableInstanceDataManager.findHistoricVariableInstanceByVariableInstanceId(variableInstanceId);
}
@Override
public void deleteHistoricVariableInstancesByTaskId(String taskId) {
if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
List<HistoricVariableInstanceEntity> historicProcessVariables =
historicVariableInstanceDataManager.findHistoricVariableInstancesByTaskId(taskId);
for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) {
delete((HistoricVariableInstanceEntity) historicProcessVariable);
}
}
}
@Override
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return historicVariableInstanceDataManager.findHistoricVariableInstancesByNativeQuery(
parameterMap,
|
firstResult,
maxResults
);
}
@Override
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return historicVariableInstanceDataManager.findHistoricVariableInstanceCountByNativeQuery(parameterMap);
}
public HistoricVariableInstanceDataManager getHistoricVariableInstanceDataManager() {
return historicVariableInstanceDataManager;
}
public void setHistoricVariableInstanceDataManager(
HistoricVariableInstanceDataManager historicVariableInstanceDataManager
) {
this.historicVariableInstanceDataManager = historicVariableInstanceDataManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public class DefaultCmmnClassDelegateFactory implements CmmnClassDelegateFactory {
protected ExpressionManager expressionManager;
public DefaultCmmnClassDelegateFactory(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
@Override
public CmmnClassDelegate create(String className, List<FieldExtension> fieldExtensions) {
return new CmmnClassDelegate(className, fieldExtensions);
}
@Override
public CmmnClassDelegate createLifeCycleListener(String className, String sourceState, String targetState, List<FieldExtension> fieldExtensions) {
CmmnClassDelegate cmmnClassDelegate = create(className, fieldExtensions);
cmmnClassDelegate.setSourceState(sourceState);
cmmnClassDelegate.setTargetState(targetState);
return cmmnClassDelegate;
}
@Override
public Object defaultInstantiateDelegate(Class<?> clazz, ServiceTask serviceTask, boolean allExpressions) {
Object object = ReflectUtil.instantiate(clazz.getName());
if (serviceTask != null) {
for (FieldExtension extension : serviceTask.getFieldExtensions()) {
Object value;
if (StringUtils.isNotEmpty(extension.getExpression())) {
|
value = expressionManager.createExpression(extension.getExpression());
} else if (allExpressions) {
value = new FixedValue(extension.getStringValue());
} else {
value = extension.getStringValue();
}
ReflectUtil.invokeSetterOrField(object, extension.getFieldName(), value, false);
}
ReflectUtil.invokeSetterOrField(object, "serviceTask", serviceTask, false);
}
return object;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\DefaultCmmnClassDelegateFactory.java
| 1
|
请完成以下Java代码
|
public BigDecimal firstGreaterThanZero(@Nullable final BigDecimal... values)
{
if (values == null || values.length == 0)
{
return BigDecimal.ZERO;
}
for (final BigDecimal value : values)
{
if (value != null && value.signum() > 0)
{
return value;
}
}
return BigDecimal.ZERO;
}
@SafeVarargs
@NonNull
public BigDecimal firstGreaterThanZeroBigDecimalSupplier(@NonNull final Supplier<BigDecimal>... suppliers)
{
if (suppliers == null)
{
return BigDecimal.ZERO;
}
for (final Supplier<BigDecimal> supplier : suppliers)
{
final BigDecimal value = supplier.get();
if (value != null && value.signum() > 0)
{
return value;
}
}
return BigDecimal.ZERO;
}
@SafeVarargs
public int firstGreaterThanZeroIntegerSupplier(@NonNull final Supplier<Integer>... suppliers)
{
if (suppliers == null)
{
return 0;
}
for (final Supplier<Integer> supplier : suppliers)
{
final Integer value = supplier.get();
if (value != null && value > 0)
{
return value;
}
}
return 0;
}
/**
* @return the first non-empty string or {@code null}.
*/
@Nullable
public String firstNotEmptyTrimmed(@Nullable final String... values)
{
return firstNotBlank(values);
}
@Nullable
public String firstNotBlank(@Nullable final String... values)
{
if(values == null)
{
return null;
}
for (final String value : values)
{
final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm != null)
{
return valueNorm;
}
}
return null;
}
@Nullable
@SafeVarargs
|
public String firstNotBlank(@Nullable final Supplier<String>... valueSuppliers)
{
if(valueSuppliers == null)
{
return null;
}
for (final Supplier<String> valueSupplier : valueSuppliers)
{
if (valueSupplier == null)
{
continue;
}
final String value = valueSupplier.get();
final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm != null)
{
return valueNorm;
}
}
return null;
}
public boolean isAllNotNulls(final Object... values)
{
for (final Object value : values)
{
if (value == null)
{
return false;
}
}
return true;
}
public int countNotNulls(@Nullable final Object... values)
{
if (values == null || values.length == 0)
{
return 0;
}
int count = 0;
for (final Object value : values)
{
if (value != null)
{
count++;
}
}
return count;
}
@NonNull
public BigDecimal firstPositiveOrZero(final BigDecimal... values)
{
if (values == null)
{
return BigDecimal.ZERO;
}
for (final BigDecimal value : values)
{
if (value != null && value.signum() > 0)
{
return value;
}
}
return BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\CoalesceUtil.java
| 1
|
请完成以下Java代码
|
public class NameAnalysisEntity {
private String name;
private NameAgeEntity age;
private NameCountriesEntity countries;
private NameGenderEntity gender;
public NameAnalysisEntity() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public NameAgeEntity getAge() {
return age;
}
public void setAge(NameAgeEntity age) {
this.age = age;
}
public NameCountriesEntity getCountries() {
return countries;
}
public void setCountries(NameCountriesEntity countries) {
this.countries = countries;
}
public NameGenderEntity getGender() {
return gender;
}
public void setGender(NameGenderEntity gender) {
this.gender = gender;
}
@Override
public int hashCode() {
final int prime = 31;
|
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((countries == null) ? 0 : countries.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.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;
NameAnalysisEntity other = (NameAnalysisEntity) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (countries == null) {
if (other.countries != null)
return false;
} else if (!countries.equals(other.countries))
return false;
if (gender == null) {
if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
return true;
}
@Override
public String toString() {
return "NameAnalysisEntity [name=" + name + ", age=" + age + ", countries=" + countries + ", gender=" + gender + "]";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameAnalysisEntity.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
Process process = getProcess(builder.getProcessDefinitionId(), commandContext);
List<StartEvent> startEvents = process.findFlowElementsOfType(StartEvent.class, false);
for (StartEvent startEvent : startEvents) {
// looking for a start event based on an event-registry event subscription
List<ExtensionElement> eventTypeElements = startEvent.getExtensionElements().get(BpmnXMLConstants.ELEMENT_EVENT_TYPE);
if (eventTypeElements != null && eventTypeElements.size() > 0) {
// looking for a dynamic, manually subscribed behavior of the event-registry start event
List<ExtensionElement> correlationConfiguration = startEvent.getExtensionElements().get(BpmnXMLConstants.START_EVENT_CORRELATION_CONFIGURATION);
if (correlationConfiguration != null && correlationConfiguration.size() > 0 &&
BpmnXMLConstants.START_EVENT_CORRELATION_MANUAL.equals(correlationConfiguration.get(0).getElementText())) {
String eventDefinitionKey = eventTypeElements.get(0).getElementText();
String correlationKey = null;
|
if (builder.hasCorrelationParameterValues()) {
correlationKey = generateCorrelationConfiguration(eventDefinitionKey, builder.getTenantId(),
builder.getCorrelationParameterValues(), commandContext);
}
getEventSubscriptionService(commandContext).deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(builder.getProcessDefinitionId(),
eventDefinitionKey, startEvent.getId(), correlationKey);
}
}
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\DeleteProcessInstanceStartEventSubscriptionCmd.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_PInstance getAD_PInstance()
{
return get_ValueAsPO(COLUMNNAME_AD_PInstance_ID, org.compiere.model.I_AD_PInstance.class);
}
@Override
public void setAD_PInstance(final org.compiere.model.I_AD_PInstance AD_PInstance)
{
set_ValueFromPO(COLUMNNAME_AD_PInstance_ID, org.compiere.model.I_AD_PInstance.class, AD_PInstance);
}
@Override
public void setAD_PInstance_ID (final int AD_PInstance_ID)
{
if (AD_PInstance_ID < 1)
set_Value (COLUMNNAME_AD_PInstance_ID, null);
else
set_Value (COLUMNNAME_AD_PInstance_ID, AD_PInstance_ID);
}
@Override
public int getAD_PInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PInstance_ID);
}
@Override
public void setC_Async_Batch_ID (final int C_Async_Batch_ID)
{
if (C_Async_Batch_ID < 1)
set_Value (COLUMNNAME_C_Async_Batch_ID, null);
else
set_Value (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID);
}
@Override
public int getC_Async_Batch_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID);
}
|
@Override
public void setChunkUUID (final @Nullable java.lang.String ChunkUUID)
{
set_Value (COLUMNNAME_ChunkUUID, ChunkUUID);
}
@Override
public java.lang.String getChunkUUID()
{
return get_ValueAsString(COLUMNNAME_ChunkUUID);
}
@Override
public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule()
{
return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class);
}
@Override
public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule)
{
set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule);
}
@Override
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID);
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_Recompute.java
| 1
|
请完成以下Java代码
|
public static String post(String url, String parameters) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
String body = null;
if (method != null & parameters != null && !"".equals(parameters.trim())) {
try {
// 建立一个NameValuePair数组,用于存储欲传送的参数
method.addHeader("Content-type", "application/json; charset=utf-8");
method.setHeader("Accept", "application/json");
method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
HttpResponse response = httpClient.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return "1";// 返回1表示请求失败
|
}
// Read the response body
body = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// 网络错误
return "2";
} finally {
}
}
return body;
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\utils\RoncooHttpClientUtils.java
| 1
|
请完成以下Java代码
|
public class Play2048 {
private static final int SIZE = 4;
private static final int INITIAL_NUMBERS = 2;
public static void main(String[] args) {
// The board and players
Board board = new Board(SIZE);
Computer computer = new Computer();
Human human = new Human();
// The computer has two moves first
System.out.println("Setup");
System.out.println("=====");
for (int i = 0; i < INITIAL_NUMBERS; ++i) {
board = computer.makeMove(board);
}
printBoard(board);
do {
board = human.makeMove(board);
System.out.println("Human move");
System.out.println("==========");
printBoard(board);
board = computer.makeMove(board);
System.out.println("Computer move");
System.out.println("=============");
printBoard(board);
} while (!board.emptyCells().isEmpty());
System.out.println("Final Score: " + board.getScore());
}
private static void printBoard(Board board) {
StringBuilder topLines = new StringBuilder();
StringBuilder midLines = new StringBuilder();
for (int x = 0; x < board.getSize(); ++x) {
topLines.append("+--------");
midLines.append("| ");
}
topLines.append("+");
midLines.append("|");
|
for (int y = 0; y < board.getSize(); ++y) {
System.out.println(topLines);
System.out.println(midLines);
for (int x = 0; x < board.getSize(); ++x) {
Cell cell = new Cell(x, y);
System.out.print("|");
if (board.isEmpty(cell)) {
System.out.print(" ");
} else {
StringBuilder output = new StringBuilder(Integer.toString(board.getCell(cell)));
while (output.length() < 8) {
output.append(" ");
if (output.length() < 8) {
output.insert(0, " ");
}
}
System.out.print(output);
}
}
System.out.println("|");
System.out.println(midLines);
}
System.out.println(topLines);
System.out.println("Score: " + board.getScore());
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\play2048\Play2048.java
| 1
|
请完成以下Java代码
|
public class Salary implements Serializable {
private Long amount;
private String currency;
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
|
this.currency = currency;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Salary salary = (Salary) o;
return Objects.equals(amount, salary.amount) &&
Objects.equals(currency, salary.currency);
}
@Override
public int hashCode() {
return Objects.hash(amount, currency);
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\Salary.java
| 1
|
请完成以下Java代码
|
public int getC_UOM_ID()
{
return model.getC_UOM_ID();
}
public int getM_HU_PI_Item_Product_ID()
{
return Services.get(IPMMPurchaseCandidateBL.class).getM_HU_PI_Item_Product_Effective_ID(model);
}
public BigDecimal getQtyToOrder()
{
return model.getQtyToOrder();
}
public BigDecimal getQtyToOrder_TU()
{
return model.getQtyToOrder_TU();
}
public boolean isZeroQty()
{
return getQtyToOrder().signum() == 0
&& getQtyToOrder_TU().signum() == 0;
}
/**
*
* @return the <code>model</code>'s date promised value, truncated to "day".
*/
public Timestamp getDatePromised()
{
return TimeUtil.trunc(model.getDatePromised(), TimeUtil.TRUNC_DAY);
}
public Object getHeaderAggregationKey()
{
// the pricelist is no aggregation criterion, because
// the orderline's price is manually set, i.e. the pricing system is not invoked
// and we often want to combine candidates with C_Flatrate_Terms (-> no pricelist, price take from the term)
// and candidates without a term, where the candidate's price is computed by the pricing system
return Util.mkKey(getAD_Org_ID(),
getM_Warehouse_ID(),
getC_BPartner_ID(),
getDatePromised().getTime(),
|
getM_PricingSystem_ID(),
// getM_PriceList_ID(),
getC_Currency_ID());
}
/**
* This method is actually used by the item aggregation key builder of {@link OrderLinesAggregator}.
*
* @return
*/
public Object getLineAggregationKey()
{
return Util.mkKey(
getM_Product_ID(),
getAttributeSetInstanceId().getRepoId(),
getC_UOM_ID(),
getM_HU_PI_Item_Product_ID(),
getPrice());
}
/**
* Creates and {@link I_PMM_PurchaseCandidate} to {@link I_C_OrderLine} line allocation using the whole candidate's QtyToOrder.
*
* @param orderLine
*/
/* package */void createAllocation(final I_C_OrderLine orderLine)
{
Check.assumeNotNull(orderLine, "orderLine not null");
final BigDecimal qtyToOrder = getQtyToOrder();
final BigDecimal qtyToOrderTU = getQtyToOrder_TU();
//
// Create allocation
final I_PMM_PurchaseCandidate_OrderLine alloc = InterfaceWrapperHelper.newInstance(I_PMM_PurchaseCandidate_OrderLine.class, orderLine);
alloc.setC_OrderLine(orderLine);
alloc.setPMM_PurchaseCandidate(model);
alloc.setQtyOrdered(qtyToOrder);
alloc.setQtyOrdered_TU(qtyToOrderTU);
InterfaceWrapperHelper.save(alloc);
// NOTE: on alloc's save we expect the model's quantities to be updated
InterfaceWrapperHelper.markStaled(model); // FIXME: workaround because we are modifying the model from alloc's model interceptor
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PurchaseCandidate.java
| 1
|
请完成以下Java代码
|
public boolean isBefore()
{
return this == BEFORE_NEW
|| this == BEFORE_CHANGE
|| this == BEFORE_DELETE
|| this == BEFORE_DELETE_REPLICATION
|| this == BEFORE_SAVE_TRX;
}
public boolean isAfter()
{
return this == AFTER_NEW
|| this == AFTER_NEW_REPLICATION
|| this == AFTER_CHANGE
|| this == AFTER_CHANGE_REPLICATION
|
|| this == AFTER_DELETE;
}
public boolean isBeforeSaveTrx()
{
return this == BEFORE_SAVE_TRX;
}
public static boolean isBeforeSaveTrx(final TimingType timingType)
{
return timingType instanceof ModelChangeType
? ((ModelChangeType)timingType).isBeforeSaveTrx()
: false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModelChangeType.java
| 1
|
请完成以下Java代码
|
public void setP_WIP_A(org.compiere.model.I_C_ValidCombination P_WIP_A)
{
set_ValueFromPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, P_WIP_A);
}
/** Set Unfertige Leistungen.
@param P_WIP_Acct
Das Konto Unfertige Leistungen wird im Produktionaauftrag verwendet
*/
@Override
public void setP_WIP_Acct (int P_WIP_Acct)
{
set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct));
}
/** Get Unfertige Leistungen.
@return Das Konto Unfertige Leistungen wird im Produktionaauftrag verwendet
*/
@Override
public int getP_WIP_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
|
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Category_Acct.java
| 1
|
请完成以下Java代码
|
private Class<? extends IScriptExecutor> getScriptExecutorClass(final String dbType, final ScriptType scriptType)
{
for (final String currDbType : Arrays.asList(dbType, TYPE_ANY))
{
for (final ScriptType currScriptType : Arrays.asList(scriptType, null))
{
final ScriptExecutorKey key = ScriptExecutorKey.of(currDbType, currScriptType);
final Class<? extends IScriptExecutor> scriptExecutorClass = scriptExecutorClasses.get(key);
if (scriptExecutorClass != null)
{
return scriptExecutorClass;
}
}
}
return null;
}
@Override
public Set<ScriptType> getSupportedScriptTypes()
{
return ImmutableSet.copyOf(supportedScriptTypes);
}
@Override
public IScriptExecutor createScriptExecutor(final IDatabase targetDatabase, final IScript script)
{
return createScriptExecutor(targetDatabase, script.getType());
}
@Override
public IScriptExecutor createScriptExecutor(final IDatabase targetDatabase)
{
return createScriptExecutor(targetDatabase, ScriptType.SQL);
}
public IScriptExecutor createScriptExecutor(final IDatabase targetDatabase, final ScriptType scriptType)
{
final Class<? extends IScriptExecutor> scriptExecutorClass = getScriptExecutorClass(targetDatabase.getDbType(), scriptType);
if (scriptExecutorClass == null)
{
throw new ScriptException("No script executors found for " + scriptType)
.addParameter("Database", targetDatabase);
}
if (dryRunMode)
{
return new NullScriptExecutor(targetDatabase);
}
try
{
final IScriptExecutor executor = scriptExecutorClass.getConstructor(IDatabase.class).newInstance(targetDatabase);
return executor;
|
}
catch (final Exception e)
{
throw new ScriptException("Cannot instantiate executor class: " + scriptExecutorClass, e);
}
}
/**
* Enable/Disable dry run mode.
*
* If dry run mode is enabled then scripts won't be actually executed (i.e. {@link NullScriptExecutor} will be used)
*
* @param dryRunMode
*/
@Override
public void setDryRunMode(final boolean dryRunMode)
{
this.dryRunMode = dryRunMode;
}
/**
* @return true if dry run mode is enabled
* @see #setDryRunMode(boolean)
*/
@Override
public boolean isDryRunMode()
{
return dryRunMode;
}
@Value(staticConstructor = "of")
private static class ScriptExecutorKey
{
final String dbType;
final ScriptType scriptType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\executor\impl\DefaultScriptExecutorFactory.java
| 1
|
请完成以下Java代码
|
List<Integer> transform(List<Action> actions)
{
List<Integer> classes = new ArrayList<Integer>();
transform(actions, classes);
return classes;
}
void transform(List<Action> actions,
List<Integer> classes)
{
classes.clear();
for (int i = 0; i < actions.size(); ++i)
{
classes.add(transform(actions.get(i)));
}
}
/**
* 转换动作为动作id
* @param act 动作
* @return 动作类型的依存关系id
*/
int transform(Action act)
{
int deprel = 0;
int[] deprel_inference = new int[]{deprel};
if (ActionUtils.is_shift(act))
{
return 0;
}
else if (ActionUtils.is_left_arc(act, deprel_inference))
{
deprel = deprel_inference[0];
return 1 + deprel;
}
else if (ActionUtils.is_right_arc(act, deprel_inference))
{
deprel = deprel_inference[0];
return L + 1 + deprel;
}
else
{
System.err.printf("unknown transition in transform(Action): %d-%d", act.name(), act.rel());
|
}
return -1;
}
/**
* 转换动作id为动作
* @param act 动作类型的依存关系id
* @return 动作
*/
Action transform(int act)
{
if (act == 0)
{
return ActionFactory.make_shift();
}
else if (act < 1 + L)
{
return ActionFactory.make_left_arc(act - 1);
}
else if (act < 1 + 2 * L)
{
return ActionFactory.make_right_arc(act - 1 - L);
}
else
{
System.err.printf("unknown transition in transform(int): %d", act);
}
return new Action();
}
int number_of_transitions()
{
return L * 2 + 1;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\TransitionSystem.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractGatewayFilterFactory<C> extends AbstractConfigurable<C>
implements GatewayFilterFactory<C>, ApplicationEventPublisherAware {
private @Nullable ApplicationEventPublisher publisher;
@SuppressWarnings("unchecked")
public AbstractGatewayFilterFactory() {
super((Class<C>) Object.class);
}
public AbstractGatewayFilterFactory(Class<C> configClass) {
super(configClass);
}
protected @Nullable ApplicationEventPublisher getPublisher() {
return this.publisher;
}
protected void enableBodyCaching(@Nullable String routeId) {
if (routeId != null && getPublisher() != null) {
// send an event to enable caching
getPublisher().publishEvent(new EnableBodyCachingEvent(this, routeId));
}
}
@Override
|
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public static class NameConfig {
private @Nullable String name;
public @Nullable String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AbstractGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
@Override
public ScriptInfo getScriptInfo() {
return scriptInfo;
}
|
@Override
public void setScriptInfo(ScriptInfo scriptInfo) {
this.scriptInfo = scriptInfo;
}
@Override
public abstract AbstractFlowableHttpHandler clone();
public void setValues(AbstractFlowableHttpHandler otherHandler) {
super.setValues(otherHandler);
setImplementation(otherHandler.getImplementation());
setImplementationType(otherHandler.getImplementationType());
if (otherHandler.getScriptInfo() != null) {
setScriptInfo(otherHandler.getScriptInfo().clone());
}
fieldExtensions = new ArrayList<>();
if (otherHandler.getFieldExtensions() != null && !otherHandler.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherHandler.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\AbstractFlowableHttpHandler.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public Role() {
}
public Role(String name) {
this.name = name;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
|
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\model\Role.java
| 1
|
请完成以下Java代码
|
private void accessDeviceNTimes(final DeviceAccessor deviceAccessor, final int times)
{
IntStream.rangeClosed(1, times)
.forEach(time -> accessDevice(deviceAccessor, time));
}
private void accessDevice(final DeviceAccessor deviceAccessor, final int time)
{
logger.info("Accessing({}) {}", time, deviceAccessor);
countDevicesChecked++;
final Stopwatch stopwatch = Stopwatch.createStarted();
try
{
logger.debug("Getting response from {}", deviceAccessor);
|
final Object value = deviceAccessor.acquireValue();
logger.debug("Got respose from {}: {}", deviceAccessor, value);
addLog("OK(" + time + "): accessed " + deviceAccessor + " and got '" + value + "' in " + stopwatch);
}
catch (final Exception ex)
{
final String errmsg = "Error(" + time + "): Failed accessing " + deviceAccessor + ": " + ex.getLocalizedMessage();
addLog(errmsg);
logger.warn(errmsg, ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\adempiere\process\CheckAttributeAttachedDevices.java
| 1
|
请完成以下Java代码
|
public class ResourceRoleImpl extends BaseElementImpl implements ResourceRole {
protected static Attribute<String> nameAttribute;
protected static ElementReference<Resource, ResourceRef> resourceRefChild;
protected static ChildElementCollection<ResourceParameterBinding> resourceParameterBindingCollection;
protected static ChildElement<ResourceAssignmentExpression> resourceAssignmentExpressionChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ResourceRole.class, BPMN_ELEMENT_RESOURCE_ROLE)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ResourceRole>() {
public ResourceRole newInstance(ModelTypeInstanceContext instanceContext) {
return new ResourceRoleImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
resourceRefChild = sequenceBuilder.element(ResourceRef.class)
.qNameElementReference(Resource.class)
.build();
resourceParameterBindingCollection = sequenceBuilder.elementCollection(ResourceParameterBinding.class)
.build();
resourceAssignmentExpressionChild = sequenceBuilder.element(ResourceAssignmentExpression.class)
.build();
typeBuilder.build();
}
public ResourceRoleImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
|
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public Resource getResource() {
return resourceRefChild.getReferenceTargetElement(this);
}
public void setResource(Resource resource) {
resourceRefChild.setReferenceTargetElement(this, resource);
}
public Collection<ResourceParameterBinding> getResourceParameterBinding() {
return resourceParameterBindingCollection.get(this);
}
public ResourceAssignmentExpression getResourceAssignmentExpression() {
return resourceAssignmentExpressionChild.getChild(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ResourceRoleImpl.java
| 1
|
请完成以下Java代码
|
private Quantity computeQuantityForHuPPOrderLineRow(
@NonNull final I_PP_Order_Qty ppOrderQty,
@NonNull final HUEditorRow huEditorRow,
@Nullable final HUEditorRow parentHUEditorRow)
{
if (huEditorRow.isHUStatusDestroyed())
{
// Top level HU which was already destroyed (i.e. it was already issued & processed)
// => get the Qty/UOM from PP_Order_Qty because on HU level, for sure it will be ZERO.
if (parentHUEditorRow == null)
{
return Quantity.of(ppOrderQty.getQty(), IHUPPOrderQtyBL.extractUOM(ppOrderQty));
}
// Included HU which was already destroyed
// => we don't know the Qty
else
{
return Quantity.zero(huEditorRow.getC_UOM());
}
}
else
{
final Quantity qtyCU = huEditorRow.getQtyCUAsQuantity();
if (qtyCU == null)
{
final I_C_UOM uom = IHUPPOrderQtyBL.extractUOM(ppOrderQty);
return Quantity.zero(uom);
}
else
{
|
return qtyCU;
}
}
}
private PPOrderLineRow createRowForSourceHU(@NonNull final HUEditorRow huEditorRow)
{
final PPOrderLineRowId rowId = PPOrderLineRowId.ofSourceHU(huEditorRow.getId(), huEditorRow.getHuId());
return PPOrderLineRow.builderForSourceHU()
.rowId(rowId)
.type(PPOrderLineType.ofHUEditorRowType(huEditorRow.getType()))
.huId(huEditorRow.getHuId())
.attributesSupplier(huEditorRow.getAttributesSupplier()
.map(supplier -> supplier.changeRowId(rowId.toDocumentId()))
.orElse(null))
.code(huEditorRow.getValue())
.product(huEditorRow.getProduct())
.packingInfo(huEditorRow.getPackingInfo())
.uom(huEditorRow.getUOM())
.qty(huEditorRow.getQtyCUAsQuantity())
.huStatus(huEditorRow.getHUStatusDisplay())
.topLevelHU(huEditorRow.isTopLevel())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesViewDataLoader.java
| 1
|
请完成以下Java代码
|
public boolean shouldFilter() {
return RequestContext.getCurrentContext().getRequest().getRequestURI().endsWith(Swagger2Controller.DEFAULT_URL);
}
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
context.getResponse().setCharacterEncoding("UTF-8");
String rewrittenResponse = rewriteBasePath(context);
if (context.getResponseGZipped()) {
try {
context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse)));
} catch (IOException e) {
log.error("Swagger-docs filter error", e);
}
} else {
context.setResponseBody(rewrittenResponse);
}
return null;
}
@SuppressWarnings("unchecked")
private String rewriteBasePath(RequestContext context) {
InputStream responseDataStream = context.getResponseDataStream();
String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();
try {
if (context.getResponseGZipped()) {
responseDataStream = new GZIPInputStream(context.getResponseDataStream());
}
String response = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
if (response != null) {
LinkedHashMap<String, Object> map = this.mapper.readValue(response, LinkedHashMap.class);
|
String basePath = requestUri.replace(Swagger2Controller.DEFAULT_URL, "");
map.put("basePath", basePath);
log.debug("Swagger-docs: rewritten Base URL with correct micro-service route: {}", basePath);
return mapper.writeValueAsString(map);
}
} catch (IOException e) {
log.error("Swagger-docs filter error", e);
}
return null;
}
public static byte[] gzipData(String content) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter gzip = new PrintWriter(new GZIPOutputStream(bos));
gzip.print(content);
gzip.flush();
gzip.close();
return bos.toByteArray();
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\responserewriting\SwaggerBasePathRewritingFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Foo findById(@PathVariable("id") final Long id) {
return RestPreconditions.checkFound(service.findById(id));
}
// read - all
@GetMapping
public List<Foo> findAll() {
return service.findAll();
}
// write
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Foo create(@RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
return service.create(resource);
}
|
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findById(resource.getId()));
service.update(resource);
}
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) {
service.deleteById(id);
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest-simple\src\main\java\com\baeldung\web\controller\FooController.java
| 2
|
请完成以下Java代码
|
public static void main(String[] args) {
new SpringApplicationBuilder(ReportDesignApplication.class).web(WebApplicationType.NONE).build().run(args);
}
@Override public void run(String... args) throws Exception {
buildReport();
}
private void buildReport() throws IOException, BirtException {
final DesignConfig config = new DesignConfig();
final IDesignEngine engine;
try {
Platform.startup(config);
IDesignEngineFactory factory = (IDesignEngineFactory) Platform
.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);
engine = factory.createDesignEngine(config);
} catch (Exception ex) {
log.error("Exception during creation of DesignEngine", ex);
throw ex;
}
SessionHandle session = engine.newSessionHandle(ULocale.ENGLISH);
ReportDesignHandle design = session.createDesign();
design.setTitle("Sample Report");
// The element factory creates instances of the various BIRT elements.
ElementFactory factory = design.getElementFactory();
// Create a simple master page that describes how the report will
// appear when printed.
//
// Note: The report will fail to load in the BIRT designer
// unless you create a master page.
DesignElementHandle element = factory.newSimpleMasterPage("Page Master"); //$NON-NLS-1$
design.getMasterPages().add(element);
// Create a grid
GridHandle grid = factory.newGridItem(null, 2 /* cols */, 1 /* row */);
design.getBody().add(grid);
grid.setWidth("100%");
|
RowHandle row0 = (RowHandle) grid.getRows().get(0);
// Create an image and add it to the first cell.
ImageHandle image = factory.newImage(null);
CellHandle cell = (CellHandle) row0.getCells().get(0);
cell.getContent().add(image);
image.setURL("\"https://www.baeldung.com/wp-content/themes/baeldung/favicon/favicon-96x96.png\"");
// Create a label and add it to the second cell.
LabelHandle label = factory.newLabel(null);
cell = (CellHandle) row0.getCells().get(1);
cell.getContent().add(label);
label.setText("Hello, Baeldung world!");
// Save the design and close it.
File report = new File(REPORTS_FOLDER);
report.mkdirs();
design.saveAs(new File(report, "static_report.rptdesign").getAbsolutePath());
design.close();
log.info("Report generated");
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-birt\src\main\java\com\baeldung\birt\designer\ReportDesignApplication.java
| 1
|
请完成以下Java代码
|
public JsonPersisterService createPersister()
{
final String identifier = "persister_" + UIDStringUtil.createNext();
final JsonRetrieverService jsonRetrieverService = createRetrieverService(identifier);
return new JsonPersisterService(
jsonRetrieverService,
jsonRequestConsolidateService,
bpartnerCompositeRepository,
bpGroupRepository,
bpGroupService,
currencyRepository,
externalReferenceService,
identifier);
}
|
public JsonRetrieverService createRetriever()
{
final String identifier = "retriever_" + UIDStringUtil.createNext();
return createRetrieverService(identifier);
}
private JsonRetrieverService createRetrieverService(@NonNull final String identifier)
{
return new JsonRetrieverService(
bpartnerQueryService,
bpartnerCompositeRepository,
bpGroupRepository,
greetingRepository,
identifier);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\JsonServiceFactory.java
| 1
|
请完成以下Java代码
|
public Builder filterDescriptors(@NonNull final DocumentFilterDescriptorsProvider filterDescriptors)
{
this.filterDescriptors = filterDescriptors;
return this;
}
private DocumentFilterDescriptorsProvider getViewFilterDescriptors()
{
return filterDescriptors;
}
private SqlDocumentFilterConvertersList buildViewFilterConverters()
{
return filterConverters.build();
}
public Builder filterConverter(@NonNull final SqlDocumentFilterConverter converter)
{
filterConverters.converter(converter);
return this;
}
public Builder filterConverters(@NonNull final List<SqlDocumentFilterConverter> converters)
{
filterConverters.converters(converters);
return this;
}
public Builder rowIdsConverter(@NonNull final SqlViewRowIdsConverter rowIdsConverter)
{
this.rowIdsConverter = rowIdsConverter;
return this;
}
private SqlViewRowIdsConverter getRowIdsConverter()
{
if (rowIdsConverter != null)
{
return rowIdsConverter;
}
if (groupingBinding != null)
{
return groupingBinding.getRowIdsConverter();
}
return SqlViewRowIdsConverters.TO_INT_STRICT;
}
public Builder groupingBinding(final SqlViewGroupingBinding groupingBinding)
{
this.groupingBinding = groupingBinding;
|
return this;
}
public Builder filterConverterDecorator(@NonNull final SqlDocumentFilterConverterDecorator sqlDocumentFilterConverterDecorator)
{
this.sqlDocumentFilterConverterDecorator = sqlDocumentFilterConverterDecorator;
return this;
}
public Builder rowCustomizer(final ViewRowCustomizer rowCustomizer)
{
this.rowCustomizer = rowCustomizer;
return this;
}
private ViewRowCustomizer getRowCustomizer()
{
return rowCustomizer;
}
public Builder viewInvalidationAdvisor(@NonNull final IViewInvalidationAdvisor viewInvalidationAdvisor)
{
this.viewInvalidationAdvisor = viewInvalidationAdvisor;
return this;
}
private IViewInvalidationAdvisor getViewInvalidationAdvisor()
{
return viewInvalidationAdvisor;
}
public Builder refreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents)
{
this.refreshViewOnChangeEvents = refreshViewOnChangeEvents;
return this;
}
public Builder queryIfNoFilters(final boolean queryIfNoFilters)
{
this.queryIfNoFilters = queryIfNoFilters;
return this;
}
public Builder includedEntitiesDescriptors(final Map<DetailId, SqlDocumentEntityDataBindingDescriptor> includedEntitiesDescriptors)
{
this.includedEntitiesDescriptors = includedEntitiesDescriptors;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewBinding.java
| 1
|
请完成以下Java代码
|
public ImmutableList<I_M_HU> cusToExistingTU(
@NonNull final List<I_M_HU> sourceCuHUs,
@NonNull final I_M_HU targetTuHU)
{
final ImmutableList.Builder<I_M_HU> resultCollector = ImmutableList.builder();
sourceCuHUs.forEach(sourceCU -> {
final Quantity quantity = getSingleProductStorage(sourceCU).getQtyInStockingUOM();
resultCollector.addAll(cuToExistingTU(sourceCU, quantity, targetTuHU));
});
return resultCollector.build();
}
public void cusToExistingCU(@NonNull final List<I_M_HU> sourceCuHUs, @NonNull final I_M_HU targetCU)
{
sourceCuHUs.forEach(sourceCU -> cuToExistingCU(sourceCU, targetCU));
}
private void cuToExistingCU(@NonNull final I_M_HU sourceCuHU, @NonNull final I_M_HU targetHU)
{
trxManager.runInThreadInheritedTrx(() -> cuToExistingCU_InTrx(sourceCuHU, targetHU));
}
private void cuToExistingCU_InTrx(
@NonNull final I_M_HU sourceCuHU,
@NonNull final I_M_HU targetHU)
{
final IMutableHUContext huContextWithOrgId = huContextFactory.createMutableHUContext(InterfaceWrapperHelper.getContextAware(targetHU));
final List<IHUProductStorage> productStorages = huContext.getHUStorageFactory()
.getStorage(targetHU)
.getProductStorages();
if (productStorages.size() > 1)
{
throw new AdempiereException("CUs with more than one product are not supported!");
}
|
final IAllocationSource source = HUListAllocationSourceDestination
.of(sourceCuHU, AllocationStrategyType.UNIFORM)
.setDestroyEmptyHUs(true);
final IAllocationDestination destination = HUListAllocationSourceDestination.of(targetHU, AllocationStrategyType.UNIFORM);
final IHUProductStorage sourceProductStorage = getSingleProductStorage(sourceCuHU);
final ProductId targetHUProductId = productStorages.isEmpty()
? sourceProductStorage.getProductId()
: productStorages.get(0).getProductId();
Check.assume(sourceProductStorage.getProductId().equals(targetHUProductId), "Source and Target HU productId must match!");
HULoader.of(source, destination)
.load(AllocationUtils.builder()
.setHUContext(huContextWithOrgId)
.setDateAsToday()
.setProduct(sourceProductStorage.getProductId())
.setQuantity(sourceProductStorage.getQtyInStockingUOM())
.setFromReferencedModel(sourceCuHU)
.setForceQtyAllocation(true)
.create());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\HUTransformService.java
| 1
|
请完成以下Java代码
|
protected VirtualFile getFile(URL processesXmlResource) throws DeploymentUnitProcessingException {
try {
return VFS.getChild(processesXmlResource.toURI());
} catch(Exception e) {
throw new DeploymentUnitProcessingException(e);
}
}
protected boolean isEmptyFile(URL url) {
InputStream inputStream = null;
try {
inputStream = url.openStream();
return inputStream.available() == 0;
} catch (IOException e) {
throw new ProcessEngineException("Could not open stream for " + url, e);
} finally {
IoUtil.closeSilently(inputStream);
|
}
}
protected ProcessesXml parseProcessesXml(URL url) {
final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser();
ProcessesXml processesXml = processesXmlParser.createParse()
.sourceUrl(url)
.execute()
.getProcessesXml();
return processesXml;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessesXmlProcessor.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public BigDecimal getDiscount() {
return discount;
}
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
|
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", count=").append(count);
sb.append(", discount=").append(discount);
sb.append(", price=").append(price);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductLadder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CarrierProductRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<String, CarrierProduct> carrierProductsByExternalId = CCache.newLRUCache(I_Carrier_Product.Table_Name + "#by#M_Shipper_ID#ExternalId", 100, 0);
private final CCache<String, CarrierProduct> carrierProductsById = CCache.newLRUCache(I_Carrier_Product.Table_Name + "#byId", 100, 0);
private static CarrierProduct fromProductRecord(@NotNull final I_Carrier_Product product)
{
return CarrierProduct.builder()
.id(CarrierProductId.ofRepoId(product.getCarrier_Product_ID()))
.code(product.getExternalId())
.name(product.getName())
.build();
}
@NonNull
public CarrierProduct getOrCreateCarrierProduct(@NonNull final ShipperId shipperId, @NonNull final String code, @NonNull final String name)
{
final CarrierProduct cachedShipperProductByCode = getCachedShipperProductByCode(shipperId, code);
if (cachedShipperProductByCode != null)
{
return cachedShipperProductByCode;
}
return createShipperProduct(shipperId, code, name);
}
@Nullable
private CarrierProduct getCachedShipperProductByCode(@NonNull final ShipperId shipperId, @Nullable final String code)
{
if (code == null)
{
return null;
}
return carrierProductsByExternalId.getOrLoad(shipperId + code, () ->
queryBL.createQueryBuilder(I_Carrier_Product.class)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_ExternalId, code)
.firstOptional()
.map(CarrierProductRepository::fromProductRecord)
.orElse(null));
}
|
@Nullable
public CarrierProduct getCachedShipperProductById(@Nullable final CarrierProductId productId)
{
if (productId == null)
{
return null;
}
return carrierProductsById.getOrLoad(productId.toString(), () ->
queryBL.createQueryBuilder(I_Carrier_Product.class)
.addEqualsFilter(I_Carrier_Product.COLUMNNAME_Carrier_Product_ID, productId)
.firstOptional()
.map(CarrierProductRepository::fromProductRecord)
.orElse(null));
}
@NonNull
private CarrierProduct createShipperProduct(@NonNull final ShipperId shipperId, @NonNull final String code, @NonNull final String name)
{
final I_Carrier_Product po = InterfaceWrapperHelper.newInstance(I_Carrier_Product.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(code);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromProductRecord(po);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierProductRepository.java
| 2
|
请完成以下Java代码
|
public class ServiceTaskConnectorActivityBehavior extends TaskActivityBehavior {
/** the id of the connector */
protected String connectorId;
/** cached connector instance for this activity.
* Will be initialized after the first execution of this activity. */
protected Connector<?> connectorInstance;
/** the local ioMapping for this connector. */
protected IoMapping ioMapping;
public ServiceTaskConnectorActivityBehavior(String connectorId, IoMapping ioMapping) {
this.connectorId = connectorId;
this.ioMapping = ioMapping;
}
public void execute(final ActivityExecution execution) throws Exception {
ensureConnectorInitialized();
executeWithErrorPropagation(execution, new Callable<Void>() {
@Override
public Void call() throws Exception {
ConnectorRequest<?> request = connectorInstance.createRequest();
applyInputParameters(execution, request);
// execute the request and obtain a response:
ConnectorResponse response = request.execute();
applyOutputParameters(execution, response);
leave(execution);
return null;
}
});
}
protected void applyInputParameters(ActivityExecution execution, ConnectorRequest<?> request) {
if(ioMapping != null) {
// create variable scope for input parameters
ConnectorVariableScope connectorInputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution);
// execute the connector input parameters
ioMapping.executeInputParameters(connectorInputVariableScope);
// write the local variables to the request.
connectorInputVariableScope.writeToRequest(request);
}
}
protected void applyOutputParameters(ActivityExecution execution, ConnectorResponse response) {
if(ioMapping != null) {
|
// create variable scope for output parameters
ConnectorVariableScope connectorOutputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution);
// read parameters from response
connectorOutputVariableScope.readFromResponse(response);
// map variables to parent scope.
ioMapping.executeOutputParameters(connectorOutputVariableScope);
}
}
protected void ensureConnectorInitialized() {
if(connectorInstance == null) {
synchronized (this) {
if(connectorInstance == null) {
connectorInstance = Connectors.getConnector(connectorId);
if (connectorInstance == null) {
throw new ConnectorException("No connector found for connector id '" + connectorId + "'");
}
}
}
}
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ServiceTaskConnectorActivityBehavior.java
| 1
|
请完成以下Java代码
|
private static final class Pattern
{
private static final int BUFSIZE = 255;
/** Offsets to {} expressions */
private final int[] offsets;
/** Keys enclosed by {} brackets */
private final String[] arguments;
/** Max used offset */
private int maxOffset;
private final String patternPrepared;
public Pattern(final String patternStr, final String leftDelimiter, final String rightDelimiter, final boolean exactMatch)
{
super();
int idx = 0;
int offnum = -1;
final StringBuffer outpat = new StringBuffer();
offsets = new int[BUFSIZE];
arguments = new String[BUFSIZE];
maxOffset = -1;
while (true)
{
int rightDelimiterIdx = -1;
final int leftDelimiterIdx = patternStr.indexOf(leftDelimiter, idx);
if (leftDelimiterIdx >= 0)
{
rightDelimiterIdx = patternStr.indexOf(rightDelimiter, leftDelimiterIdx + leftDelimiter.length());
}
else
{
break;
}
if (++offnum >= BUFSIZE)
{
throw new IllegalArgumentException("TooManyArguments");
}
if (rightDelimiterIdx < 0)
{
if (exactMatch)
{
throw new IllegalArgumentException("UnmatchedBraces");
}
else
{
break;
}
}
outpat.append(patternStr.substring(idx, leftDelimiterIdx));
offsets[offnum] = outpat.length();
arguments[offnum] = patternStr.substring(leftDelimiterIdx + leftDelimiter.length(), rightDelimiterIdx);
idx = rightDelimiterIdx + rightDelimiter.length();
maxOffset++;
|
}
outpat.append(patternStr.substring(idx));
patternPrepared = outpat.toString();
}
public String substring(final int beginIndex, final int endIndex)
{
return patternPrepared.substring(beginIndex, endIndex);
}
public int length()
{
return patternPrepared.length();
}
public int getMaxOffset()
{
return maxOffset;
}
public int getOffsetIndex(final int i)
{
return offsets[i];
}
public String getArgument(final int i)
{
return arguments[i];
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\util\MapFormat.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<byte[]> getUserAvatar(
@PathVariable("token") final String token,
@RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth,
@RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight)
{
final I_AD_User user = usersService.getByPasswordResetCode(token);
final WebuiImageId avatarId = WebuiImageId.ofRepoIdOrNull(user.getAvatar_ID());
if (avatarId == null)
{
return imageService.getEmptyImage();
}
return imageService.getWebuiImage(avatarId, maxWidth, maxHeight)
.toResponseEntity();
}
@PostMapping("/resetPassword/{token}")
|
public JSONLoginAuthResponse resetPasswordComplete(
@PathVariable("token") final String token,
@RequestBody final JSONResetPasswordCompleteRequest request)
{
userSession.assertNotLoggedIn();
if (!Objects.equals(token, request.getToken()))
{
throw new AdempiereException("@Invalid@ @PasswordResetCode@");
}
final I_AD_User user = usersService.resetPassword(token, request.getPassword());
final String username = usersService.extractUserLogin(user);
final HashableString password = usersService.extractUserPassword(user);
return authenticate(username, password, null);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\login\LoginRestController.java
| 1
|
请完成以下Java代码
|
public Builder range(@Nullable final TimeRange range)
{
this.range = range;
return this;
}
@Nullable
public TimeRange getRange()
{
return range;
}
public Builder datasetsComputeDuration(@Nullable final Duration datasetsComputeDuration)
{
this.datasetsComputeDuration = datasetsComputeDuration;
return this;
}
public void putValue(
@NonNull final String dataSetName,
@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey,
@NonNull final String fieldName,
@NonNull final KPIDataValue value)
{
dataSet(dataSetName).putValue(dataSetValueKey, fieldName, value);
}
public void putValueIfAbsent(
@NonNull final String dataSetName,
@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey,
|
@NonNull final String fieldName,
@NonNull final KPIDataValue value)
{
dataSet(dataSetName).putValueIfAbsent(dataSetValueKey, fieldName, value);
}
public Builder error(@NonNull final Exception exception)
{
final ITranslatableString errorMessage = AdempiereException.isUserValidationError(exception)
? AdempiereException.extractMessageTrl(exception)
: TranslatableStrings.adMessage(MSG_FailedLoadingKPI);
this.error = WebuiError.of(exception, errorMessage);
return this;
}
public Builder error(@NonNull final ITranslatableString errorMessage)
{
this.error = WebuiError.of(errorMessage);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataResult.java
| 1
|
请完成以下Java代码
|
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Teacher() {
}
public Teacher(Integer id, String name, String idCard, String tel, String email, String password) {
this.id = id;
this.name = name;
|
this.idCard = idCard;
this.tel = tel;
this.email = email;
this.password = password;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
", idCard='" + idCard + '\'' +
", tel='" + tel + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
}
|
repos\springboot-demo-master\desensitization\src\main\java\com\et\desensization\dto\Teacher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Map<String, String> createCookiesMap(Cookie[] cookies) {
Map<String, String> cookiesMap = new HashMap<>();
if (cookies != null) {
for (Cookie cookie : cookies) {
String id = cookie.getDomain() + ":" + cookie.getName();
cookiesMap.put(id, cookie.toString());
}
}
return cookiesMap;
}
private Map<String, List<String>> createHeaderMap(HttpServletRequest request) {
Map<String, List<String>> headers = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
List<String> headerValues = new ArrayList<>();
|
String headerName = headerNames.nextElement();
Enumeration<String> values = request.getHeaders(headerName);
while (values.hasMoreElements()) {
headerValues.add(values.nextElement());
}
headers.put(headerName, headerValues);
}
}
return headers;
}
private String createRemoteInfo(HttpServletRequest request) {
return request.getRemoteHost() + ":" + request.getRemotePort();
}
}
|
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\controller\DataServiceController.java
| 2
|
请完成以下Java代码
|
public SetRemovalTimeToHistoricBatchesBuilder byQuery(HistoricBatchQuery query) {
this.query = query;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder byIds(String... ids) {
this.ids = ids != null ? Arrays.asList(ids) : null;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder absoluteRemovalTime(Date removalTime) {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
this.mode = Mode.ABSOLUTE_REMOVAL_TIME;
this.removalTime = removalTime;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder calculatedRemovalTime() {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
this.mode = Mode.CALCULATED_REMOVAL_TIME;
return this;
}
public SetRemovalTimeToHistoricBatchesBuilder clearedRemovalTime() {
ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode);
mode = Mode.CLEARED_REMOVAL_TIME;
return this;
}
public Batch executeAsync() {
return commandExecutor.execute(new SetRemovalTimeToHistoricBatchesCmd(this));
}
public HistoricBatchQuery getQuery() {
return query;
}
public List<String> getIds() {
|
return ids;
}
public Date getRemovalTime() {
return removalTime;
}
public Mode getMode() {
return mode;
}
public enum Mode
{
CALCULATED_REMOVAL_TIME,
ABSOLUTE_REMOVAL_TIME,
CLEARED_REMOVAL_TIME;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricBatchesBuilderImpl.java
| 1
|
请完成以下Java代码
|
public Builder traceEnhancer(ScriptTraceEnhancer enhancer) {
this.traceEnhancer = enhancer;
return this;
}
public ScriptEngineRequest build() {
if (script == null || script.isEmpty()) {
throw new FlowableIllegalStateException("A script is required");
}
return new ScriptEngineRequest(script,
language,
scopeContainer,
inputVariableContainer != null ? inputVariableContainer : scopeContainer,
storeScriptVariables,
additionalResolvers,
traceEnhancer);
}
}
private ScriptEngineRequest(String script,
String language,
VariableContainer scopeContainer,
VariableContainer inputVariableContainer,
boolean storeScriptVariables,
List<Resolver> additionalResolvers,
ScriptTraceEnhancer errorTraceEnhancer) {
this.script = script;
this.language = language;
this.scopeContainer = scopeContainer;
this.inputVariableContainer = inputVariableContainer;
this.storeScriptVariables = storeScriptVariables;
this.additionalResolvers = additionalResolvers;
this.traceEnhancer = errorTraceEnhancer;
}
/**
* @see Builder#(String)
*/
public String getLanguage() {
return language;
}
/**
* @see Builder#(String)
*/
public String getScript() {
return script;
}
/**
* @see Builder#scopeContainer(VariableContainer)
|
*/
public VariableContainer getScopeContainer() {
return scopeContainer;
}
/**
* @see Builder#inputVariableContainer(VariableContainer)
*/
public VariableContainer getInputVariableContainer() {
return inputVariableContainer;
}
/**
* @see Builder#storeScriptVariables
*/
public boolean isStoreScriptVariables() {
return storeScriptVariables;
}
/**
* @see Builder#additionalResolver(Resolver)
*/
public List<Resolver> getAdditionalResolvers() {
return additionalResolvers;
}
/**
* @see Builder#traceEnhancer(ScriptTraceEnhancer)
*/
public ScriptTraceEnhancer getTraceEnhancer() {
return traceEnhancer;
}
@Override
public String toString() {
return new StringJoiner(", ", ScriptEngineRequest.class.getSimpleName() + "[", "]")
.add("language='" + language + "'")
.add("script='" + script + "'")
.add("variableContainer=" + scopeContainer)
.add("storeScriptVariables=" + storeScriptVariables)
.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptEngineRequest.java
| 1
|
请完成以下Java代码
|
public BatchStatisticsQuery withFailures() {
this.hasFailure = true;
return this;
}
@Override
public BatchStatisticsQuery withoutFailures() {
this.hasFailure = false;
return this;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public BatchStatisticsQuery orderById() {
return orderBy(BatchQueryProperty.ID);
}
@Override
public BatchStatisticsQuery orderByTenantId() {
return orderBy(BatchQueryProperty.TENANT_ID);
}
@Override
public BatchStatisticsQuery orderByStartTime() {
return orderBy(BatchQueryProperty.START_TIME);
}
|
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getStatisticsManager()
.getStatisticsCountGroupedByBatch(this);
}
public List<BatchStatistics> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getStatisticsManager()
.getStatisticsGroupedByBatch(this, page);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchStatisticsQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static OAuth2User getOAuth2User(String email, Map<String, Object> attributes, OAuth2MapperConfig config) {
OAuth2User oauth2User = new OAuth2User();
oauth2User.setEmail(email);
oauth2User.setTenantName(getTenantName(email, attributes, config));
if (!StringUtils.isEmpty(config.getBasic().getLastNameAttributeKey())) {
String lastName = getStringAttributeByKey(attributes, config.getBasic().getLastNameAttributeKey());
oauth2User.setLastName(lastName);
}
if (!StringUtils.isEmpty(config.getBasic().getFirstNameAttributeKey())) {
String firstName = getStringAttributeByKey(attributes, config.getBasic().getFirstNameAttributeKey());
oauth2User.setFirstName(firstName);
}
if (!StringUtils.isEmpty(config.getBasic().getCustomerNamePattern())) {
StrSubstitutor sub = new StrSubstitutor(attributes, START_PLACEHOLDER_PREFIX, END_PLACEHOLDER_PREFIX);
String customerName = sub.replace(config.getBasic().getCustomerNamePattern());
oauth2User.setCustomerName(customerName);
}
oauth2User.setAlwaysFullScreen(config.getBasic().isAlwaysFullScreen());
if (!StringUtils.isEmpty(config.getBasic().getDefaultDashboardName())) {
oauth2User.setDefaultDashboardName(config.getBasic().getDefaultDashboardName());
}
return oauth2User;
}
|
public static String getTenantName(String email, Map<String, Object> attributes, OAuth2MapperConfig config) {
switch (config.getBasic().getTenantNameStrategy()) {
case EMAIL:
return email;
case DOMAIN:
return email.substring(email .indexOf("@") + 1);
case CUSTOM:
StrSubstitutor sub = new StrSubstitutor(attributes, START_PLACEHOLDER_PREFIX, END_PLACEHOLDER_PREFIX);
return sub.replace(config.getBasic().getTenantNamePattern());
default:
throw new RuntimeException("Tenant Name Strategy with type " + config.getBasic().getTenantNameStrategy() + " is not supported!");
}
}
public static String getStringAttributeByKey(Map<String, Object> attributes, String key) {
String result = null;
try {
result = (String) attributes.get(key);
} catch (Exception e) {
log.warn("Can't convert attribute to String by key " + key);
}
return result;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\BasicMapperUtils.java
| 2
|
请完成以下Java代码
|
public IAutoCloseable temporaryDisableCache()
{
final Boolean noCachePrev = noCacheRef.get();
noCacheRef.set(Boolean.TRUE);
return new IAutoCloseable()
{
boolean closed = false;
@Override
public void close()
{
if (closed)
{
return;
}
closed = true;
noCacheRef.set(noCachePrev);
}
};
}
|
private static boolean isApplicationDictionaryCache(@NonNull final String cacheName, @NonNull final ImmutableSet<CacheLabel> labels)
{
final boolean anyApplicationDictionaryTableNames = labels.stream().anyMatch(CacheLabel::isApplicationDictionaryTableName);
if (!anyApplicationDictionaryTableNames)
{
return false;
}
final boolean anyNonApplicationDictionaryTableNames = labels.stream().anyMatch(label -> isNonApplicationDictionaryTableName(label, cacheName));
return !anyNonApplicationDictionaryTableNames;
}
private static boolean isNonApplicationDictionaryTableName(@NonNull final CacheLabel label, @NonNull final String cacheName)
{
return !label.equalsByName(cacheName) //ignore the label created from this.cacheName as it's not necessary a table name
&& !label.containsNoTableNameMarker()
&& !label.isApplicationDictionaryTableName();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\ThreadLocalCacheController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BookstoreService {
private final AuthorAnthologyViewRepository authorAnthologyViewRepository;
public BookstoreService(AuthorAnthologyViewRepository authorAnthologyViewRepository) {
this.authorAnthologyViewRepository = authorAnthologyViewRepository;
}
// Works
public void insertAnthologyAuthorInView() {
AuthorAnthologyView author = new AuthorAnthologyView();
author.setName("Mark Powell");
author.setGenre("Anthology");
author.setAge(45);
|
authorAnthologyViewRepository.save(author);
}
// Doesn't work
// WITH CHECK OPTION doesn't allow this insert
// expect to see: java.sql.SQLException: CHECK OPTION failed 'bookstoredb.author_anthology_view'
public void insertHistoryAuthorInView() {
AuthorAnthologyView author = new AuthorAnthologyView();
author.setName("Mark Powell");
author.setGenre("History"); // this field doesn't pass the check
author.setAge(45);
authorAnthologyViewRepository.save(author);
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseViewWithCheckOption\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
protected boolean isValidEvent(FlowableEvent event) {
boolean valid = false;
if (event instanceof FlowableEntityEvent) {
if (entityClass == null) {
valid = true;
} else {
valid = entityClass.isAssignableFrom(((FlowableEntityEvent) event).getEntity().getClass());
}
}
return valid;
}
/**
* Called when an entity create event is received.
*/
protected void onCreate(FlowableEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity initialized event is received.
*/
protected void onInitialized(FlowableEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an entity delete event is received.
*/
protected void onDelete(FlowableEvent event) {
// Default implementation is a NO-OP
}
|
/**
* Called when an entity update event is received.
*/
protected void onUpdate(FlowableEvent event) {
// Default implementation is a NO-OP
}
/**
* Called when an event is received, which is not a create, an update or delete.
*/
protected void onEntityEvent(FlowableEvent event) {
// Default implementation is a NO-OP
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\delegate\event\BaseEntityEventListener.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.