instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public E getItemToSelect() { return itemToSelect; } public void setTextToSet(String textToSet) { this.textToSet = textToSet; this.doSetText = true; } public boolean isDoSetText() { return doSetText; } public String getTextToSet() { return textToSet; }
public void setHighlightTextStartPosition(int highlightTextStartPosition) { this.highlightTextStartPosition = highlightTextStartPosition; this.doHighlightText = true; } public boolean isDoHighlightText() { return doHighlightText; } public int getHighlightTextStartPosition() { return highlightTextStartPosition; } }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\ComboBoxAutoCompletion.java
1
请在Spring Boot框架中完成以下Java代码
public void longRunningServiceMethod() throws InterruptedException { System.out.println("Service-method start ..."); System.out.println("Sleeping before triggering SQL to simulate a long running code ..."); Thread.sleep(40000); Author author = authorRepository.fetchByName("Joana Nimar"); authorRepository.deleteByNeGenre(author.getGenre()); System.out.println("Service-method done ..."); } @Transactional public void newAuthors() { Author a1 = new Author(); a1.setName("Mark Janel"); a1.setGenre("Anthology"); a1.setId(1L); a1.setAge(23); Author a2 = new Author(); a2.setName("Olivia Goy"); a2.setGenre("Anthology"); a2.setId(2L);
a2.setAge(43); Author a3 = new Author(); a3.setName("Quartis Young"); a3.setGenre("Anthology"); a3.setId(3L); a3.setAge(51); Author a4 = new Author(); a4.setName("Joana Nimar"); a4.setGenre("History"); a4.setId(4L); a4.setAge(34); authorRepository.save(a1); authorRepository.save(a2); authorRepository.save(a3); authorRepository.save(a4); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootTransactionalInRepository\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Spring Boot application配置
app.datasource.url=jdbc:mysql://localhost:3306/numberdb?createDatabaseIfNotExist=true app.datasource.username=root app.datasource.password=root app.datasource.initialization-mode=always app.datasource.platform=mysql app.datasource.pool-initial-size=10 app.datasource.pool-max-size=50 app.datasource.connection-idle-limit-in-seconds=35 app.datasource.test-connection-query=select 1 from dual app.datasource.log-query-execution-longer-than-ms=2550 app.datasource.log-stack-trace-for-long-query-execution=true app.datasource.statement-cache-max-size=200 app.datasource.name=MyViburCP # d
isable auto-commit app.datasource.default-auto-commit=false # more settings can be added as app.datasource.* spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.open-in-view=false spring.jpa.hibernate.ddl-auto=none
repos\Hibernate-SpringBoot-master\HibernateSpringBootDataSourceBuilderViburDBCPKickoff\src\main\resources\application.properties
2
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Preis. @param Price Price */ @Override public void setPrice (java.math.BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } /** Get Preis. @return Price */ @Override public java.math.BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set 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; } /** Set Ranking. @param Ranking Relative Rank Number */ @Override public void setRanking (int Ranking) { set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking)); } /** Get Ranking. @return Relative Rank Number */ @Override public int getRanking () { Integer ii = (Integer)get_Value(COLUMNNAME_Ranking); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse.java
1
请完成以下Java代码
public class EntityListQueryProcessor extends AbstractSingleEntityTypeQueryProcessor<EntityListFilter> { private final EntityType entityType; private final Set<UUID> entityIds; public EntityListQueryProcessor(TenantRepo repo, QueryContext ctx, EdqsQuery query) { super(repo, ctx, query, (EntityListFilter) query.getEntityFilter()); this.entityType = filter.getEntityType(); this.entityIds = filter.getEntityList().stream().map(UUID::fromString).collect(Collectors.toSet()); } @Override protected void processCustomerQuery(UUID customerId, Consumer<EntityData<?>> processor) { processAll(ed -> { if (checkCustomerId(customerId, ed)) { processor.accept(ed); } }); }
@Override protected void processAll(Consumer<EntityData<?>> processor) { var map = repository.getEntityMap(entityType); for (UUID entityId : entityIds) { EntityData<?> ed = map.get(entityId); if (matches(ed)) { processor.accept(ed); } } } @Override protected int getProbableResultSize() { return entityIds.size(); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\query\processor\EntityListQueryProcessor.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getRoleLevel() { return roleLevel; } public void setRoleLevel(Integer roleLevel) {
this.roleLevel = roleLevel; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Role{" + "id=" + id + ", name=" + name + ", roleLevel=" + roleLevel + ", description=" + description + '}'; } }
repos\springBoot-master\springboot-dubbo\abel-user-api\src\main\java\cn\abel\user\models\Role.java
1
请完成以下Java代码
public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException { User user = null; try { user = this.identityService.createUserQuery() .userId(userId) .singleResult(); } catch (FlowableException ex) { // don't care } if (null == user) { throw new UsernameNotFoundException( String.format("user (%s) could not be found", userId)); } return createFlowableUser(user); } protected FlowableUser createFlowableUser(User user) { String userId = user.getId(); List<Privilege> userPrivileges = identityService.createPrivilegeQuery().userId(userId).list(); Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); for (Privilege userPrivilege : userPrivileges) { grantedAuthorities.add(new SimpleGrantedAuthority(userPrivilege.getName())); } List<Group> groups = identityService.createGroupQuery().groupMember(userId).list(); if (!groups.isEmpty()) { List<String> groupIds = new ArrayList<>(groups.size()); for (Group group : groups) {
groupIds.add(group.getId()); } List<Privilege> groupPrivileges = identityService.createPrivilegeQuery().groupIds(groupIds).list(); for (Privilege groupPrivilege : groupPrivileges) { grantedAuthorities.add(new SimpleGrantedAuthority(groupPrivilege.getName())); } } // We have to create new UserDto as the User returned by IDM is not serialized properly // (it extends AbstractEntity which is not serializable) and leads to the id not being serialized // We have to create new GroupDetails as Group returned bby IDM is not serialized properly. Same reasoning as with the User return new FlowableUser(UserDto.create(user), true, GroupDetails.create(groups), grantedAuthorities); } }
repos\flowable-engine-main\modules\flowable-spring-security\src\main\java\org\flowable\spring\security\FlowableUserDetailsService.java
1
请完成以下Java代码
public I_M_AttributeSetInstance generateASI(final I_M_ProductPrice productPrice) { final I_M_AttributeSetInstance productPriceASI = productPrice.getM_AttributeSetInstance(); if (productPriceASI == null || productPriceASI.getM_AttributeSetInstance_ID() <= 0) { return null; } final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID()); final AttributeSetId overrideAttributeSetId = Services.get(IProductBL.class).getAttributeSetId(productId); return asiBL.prepareCopy(productPriceASI) .overrideAttributeSetId(overrideAttributeSetId) // IMPORTANT: copy only those which are not empty (task #1272) // NOTE: At the moment we use only the M_AttributeValue_ID so that's why we check only that field .filter(ai -> ai.getM_AttributeValue_ID() > 0) // .copy(); } @Override public List<IPricingAttribute> extractPricingAttributes(@NonNull final I_M_ProductPrice productPrice) { final I_M_AttributeSetInstance productPriceASI = productPrice.getM_AttributeSetInstance(); if (productPriceASI == null || productPriceASI.getM_AttributeSetInstance_ID() <= 0) { return ImmutableList.of(); } return asiBL.getAttributeInstances(productPriceASI) .stream() .map(this::createPricingAttribute) .collect(GuavaCollectors.toImmutableList()); } private PricingAttribute createPricingAttribute(final I_M_AttributeInstance instance) { final AttributeId attributeId = AttributeId.ofRepoId(instance.getM_Attribute_ID()); final AttributeValueId attributeValueId = AttributeValueId.ofRepoIdOrNull(instance.getM_AttributeValue_ID()); final AttributeListValue attributeValue = attributeValueId != null ? attributesRepo.retrieveAttributeValueOrNull(attributeId, attributeValueId) : null; return new PricingAttribute(attributeValue); }
// task 08839 private final static ModelDynAttributeAccessor<IAttributeSetInstanceAware, IProductPriceAware> DYN_ATTR_IProductPriceAware = new ModelDynAttributeAccessor<>(IProductPriceAware.class); @Override public void setDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware, final Optional<IProductPriceAware> productPriceAware) { if (asiAware == null) { return; // nothing to do } DYN_ATTR_IProductPriceAware.setValue(asiAware, productPriceAware.orElse(null)); } @Override public void setDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware, final IProductPriceAware productPriceAware) { if (asiAware == null) { return; // nothing to do } DYN_ATTR_IProductPriceAware.setValue(asiAware, productPriceAware); } @Override public Optional<IProductPriceAware> getDynAttrProductPriceAttributeAware(final IAttributeSetInstanceAware asiAware) { return DYN_ATTR_IProductPriceAware.getValueIfExists(asiAware); } @Value private static class PricingAttribute implements IPricingAttribute { @Nullable AttributeListValue attributeValue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\attributebased\impl\AttributePricingBL.java
1
请在Spring Boot框架中完成以下Java代码
public class DeploymentResource { @Autowired protected RestResponseFactory restResponseFactory; @Autowired protected RepositoryService repositoryService; @Autowired(required=false) protected BpmnRestApiInterceptor restApiInterceptor; @ApiOperation(value = "Get a deployment", tags = { "Deployment" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the deployment was found and returned."), @ApiResponse(code = 404, message = "Indicates the requested deployment was not found.") }) @GetMapping(value = "/repository/deployments/{deploymentId}", produces = "application/json") public DeploymentResponse getDeployment(@ApiParam(name = "deploymentId", value ="The id of the deployment to get.") @PathVariable String deploymentId) { Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); if (deployment == null) { throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.class); } if (restApiInterceptor != null) { restApiInterceptor.accessDeploymentById(deployment); } return restResponseFactory.createDeploymentResponse(deployment); }
@ApiOperation(value = "Delete a deployment", tags = { "Deployment" }, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the deployment was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested deployment was not found.") }) @DeleteMapping(value = "/repository/deployments/{deploymentId}", produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteDeployment(@ApiParam(name = "deploymentId") @PathVariable String deploymentId, @RequestParam(value = "cascade", required = false, defaultValue = "false") Boolean cascade) { Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); if (deployment == null) { throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.class); } if (restApiInterceptor != null) { restApiInterceptor.deleteDeployment(deployment); } if (cascade) { repositoryService.deleteDeployment(deploymentId, true); } else { repositoryService.deleteDeployment(deploymentId); } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\DeploymentResource.java
2
请完成以下Java代码
private void start(final I_IMP_Processor processorDef) { final AdempiereProcessor adempiereProcessorDef = Services.get(IIMPProcessorBL.class).asAdempiereProcessor(processorDef); final ReplicationProcessor processorThread = new ReplicationProcessor( adempiereProcessorDef, 0 // initialNap=0sec ); processorThread.setDaemon(true); processorThread.start(); System.out.println("Started " + processorThread); } private List<I_IMP_Processor> retrieveProcessors() { final Properties ctx = Env.getCtx(); final List<I_IMP_Processor> processorDefs = new Query(ctx, I_IMP_Processor.Table_Name, null, ITrx.TRXNAME_None) .setOnlyActiveRecords(true) .setOrderBy(I_IMP_Processor.COLUMNNAME_AD_Client_ID
+ ", " + I_IMP_Processor.COLUMNNAME_IMP_Processor_ID) .list(I_IMP_Processor.class); return processorDefs; } public static final void main(String[] args) throws InterruptedException { Env.getSingleAdempiereInstance(null).startup(RunMode.BACKEND); final IMP_Processors_StandaloneLauncher launcher = new IMP_Processors_StandaloneLauncher(); launcher.start(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\org\adempiere\process\rpl\imp\IMP_Processors_StandaloneLauncher.java
1
请在Spring Boot框架中完成以下Java代码
public class EDIDesadvPack { @NonNull EDIDesadvPackId ediDesadvPackId; @NonNull EDIDesadvId ediDesadvId; int seqNo; @NonNull String sscc18; @NonNull Boolean isManualIpaSscc; @Nullable HuId huId; @Nullable PackagingCodeId huPackagingCodeId; @Nullable String gtinPackingMaterial; @NonNull @Singular List<EDIDesadvPackItem> ediDesadvPackItems; @NonNull public Integer getQtyTU() { return ediDesadvPackItems.stream() .map(EDIDesadvPackItem::getQtyTu) .filter(Objects::nonNull) .reduce(0, Integer::sum); } @NonNull public BigDecimal getQtyCUsPerTU() { return ediDesadvPackItems.stream() .map(EDIDesadvPackItem::getQtyCUsPerTU) .filter(Objects::nonNull) .reduce(BigDecimal.ZERO, BigDecimal::add); } @NonNull public BigDecimal getQtyCUsPerLU() { return ediDesadvPackItems.stream() .map(EDIDesadvPackItem::getQtyCUsPerLU) .filter(Objects::nonNull) .reduce(BigDecimal.ZERO, BigDecimal::add); } @Value @Builder public static class EDIDesadvPackItem { @NonNull EDIDesadvPackItemId ediDesadvPackItemId; @NonNull EDIDesadvPackId ediDesadvPackId; @NonNull EDIDesadvLineId ediDesadvLineId; int line;
@NonNull BigDecimal movementQty; @Nullable InOutId inOutId; @Nullable InOutLineId inOutLineId; @Nullable BigDecimal qtyItemCapacity; @Nullable Integer qtyTu; @Nullable BigDecimal qtyCUsPerTU; @Nullable BigDecimal qtyCUPerTUinInvoiceUOM; @Nullable BigDecimal qtyCUsPerLU; @Nullable BigDecimal qtyCUsPerLUinInvoiceUOM; @Nullable Timestamp bestBeforeDate; @Nullable String lotNumber; @Nullable PackagingCodeId huPackagingCodeTuId; @Nullable String gtinTuPackingMaterial; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\EDIDesadvPack.java
2
请在Spring Boot框架中完成以下Java代码
public JAXBElement<XLSImpCOLCandType> createXLSImpCOLCand(XLSImpCOLCandType value) { return new JAXBElement<XLSImpCOLCandType>(_XLSImpCOLCand_QNAME, XLSImpCOLCandType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvPackItemType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvPackItemType }{@code >} */ @XmlElementDecl(namespace = "", name = "EDI_Exp_Desadv_Pack_Item") public JAXBElement<EDIExpDesadvPackItemType> createEDIExpDesadvPackItem(EDIExpDesadvPackItemType value) { return new JAXBElement<EDIExpDesadvPackItemType>(_EDIExpDesadvPackItem_QNAME, EDIExpDesadvPackItemType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvPackType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvPackType }{@code >} */ @XmlElementDecl(namespace = "", name = "EDI_Exp_Desadv_Pack") public JAXBElement<EDIExpDesadvPackType> createEDIExpDesadvPack(EDIExpDesadvPackType value) { return new JAXBElement<EDIExpDesadvPackType>(_EDIExpDesadvPack_QNAME, EDIExpDesadvPackType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvLineWithNoPackType }{@code >} * * @param value * Java instance representing xml element's value.
* @return * the new instance of {@link JAXBElement }{@code <}{@link EDIExpDesadvLineWithNoPackType }{@code >} */ @XmlElementDecl(namespace = "", name = "EDI_Exp_DesadvLineWithNoPack") public JAXBElement<EDIExpDesadvLineWithNoPackType> createEDIExpDesadvLineWithNoPack(EDIExpDesadvLineWithNoPackType value) { return new JAXBElement<EDIExpDesadvLineWithNoPackType>(_EDIExpDesadvLineWithNoPack_QNAME, EDIExpDesadvLineWithNoPackType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EDIReplicationTrxUpdateType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link EDIReplicationTrxUpdateType }{@code >} */ @XmlElementDecl(namespace = "", name = "EDI_ReplicationTrx_Update") public JAXBElement<EDIReplicationTrxUpdateType> createEDIReplicationTrxUpdate(EDIReplicationTrxUpdateType value) { return new JAXBElement<EDIReplicationTrxUpdateType>(_EDIReplicationTrxUpdate_QNAME, EDIReplicationTrxUpdateType.class, null, value); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\ObjectFactory.java
2
请完成以下Java代码
public void setAD_Image_ID (final int AD_Image_ID) { if (AD_Image_ID < 1) set_Value (COLUMNNAME_AD_Image_ID, null); else set_Value (COLUMNNAME_AD_Image_ID, AD_Image_ID); } @Override public int getAD_Image_ID() { return get_ValueAsInt(COLUMNNAME_AD_Image_ID); } @Override public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID) { if (M_HazardSymbol_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID); } @Override public int getM_HazardSymbol_ID() { return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_ID); }
@Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_HazardSymbol.java
1
请完成以下Java代码
public void setUseUnits (int UseUnits) { set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits)); } /** Get Use units. @return Currently used units of the assets */ public int getUseUnits () { Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits); if (ii == null) return 0; return ii.intValue(); } /** Set Version No.
@param VersionNo Version Number */ public void setVersionNo (String VersionNo) { set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo); } /** Get Version No. @return Version Number */ public String getVersionNo () { return (String)get_Value(COLUMNNAME_VersionNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Change.java
1
请完成以下Java代码
public static List<JdtDepartmentTreeVo> listToTree(List<Department> allDepartment) { // 先找出所有的父级 List<JdtDepartmentTreeVo> treeList = getByParentId(1, allDepartment); Optional<Department> departmentOptional = allDepartment.stream().filter(item -> item.getParent_id() == null).findAny(); Department department = new Department(); //判断是否找到数据 if(departmentOptional.isPresent()){ department = departmentOptional.get(); } getChildrenRecursion(treeList, allDepartment); // 代码逻辑说明: 【issues/6017】钉钉同步部门时没有最顶层的部门名,同步用户时,用户没有部门信息--- JdtDepartmentTreeVo treeVo = new JdtDepartmentTreeVo(department); treeVo.setChildren(treeList); List<JdtDepartmentTreeVo> list = new ArrayList<>(); list.add(treeVo); return list; } private static List<JdtDepartmentTreeVo> getByParentId(Integer parentId, List<Department> allDepartment) { List<JdtDepartmentTreeVo> list = new ArrayList<>(); for (Department department : allDepartment) {
if (parentId.equals(department.getParent_id())) { list.add(new JdtDepartmentTreeVo(department)); } } return list; } private static void getChildrenRecursion(List<JdtDepartmentTreeVo> treeList, List<Department> allDepartment) { for (JdtDepartmentTreeVo departmentTree : treeList) { // 递归寻找子级 List<JdtDepartmentTreeVo> children = getByParentId(departmentTree.getDept_id(), allDepartment); if (children.size() > 0) { departmentTree.setChildren(children); getChildrenRecursion(children, allDepartment); } } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\thirdapp\JdtDepartmentTreeVo.java
1
请完成以下Java代码
public IExportProcessor getIExportProcessor() { I_EXP_Processor_Type type = getEXP_Processor_Type(); // TODO: caching String classname = type.getJavaClass(); try { return (IExportProcessor)getClass().getClassLoader().loadClass(classname).newInstance(); } catch (Exception e) { throw new AdempiereException(e); } } private void deleteParameters() { for (I_EXP_ProcessorParameter para : getEXP_ProcessorParameters()) { InterfaceWrapperHelper.delete(para); } } public I_EXP_ProcessorParameter createParameter(String key, String name, String desc, String help, String value) { final String whereClause = I_EXP_ProcessorParameter.COLUMNNAME_EXP_Processor_ID+"=?" +" AND "+I_EXP_ProcessorParameter.COLUMNNAME_Value+"=?"; I_EXP_ProcessorParameter para = new Query(this.getCtx(), I_EXP_ProcessorParameter.Table_Name, whereClause, this.get_TrxName()) .setParameters(this.getEXP_Processor_ID(), key) .firstOnly(I_EXP_ProcessorParameter.class); if (para == null) { para = new X_EXP_ProcessorParameter(this.getCtx(), 0, this.get_TrxName()); para.setEXP_Processor_ID(this.getEXP_Processor_ID()); para.setValue(key); } para.setIsActive(true); para.setName(name); para.setDescription(desc);
para.setHelp(help); para.setParameterValue(value); InterfaceWrapperHelper.save(para); return para; } @Override protected boolean beforeDelete() { deleteParameters(); // deleteLog(true); return true; } @Override protected boolean afterSave(boolean newRecord, boolean success) { if (!success) return false; if (newRecord || is_ValueChanged(COLUMNNAME_EXP_Processor_Type_ID)) { deleteParameters(); final IExportProcessor proc = getIExportProcessor(); proc.createInitialParameters(this); } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MEXPProcessor.java
1
请完成以下Java代码
private int handleNewBPartnerRequest(final ProcessNewRecordDocumentRequest request) { final I_C_BPartner_QuickInput template = InterfaceWrapperHelper.getPO(request.getDocument()); final BPartnerId bpartnerId = bpartnerQuickInputService.createBPartnerFromTemplate( template, NewRecordContext.builder() .loginOrgId(request.getLoginOrgId()) .loggedUserId(request.getLoggedUserId()) .loginLanguage(request.getLoginLanguage()) .build() ); return bpartnerId.getRepoId(); } public void addNewRecordDescriptor(@NonNull final NewRecordDescriptor newRecordDescriptor) { newRecordDescriptorsByTableName.put(newRecordDescriptor.getTableName(), newRecordDescriptor); logger.info("Registered {}", newRecordDescriptor); } public NewRecordDescriptor getNewRecordDescriptorOrNull(@NonNull final String tableName) { return newRecordDescriptorsByTableName.get(tableName); } /** * @param entityDescriptor the entity descriptor of the quick input window (e.g. for BPartner that is C_BPartner_QuickInput) * @return new record descriptor */ public NewRecordDescriptor getNewRecordDescriptor(final DocumentEntityDescriptor entityDescriptor) { final WindowId newRecordWindowId = entityDescriptor.getWindowId();
return newRecordDescriptorsByTableName.values() .stream() .filter(descriptor -> WindowId.equals(newRecordWindowId, descriptor.getNewRecordWindowId())) .findFirst() .orElseThrow(() -> new AdempiereException("No new record quick input defined windowId=" + newRecordWindowId)); } @Nullable public DocumentEntityDescriptor getNewRecordEntityDescriptorIfAvailable(@NonNull final String tableName) { final NewRecordDescriptor newRecordDescriptor = getNewRecordDescriptorOrNull(tableName); if (newRecordDescriptor == null) { return null; } try { return documentDescriptors.getDocumentEntityDescriptor(newRecordDescriptor.getNewRecordWindowId()); } catch (final Exception ex) { logger.warn("Failed fetching document entity descriptor for {}. Ignored", newRecordDescriptor, ex); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\NewRecordDescriptorsProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String genre; private int age; @OneToMany(cascade = CascadeType.ALL, mappedBy = "author", orphanRemoval = true) @JsonManagedReference private List<Book> books = new ArrayList<>(); public void addBook(Book book) { this.books.add(book); book.setAuthor(this); } public void removeBook(Book book) { book.setAuthor(null); this.books.remove(book); } public void removeBooks() { Iterator<Book> iterator = this.books.iterator(); while (iterator.hasNext()) { Book book = iterator.next(); book.setAuthor(null); iterator.remove(); } } 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 String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJacksonHibernate5Module\src\main\java\com\bookstore\entity\Author.java
2
请在Spring Boot框架中完成以下Java代码
public class Golfer implements Comparable<Golfer> { @jakarta.persistence.Id @Id @NonNull private String name; @Setter private Integer hole = 0; @Setter private Integer score = 0; @Override public int compareTo(Golfer other) { return this.getName().compareTo(other.getName()); } private boolean isValidHole(int hole) { return hole >= 1 && hole <= 18; }
public Golfer on(int hole) { Assert.isTrue(isValidHole(hole), () -> String.format("Hole [%d] must be 1 through 18", hole)); this.hole = hole; return this; } public Golfer shot(int score) { this.score = score; return this; } }
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\Golfer.java
2
请完成以下Java代码
public class BagOfWordsDocument implements ITermFrequencyHolder { // // /** // * 文档所属的词表 // */ // private Lexicon lexicon; // /** // * 文档所属的类表 // */ // private Catalog catalog; public FrequencyMap<Integer> tfMap; public BagOfWordsDocument() { tfMap = new FrequencyMap<Integer>();
} public FrequencyMap<Integer> getTfMap() { return tfMap; } /** * 是否为空(文档中没有任何词) * @return */ public boolean isEmpty() { return tfMap.isEmpty(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\BagOfWordsDocument.java
1
请在Spring Boot框架中完成以下Java代码
public void deletePayProduct(String productCode) throws PayBizException{ List<RpPayWay> payWayList = rpPayWayService.listByProductCode(productCode); if(!payWayList.isEmpty()){ throw new PayBizException(PayBizException.PAY_PRODUCT_HAS_DATA,"支付产品已关联支付方式,无法删除!"); } List<RpUserPayConfig> payConfigList = rpUserPayConfigService.listByProductCode(productCode); if(!payConfigList.isEmpty()){ throw new PayBizException(PayBizException.PAY_PRODUCT_HAS_DATA,"支付产品已关联用户,无法删除!"); } RpPayProduct rpPayProduct = getByProductCode(productCode, null); if(rpPayProduct.getAuditStatus().equals(PublicEnum.YES.name())){ throw new PayBizException(PayBizException.PAY_PRODUCT_IS_EFFECTIVE,"支付产品已生效,无法删除!"); } rpPayProduct.setStatus(PublicStatusEnum.UNACTIVE.name()); updateData(rpPayProduct); } /** * 获取所有支付产品 * @param productCode */ @Override public List<RpPayProduct> listAll(){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); return rpPayProductDao.listBy(paramMap); } /** * 审核 * @param productCode * @param auditStatus */ @Override
public void audit(String productCode, String auditStatus) throws PayBizException{ RpPayProduct rpPayProduct = getByProductCode(productCode, null); if(rpPayProduct == null){ throw new PayBizException(PayBizException.PAY_PRODUCT_IS_NOT_EXIST,"支付产品不存在!"); } if(auditStatus.equals(PublicEnum.YES.name())){ //检查是否已设置支付方式 List<RpPayWay> payWayList = rpPayWayService.listByProductCode(productCode); if(payWayList.isEmpty()){ throw new PayBizException(PayBizException.PAY_TYPE_IS_NOT_EXIST,"支付方式未设置,无法操作!"); } }else if(auditStatus.equals(PublicEnum.NO.name())){ //检查是否已有支付配置 List<RpUserPayConfig> payConfigList = rpUserPayConfigService.listByProductCode(productCode); if(!payConfigList.isEmpty()){ throw new PayBizException(PayBizException.USER_PAY_CONFIG_IS_EXIST,"支付产品已关联用户支付配置,无法操作!"); } } rpPayProduct.setAuditStatus(auditStatus); rpPayProduct.setEditTime(new Date()); updateData(rpPayProduct); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpPayProductServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class SslProperties { /** * SSL bundles. */ private final Bundles bundle = new Bundles(); public Bundles getBundle() { return this.bundle; } /** * Properties to define SSL Bundles. */ public static class Bundles { /** * PEM-encoded SSL trust material. */ private final Map<String, PemSslBundleProperties> pem = new LinkedHashMap<>(); /** * Java keystore SSL trust material. */ private final Map<String, JksSslBundleProperties> jks = new LinkedHashMap<>(); /** * Trust material watching. */ private final Watch watch = new Watch(); public Map<String, PemSslBundleProperties> getPem() { return this.pem; } public Map<String, JksSslBundleProperties> getJks() { return this.jks; } public Watch getWatch() { return this.watch; } public static class Watch { /** * File watching. */ private final File file = new File(); public File getFile() { return this.file; }
public static class File { /** * Quiet period, after which changes are detected. */ private Duration quietPeriod = Duration.ofSeconds(10); public Duration getQuietPeriod() { return this.quietPeriod; } public void setQuietPeriod(Duration quietPeriod) { this.quietPeriod = quietPeriod; } } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslProperties.java
2
请完成以下Java代码
public String toString() { final StringBuffer sb = new StringBuffer("MReportSource[") .append(get_ID()).append(" - ").append(getDescription()) .append(" - ").append(getElementType()); sb.append("]"); return sb.toString(); } // toString /************************************************************************** * Copy Constructor * * @param ctx context * @param AD_Client_ID parent * @param AD_Org_ID parent
* @param PA_ReportLine_ID parent * @param source copy source * @param trxName transaction * @return Report Source */ public static MReportSource copy(final Properties ctx, final int AD_Client_ID, final int AD_Org_ID, final int PA_ReportLine_ID, final MReportSource source, final String trxName) { final MReportSource retValue = new MReportSource(ctx, 0, trxName); PO.copyValues(source, retValue, AD_Client_ID, AD_Org_ID); retValue.setPA_ReportLine_ID(PA_ReportLine_ID); return retValue; } // copy } // MReportSource
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportSource.java
1
请完成以下Java代码
public void setIsDocumentLevel (final boolean IsDocumentLevel) { set_Value (COLUMNNAME_IsDocumentLevel, IsDocumentLevel); } @Override public boolean isDocumentLevel() { return get_ValueAsBoolean(COLUMNNAME_IsDocumentLevel); } @Override public void setIsPackagingTax (final boolean IsPackagingTax) { set_Value (COLUMNNAME_IsPackagingTax, IsPackagingTax); } @Override public boolean isPackagingTax() { return get_ValueAsBoolean(COLUMNNAME_IsPackagingTax); } @Override public void setIsTaxIncluded (final boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, IsTaxIncluded); } @Override public boolean isTaxIncluded() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded); } @Override public void setIsWholeTax (final boolean IsWholeTax) { set_Value (COLUMNNAME_IsWholeTax, IsWholeTax); } @Override public boolean isWholeTax() { return get_ValueAsBoolean(COLUMNNAME_IsWholeTax); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmt (final BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceTax.java
1
请在Spring Boot框架中完成以下Java代码
public void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); if (ArrayUtil.isNotEmpty(cc)) { helper.setCc(cc); } mailSender.send(message); } /** * 发送带附件的邮件 * * @param to 收件人地址 * @param subject 邮件主题 * @param content 邮件内容 * @param filePath 附件地址 * @param cc 抄送地址 * @throws MessagingException 邮件发送异常 */ @Override public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); if (ArrayUtil.isNotEmpty(cc)) { helper.setCc(cc); } FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); mailSender.send(message);
} /** * 发送正文中有静态资源的邮件 * * @param to 收件人地址 * @param subject 邮件主题 * @param content 邮件内容 * @param rscPath 静态资源地址 * @param rscId 静态资源id * @param cc 抄送地址 * @throws MessagingException 邮件发送异常 */ @Override public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); if (ArrayUtil.isNotEmpty(cc)) { helper.setCc(cc); } FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); } }
repos\spring-boot-demo-master\demo-email\src\main\java\com\xkcoding\email\service\impl\MailServiceImpl.java
2
请完成以下Java代码
public class Main extends AbstractModuleInterceptor { @Override protected void registerInterceptors(final IModelValidationEngine engine) { engine.addModelValidator(new de.metas.aggregation.model.validator.C_Aggregation()); engine.addModelValidator(new de.metas.aggregation.model.validator.C_AggregationItem()); } @Override protected void registerCallouts(final IProgramaticCalloutProvider calloutsRegistry) { calloutsRegistry.registerAnnotatedCallout(new de.metas.aggregation.callout.C_Aggregation()); calloutsRegistry.registerAnnotatedCallout(new de.metas.aggregation.callout.C_AggregationItem()); }
@Override protected void setupCaching(final IModelCacheService cachingService) { cachingService.addTableCacheConfigIfAbsent(I_C_Aggregation.class); cachingService.addTableCacheConfigIfAbsent(I_C_Aggregation_Attribute.class); final CacheMgt cacheMgt = CacheMgt.get(); // important: if an aggregation changes, we not only want 50000 invoice candidate to be recomputed, but we also want them to be recomputed with the recent value cacheMgt.enableRemoteCacheInvalidationForTableName(I_C_Aggregation.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_C_Aggregation_Attribute.Table_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\validator\Main.java
1
请在Spring Boot框架中完成以下Java代码
public Long getProductId() { return product.getId(); } public String getProductIdAsString() { return product.getIdAsString(); } public String getProductUUID() { return product.getUuid(); } public String getBpartnerUUID() { return bpartner.getUuid(); } public LocalDate getDay() { return day.toLocalDate(); }
public YearWeek getWeek() { return YearWeekUtil.ofLocalDate(day.toLocalDate()); } @Nullable public Trend getTrend() { return Trend.ofNullableCode(trend); } @Nullable public String getTrendAsString() { return trend; } public void setTrend(@Nullable final Trend trend) { this.trend = trend != null ? trend.getCode() : null; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\WeekSupply.java
2
请完成以下Java代码
public Quantity getQtyRequiredForOneFinishedGood() { if (qtyPercentage) { // // We also need to multiply by BOM UOM to BOM Line UOM multiplier // see http://dewiki908/mediawiki/index.php/06973_Fix_percentual_BOM_line_quantities_calculation_%28108941319640%29 final UOMConversionRate bomToLineRate = uomConversionService.getRate(bomProductId, UomId.ofRepoId(bomProductUOM.getC_UOM_ID()), UomId.ofRepoId(uom.getC_UOM_ID())); final BigDecimal bomToLineUOMMultiplier = bomToLineRate.getFromToMultiplier(); return Quantity.of( percentOfFinishedGood.computePercentageOf(bomToLineUOMMultiplier, 12), uom); } else { return qtyForOneFinishedGood; } } @Deprecated public Quantity computeQtyOfFinishedGoodsForComponentQty(@NonNull final BigDecimal componentsQty) { return computeQtyOfFinishedGoodsForComponentQty(Quantity.of(componentsQty, uom)); } public Quantity computeQtyOfFinishedGoodsForComponentQty(@NonNull final Quantity componentsQty)
{ final Quantity qtyRequiredForOneFinishedGood = getQtyRequiredForOneFinishedGood(); final Quantity componentsQtyConverted = uomConversionService.convertQuantityTo(componentsQty, UOMConversionContext.of(productId), uom); final BigDecimal qtyOfFinishedGoodsBD = componentsQtyConverted .toBigDecimal() .divide( qtyRequiredForOneFinishedGood.toBigDecimal(), bomProductUOM.getStdPrecision(), RoundingMode.DOWN); // IMPORTANT to round DOWN because we need complete products. return Quantity.of(qtyOfFinishedGoodsBD, bomProductUOM); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\QtyCalculationsBOMLine.java
1
请在Spring Boot框架中完成以下Java代码
public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name", nullable = false) private String name; @Column(name = "item_price", nullable = false) private Double itemPrice; // Default constructor required by JPA public Item() { } public Item(String name, Double itemPrice) { this.name = name; this.itemPrice = itemPrice; } // Getters and setters 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 Double getItemPrice() { return itemPrice; } public void setItemPrice(Double itemPrice) { this.itemPrice = itemPrice; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\pojo\Item.java
2
请完成以下Java代码
static I_M_Product extractProductOrNull(@NonNull final I_M_HU_PackingMaterial pm) { final ProductId productId = ProductId.ofRepoIdOrNull(pm.getM_Product_ID()); return productId != null ? Services.get(IProductDAO.class).getById(productId) : null; } /** * Retrieve the packing material of a package by package Id. * <p> * If there's no packing material, null is returned. * <p> * sql: * * <pre>{@code * SELECT pack.* * FROM m_package_hu phu * INNER JOIN m_hu_item huitem ON phu.m_hu_id = huitem.m_hu_id * INNER JOIN m_hu_packingmaterial pack ON huitem.m_hu_packingmaterial_id = pack.m_hu_packingmaterial_id * WHERE phu.m_package_id = 1000023 * LIMIT 1; * }</pre> * <p> * thx to ruxi for transforming this sql query into "metasfresh"
*/ @Nullable I_M_HU_PackingMaterial retrievePackingMaterialOrNull(@NonNull final PackageId packageId); @Nullable I_M_HU_PackingMaterial getById(@NonNull HuPackingMaterialId packingMaterialId); @Nullable I_M_HU_PackingMaterial retrieveHUPackingMaterialOrNull(@NonNull I_M_HU_Item huItem); /** * Return the dimensionsInCM of the packing material, or a default with all dimensionsInCM set to 1 * <p> * This method should not be here, it should belong to de.metas.shipper.gateway.commons.DeliveryOrderUtil. * However it is here, as adding it there will create a circular dependency between de.metas.handlingunits.base and de.metas.shipper.gateway.commons, because I_M_HU_PackingMaterial must be imported. */ @NonNull PackageDimensions retrievePackageDimensions(@NonNull final I_M_HU_PackingMaterial packingMaterial, @NonNull final UomId toUomId); List<HuPackingMaterial> retrieveBy(@NonNull final HuPackingMaterialQuery query); Optional<HuPackingMaterial> getLUPIItemForHUPI(BPartnerId bpartnerId, @NonNull HuPackingInstructionsId luPIId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\IHUPackingMaterialDAO.java
1
请完成以下Java代码
public String getUPC () { return (String)get_Value(COLUMNNAME_UPC); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () {
return (String)get_Value(COLUMNNAME_Value); } /** Set Warehouse. @param WarehouseName Warehouse Name */ public void setWarehouseName (String WarehouseName) { set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName); } /** Get Warehouse. @return Warehouse Name */ public String getWarehouseName () { return (String)get_Value(COLUMNNAME_WarehouseName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RV_WarehousePrice.java
1
请完成以下Java代码
public int getC_Country_Sequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_Sequence_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Adress-Druckformat. @param DisplaySequence Format for printing this Address */ @Override public void setDisplaySequence (java.lang.String DisplaySequence) { set_Value (COLUMNNAME_DisplaySequence, DisplaySequence); } /** Get Adress-Druckformat. @return Format for printing this Address */ @Override public java.lang.String getDisplaySequence () {
return (java.lang.String)get_Value(COLUMNNAME_DisplaySequence); } /** Set Local Address Format. @param DisplaySequenceLocal Format for printing this Address locally */ @Override public void setDisplaySequenceLocal (java.lang.String DisplaySequenceLocal) { set_Value (COLUMNNAME_DisplaySequenceLocal, DisplaySequenceLocal); } /** Get Local Address Format. @return Format for printing this Address locally */ @Override public java.lang.String getDisplaySequenceLocal () { return (java.lang.String)get_Value(COLUMNNAME_DisplaySequenceLocal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Country_Sequence.java
1
请完成以下Java代码
public ScalesGetWeightHandler<C> setEndpoint(final ITcpConnectionEndPoint endpoint) { this.endpoint = endpoint; return this; } public ScalesGetWeightHandler<C> setParser(final IParser<C> parser) { this.parser = parser; return this; } public ScalesGetWeightHandler<C> setCmd(final C cmd) { this.cmd = cmd; return this; } public ScalesGetWeightHandler<C> setWeightFieldName(final String fieldName) { this.weightFieldName = fieldName; return this; } public ScalesGetWeightHandler<C> setUOMFieldName(final String fieldName) { this.uomFieldName = fieldName; return this; } /** * The weighing result number will be round to the given precision using {@link RoundingMode#HALF_UP}.<br> * If called with a value less than zero, or not called at all, then no rounding will be done. * * @param roundWeightToPrecision
* @task http://dewiki908/mediawiki/index.php/09207_Wiegen_nur_eine_Nachkommastelle_%28101684670982%29 */ public ScalesGetWeightHandler<C> setroundWeightToPrecision(final int roundWeightToPrecision) { this.roundWeightToPrecision = roundWeightToPrecision; return this; } @Override public String toString() { return String.format( "ScalesGetWeightHandler [endpoint=%s, parser=%s, cmd=%s, weightFieldName=%s, uomFieldName=%s, weightRoundToPrecision=%s]", endpoint, parser, cmd, weightFieldName, uomFieldName, roundWeightToPrecision); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\ScalesGetWeightHandler.java
1
请完成以下Java代码
public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo) { set_Value (COLUMNNAME_VendorProductNo, VendorProductNo); } @Override public java.lang.String getVendorProductNo() { return get_ValueAsString(COLUMNNAME_VendorProductNo); } @Override public void setVolume (final @Nullable BigDecimal Volume) { set_Value (COLUMNNAME_Volume, Volume); } @Override public BigDecimal getVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeight (final @Nullable BigDecimal Weight) { set_Value (COLUMNNAME_Weight, Weight); } @Override public BigDecimal getWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeightUOM (final @Nullable java.lang.String WeightUOM) { set_Value (COLUMNNAME_WeightUOM, WeightUOM); } @Override public java.lang.String getWeightUOM() { return get_ValueAsString(COLUMNNAME_WeightUOM); } @Override public void setWeight_UOM_ID (final int Weight_UOM_ID) { if (Weight_UOM_ID < 1) set_Value (COLUMNNAME_Weight_UOM_ID, null); else set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID); } @Override public int getWeight_UOM_ID() {
return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID); } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } @Override public void setX12DE355 (final @Nullable java.lang.String X12DE355) { set_Value (COLUMNNAME_X12DE355, X12DE355); } @Override public java.lang.String getX12DE355() { return get_ValueAsString(COLUMNNAME_X12DE355); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Product.java
1
请完成以下Java代码
public void setRating (int Rating) { set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating)); } /** Get Rating. @return Classification or Importance */ public int getRating () { Integer ii = (Integer)get_Value(COLUMNNAME_Rating); if (ii == null) return 0; return ii.intValue(); } /** Set Text Message.
@param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Comment.java
1
请完成以下Java代码
public void setCompact(Boolean compact) { this.compact = compact; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected CleanableHistoricCaseInstanceReport createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createCleanableHistoricCaseInstanceReport(); } @Override protected void applyFilters(CleanableHistoricCaseInstanceReport query) { if (caseDefinitionIdIn != null && caseDefinitionIdIn.length > 0) { query.caseDefinitionIdIn(caseDefinitionIdIn); } if (caseDefinitionKeyIn != null && caseDefinitionKeyIn.length > 0) {
query.caseDefinitionKeyIn(caseDefinitionKeyIn); } if (Boolean.TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIdIn != null && tenantIdIn.length > 0) { query.tenantIdIn(tenantIdIn); } if (Boolean.TRUE.equals(compact)) { query.compact(); } } @Override protected void applySortBy(CleanableHistoricCaseInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { query.orderByFinished(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricCaseInstanceReportDto.java
1
请完成以下Java代码
public class EmployeeEditor extends Composite<VerticalLayout> { public interface SaveListener { void onSave(Employee employee); } public interface DeleteListener { void onDelete(Employee employee); } public interface CancelListener { void onCancel(); } private Employee employee; private SaveListener saveListener; private DeleteListener deleteListener; private CancelListener cancelListener; private final Binder<Employee> binder = new BeanValidationBinder<>(Employee.class); public EmployeeEditor() { var firstName = new TextField("First name"); var lastName = new TextField("Last name"); var save = new Button("Save", VaadinIcon.CHECK.create()); var cancel = new Button("Cancel"); var delete = new Button("Delete", VaadinIcon.TRASH.create()); binder.forField(firstName).bind("firstName"); binder.forField(lastName).bind("lastName"); save.addThemeVariants(ButtonVariant.LUMO_PRIMARY); save.addClickListener(e -> save()); save.addClickShortcut(Key.ENTER); delete.addThemeVariants(ButtonVariant.LUMO_ERROR); delete.addClickListener(e -> deleteListener.onDelete(employee)); cancel.addClickListener(e -> cancelListener.onCancel()); getContent().add(firstName, lastName, new HorizontalLayout(save, cancel, delete));
} private void save() { // Save the form into a new instance of Employee var updated = new Employee(); updated.setId(employee.getId()); if (binder.writeBeanIfValid(updated)) { saveListener.onSave(updated); } } public void setEmployee(Employee employee) { this.employee = employee; binder.readBean(employee); } public void setSaveListener(SaveListener saveListener) { this.saveListener = saveListener; } public void setDeleteListener(DeleteListener deleteListener) { this.deleteListener = deleteListener; } public void setCancelListener(CancelListener cancelListener) { this.cancelListener = cancelListener; } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\spring\EmployeeEditor.java
1
请完成以下Java代码
public String getNb() { return nb; } /** * Sets the value of the nb property. * * @param value * allowed object is * {@link String } * */ public void setNb(String value) { this.nb = value; } /** * Gets the value of the prtry property. * * @return * possible object is * {@link String }
* */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = 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\CorporateAction1.java
1
请在Spring Boot框架中完成以下Java代码
public PageResult getAdminUserPage(PageUtil pageUtil) { //当前页码中的数据列表 List<AdminUser> users = adminUserDao.findAdminUsers(pageUtil); //数据总条数 用于计算分页数据 int total = adminUserDao.getTotalAdminUser(pageUtil); PageResult pageResult = new PageResult(users, total, pageUtil.getLimit(), pageUtil.getPage()); return pageResult; } @Override public AdminUser updateTokenAndLogin(String userName, String password) { AdminUser adminUser = adminUserDao.getAdminUserByUserNameAndPassword(userName, MD5Util.MD5Encode(password, "UTF-8")); if (adminUser != null) { //登录后即执行修改token的操作 String token = getNewToken(System.currentTimeMillis() + "", adminUser.getId()); if (adminUserDao.updateUserToken(adminUser.getId(), token) > 0) { //返回数据时带上token adminUser.setUserToken(token); return adminUser; } } return null; } /** * 获取token值 * * @param sessionId * @param userId * @return */ private String getNewToken(String sessionId, Long userId) { String src = sessionId + userId + NumberUtil.genRandomNum(4); return SystemUtil.genToken(src); } @Override
public AdminUser selectById(Long id) { return adminUserDao.getAdminUserById(id); } @Override public AdminUser selectByUserName(String userName) { return adminUserDao.getAdminUserByUserName(userName); } @Override public int save(AdminUser user) { //密码加密 user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8")); return adminUserDao.addUser(user); } @Override public int updatePassword(AdminUser user) { return adminUserDao.updateUserPassword(user.getId(), MD5Util.MD5Encode(user.getPassword(), "UTF-8")); } @Override public int deleteBatch(Integer[] ids) { return adminUserDao.deleteBatch(ids); } @Override public AdminUser getAdminUserByToken(String userToken) { return adminUserDao.getAdminUserByToken(userToken); } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\service\impl\AdminUserServiceImpl.java
2
请完成以下Java代码
public IDeliveryDayAllocable asDeliveryDayAllocable(@NonNull final Object model) { final I_M_ShipmentSchedule sched = InterfaceWrapperHelper.create(model, I_M_ShipmentSchedule.class); return new ShipmentScheduleDeliveryDayAllocable(sched); } @Override public void updateDeliveryDayAllocFromModel( @NonNull final I_M_DeliveryDay_Alloc deliveryDayAlloc, @NonNull final IDeliveryDayAllocable deliveryDayAllocable) { // Services final IShipmentScheduleDeliveryDayBL shipmentScheduleDeliveryDayBL = Services.get(IShipmentScheduleDeliveryDayBL.class); final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class); final IShipmentScheduleEffectiveBL shipmentScheduleEffectiveBL = Services.get(IShipmentScheduleEffectiveBL.class); // // Get shipment schedule final I_M_ShipmentSchedule sched = shipmentScheduleDeliveryDayBL.getShipmentScheduleOrNull(deliveryDayAllocable, I_M_ShipmentSchedule.class); if (sched == null) { // not applicable for our model return; } deliveryDayAlloc.setM_Product_ID(sched.getM_Product_ID()); // task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule final BigDecimal qtyOrdered = shipmentScheduleEffectiveBL.computeQtyOrdered(sched); deliveryDayAlloc.setQtyOrdered(qtyOrdered); final BigDecimal qtyDelivered = sched.getQtyDelivered(); deliveryDayAlloc.setQtyDelivered(qtyDelivered); final Quantity qtyToDeliver = shipmentScheduleBL.getQtyToDeliver(sched); deliveryDayAlloc.setQtyToDeliver(qtyToDeliver.toBigDecimal()); }
/** * Does nothing */ @Override public void updateDeliveryDayWhenAllocationChanged(I_M_DeliveryDay deliveryDay, I_M_DeliveryDay_Alloc deliveryDayAlloc, I_M_DeliveryDay_Alloc deliveryDayAllocOld) { // nothing } /** * Does nothing */ @Override public void updateTourInstanceWhenDeliveryDayChanged(I_M_Tour_Instance tourInstance, I_M_DeliveryDay deliveryDay, I_M_DeliveryDay deliveryDayOld) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\ShipmentScheduleDeliveryDayHandler.java
1
请完成以下Java代码
public Object getConfig() { return config; } @Override public String toString() { return String.format("Between: %s and %s", config.getDatetime1(), config.getDatetime2()); } }; } public static class Config { @NotNull private @Nullable ZonedDateTime datetime1; @NotNull private @Nullable ZonedDateTime datetime2; public @Nullable ZonedDateTime getDatetime1() { return datetime1; } public Config setDatetime1(ZonedDateTime datetime1) { this.datetime1 = datetime1;
return this; } public @Nullable ZonedDateTime getDatetime2() { return datetime2; } public Config setDatetime2(ZonedDateTime datetime2) { this.datetime2 = datetime2; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\BetweenRoutePredicateFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void customize(ResourceConfig config) { if (this.healthEndpoint != null) { register(config, this.healthEndpoint); } } private void register(ResourceConfig config, ExposableWebEndpoint healthEndpoint) { EndpointMapping mapping = new EndpointMapping(""); JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.MANAGEMENT, this.groups); Collection<Resource> endpointResources = resourceFactory .createEndpointResources(mapping, Collections.singletonList(healthEndpoint)) .stream() .filter(Objects::nonNull) .toList(); register(endpointResources, config); } private void register(Collection<Resource> resources, ResourceConfig config) { config.registerResources(new HashSet<>(resources)); } } /** * {@link ContextResolver} used to obtain the {@link ObjectMapper} that should be used
* for {@link OperationResponseBody} instances. */ @SuppressWarnings("removal") @Priority(Priorities.USER - 100) private static final class EndpointJackson2ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { private final org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper mapper; private EndpointJackson2ObjectMapperContextResolver( org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper mapper) { this.mapper = mapper; } @Override public @Nullable ObjectMapper getContext(Class<?> type) { return OperationResponseBody.class.isAssignableFrom(type) ? this.mapper.get() : null; } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\actuate\web\JerseyWebEndpointManagementContextConfiguration.java
2
请完成以下Java代码
public class BpmnDiagramImpl extends DiagramImpl implements BpmnDiagram { protected static ChildElement<BpmnPlane> bpmnPlaneChild; protected static ChildElementCollection<BpmnLabelStyle> bpmnLabelStyleCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BpmnDiagram.class, BPMNDI_ELEMENT_BPMN_DIAGRAM) .namespaceUri(BPMNDI_NS) .extendsType(Diagram.class) .instanceProvider(new ModelTypeInstanceProvider<BpmnDiagram>(){ public BpmnDiagram newInstance(ModelTypeInstanceContext instanceContext) { return new BpmnDiagramImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); bpmnPlaneChild = sequenceBuilder.element(BpmnPlane.class) .required() .build(); bpmnLabelStyleCollection = sequenceBuilder.elementCollection(BpmnLabelStyle.class) .build(); typeBuilder.build(); }
public BpmnDiagramImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public BpmnPlane getBpmnPlane() { return bpmnPlaneChild.getChild(this); } public void setBpmnPlane(BpmnPlane bpmnPlane) { bpmnPlaneChild.setChild(this, bpmnPlane); } public Collection<BpmnLabelStyle> getBpmnLabelStyles() { return bpmnLabelStyleCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnDiagramImpl.java
1
请完成以下Java代码
protected boolean isUsernameBasedPrimaryKey() { return this.usernameBasedPrimaryKey; } /** * Allows the default query string used to retrieve users based on username to be * overridden, if default table or column names need to be changed. The default query * is {@link #DEF_USERS_BY_USERNAME_QUERY}; when modifying this query, ensure that all * returned columns are mapped back to the same column positions as in the default * query. If the 'enabled' column does not exist in the source database, a permanent * true value for this column may be returned by using a query similar to * * <pre> * &quot;select username,password,'true' as enabled from users where username = ?&quot; * </pre> * @param usersByUsernameQueryString The query string to set */ public void setUsersByUsernameQuery(String usersByUsernameQueryString) { this.usersByUsernameQuery = usersByUsernameQueryString; } protected boolean getEnableAuthorities() { return this.enableAuthorities; } /** * Enables loading of authorities (roles) from the authorities table. Defaults to true */ public void setEnableAuthorities(boolean enableAuthorities) { this.enableAuthorities = enableAuthorities; } protected boolean getEnableGroups() { return this.enableGroups; }
/** * Enables support for group authorities. Defaults to false * @param enableGroups */ public void setEnableGroups(boolean enableGroups) { this.enableGroups = enableGroups; } @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } private JdbcTemplate getJdbc() { JdbcTemplate template = getJdbcTemplate(); Assert.notNull(template, "JdbcTemplate cannot be null"); return template; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\jdbc\JdbcDaoImpl.java
1
请完成以下Java代码
public void updateWhileSaving( @NonNull final I_PP_Order_Weighting_Run record, @NonNull final Consumer<PPOrderWeightingRun> consumer) { final PPOrderWeightingRunId runId = PPOrderWeightingRunLoaderAndSaver.extractId(record); final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver(); loaderAndSaver.addToCacheAndAvoidSaving(record); loaderAndSaver.updateById(runId, consumer); } public void updateById( @NonNull final PPOrderWeightingRunId runId, @NonNull final Consumer<PPOrderWeightingRun> consumer) { final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver(); loaderAndSaver.updateById(runId, consumer); } public void deleteChecks(final PPOrderWeightingRunId runId) { queryBL.createQueryBuilder(I_PP_Order_Weighting_RunCheck.class) .addEqualsFilter(I_PP_Order_Weighting_RunCheck.COLUMNNAME_PP_Order_Weighting_Run_ID, runId)
.create() .delete(); } public PPOrderWeightingRunCheckId addRunCheck( @NonNull final PPOrderWeightingRunId weightingRunId, @NonNull final SeqNo lineNo, @NonNull final Quantity weight, @NonNull final OrgId orgId) { final I_PP_Order_Weighting_RunCheck record = InterfaceWrapperHelper.newInstance(I_PP_Order_Weighting_RunCheck.class); record.setAD_Org_ID(orgId.getRepoId()); record.setPP_Order_Weighting_Run_ID(weightingRunId.getRepoId()); record.setLine(lineNo.toInt()); record.setWeight(weight.toBigDecimal()); record.setC_UOM_ID(weight.getUomId().getRepoId()); InterfaceWrapperHelper.save(record); return PPOrderWeightingRunCheckId.ofRepoId(weightingRunId, record.getPP_Order_Weighting_RunCheck_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class PeerCacheHealthIndicatorConfiguration { @Bean("GeodeAsyncEventQueuesHealthIndicator") GeodeAsyncEventQueuesHealthIndicator asyncEventQueuesHealthIndicator(GemFireCache gemfireCache) { return new GeodeAsyncEventQueuesHealthIndicator(gemfireCache); } @Bean("GeodeCacheServersHealthIndicator") GeodeCacheServersHealthIndicator cacheServersHealthIndicator(GemFireCache gemfireCache) { return new GeodeCacheServersHealthIndicator(gemfireCache); } @Bean("GeodeGatewayReceiversHealthIndicator") GeodeGatewayReceiversHealthIndicator gatewayReceiversHealthIndicator(GemFireCache gemfireCache) { return new GeodeGatewayReceiversHealthIndicator(gemfireCache); } @Bean("GeodeGatewaySendersHealthIndicator") GeodeGatewaySendersHealthIndicator gatewaySendersHealthIndicator(GemFireCache gemfireCache) { return new GeodeGatewaySendersHealthIndicator(gemfireCache); } @Bean BeanPostProcessor cacheServerLoadProbeWrappingBeanPostProcessor() { return new BeanPostProcessor() { @Nullable @Override @SuppressWarnings("all") public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheServerFactoryBean) { CacheServerFactoryBean cacheServerFactoryBean = (CacheServerFactoryBean) bean; ServerLoadProbe serverLoadProbe = ObjectUtils.<ServerLoadProbe>get(bean, "serverLoadProbe"); if (serverLoadProbe != null) { cacheServerFactoryBean.setServerLoadProbe(wrap(serverLoadProbe)); } } return bean; } @Nullable @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof CacheServer) { CacheServer cacheServer = (CacheServer) bean; Optional.ofNullable(cacheServer.getLoadProbe()) .filter(it -> !(it instanceof ActuatorServerLoadProbeWrapper)) .filter(it -> cacheServer.getLoadPollInterval() > 0) .filter(it -> !cacheServer.isRunning()) .ifPresent(serverLoadProbe -> cacheServer.setLoadProbe(new ActuatorServerLoadProbeWrapper(serverLoadProbe))); } return bean; } private ServerLoadProbe wrap(ServerLoadProbe serverLoadProbe) { return new ActuatorServerLoadProbeWrapper(serverLoadProbe); } }; } public static final class PeerCacheCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Cache peerCache = CacheUtils.getCache(); ClientCache clientCache = CacheUtils.getClientCache(); return peerCache != null || clientCache == null; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator-autoconfigure\src\main\java\org\springframework\geode\boot\actuate\autoconfigure\config\PeerCacheHealthIndicatorConfiguration.java
2
请完成以下Java代码
public int getPriorityNo () { Integer ii = (Integer)get_Value(COLUMNNAME_PriorityNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Gang. @param X X-Dimension, z.B. Gang */ @Override public void setX (java.lang.String X) { set_Value (COLUMNNAME_X, X); } /** Get Gang. @return X-Dimension, z.B. Gang */ @Override public java.lang.String getX () { return (java.lang.String)get_Value(COLUMNNAME_X); } /** Set Regal. @param X1 Regal */ @Override public void setX1 (java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } /** Get Regal. @return Regal */ @Override public java.lang.String getX1 () { return (java.lang.String)get_Value(COLUMNNAME_X1); } /** Set Fach. @param Y
Y-Dimension, z.B. Fach */ @Override public void setY (java.lang.String Y) { set_Value (COLUMNNAME_Y, Y); } /** Get Fach. @return Y-Dimension, z.B. Fach */ @Override public java.lang.String getY () { return (java.lang.String)get_Value(COLUMNNAME_Y); } /** Set Ebene. @param Z Z-Dimension, z.B. Ebene */ @Override public void setZ (java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } /** Get Ebene. @return Z-Dimension, z.B. Ebene */ @Override public java.lang.String getZ () { return (java.lang.String)get_Value(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Locator.java
1
请完成以下Java代码
protected final String getGroupRoleAttribute() { return this.groupRoleAttribute; } /** * Returns the search filter configured for this populator Method available so that * classes extending this can override * @return the search filter * @see #setGroupSearchFilter(String) */ protected final String getGroupSearchFilter() { return this.groupSearchFilter; } /** * Returns the role prefix used by this populator Method available so that classes * extending this can override * @return the role prefix * @see #setRolePrefix(String) */ protected final String getRolePrefix() { return this.rolePrefix; } /** * Returns true if role names are converted to uppercase Method available so that * classes extending this can override * @return true if role names are converted to uppercase.
* @see #setConvertToUpperCase(boolean) */ protected final boolean isConvertToUpperCase() { return this.convertToUpperCase; } /** * Returns the search controls Method available so that classes extending this can * override the search controls used * @return the search controls */ private SearchControls getSearchControls() { return this.searchControls; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\DefaultLdapAuthoritiesPopulator.java
1
请完成以下Java代码
public void setIsDirectEnqueue (final boolean IsDirectEnqueue) { set_Value (COLUMNNAME_IsDirectEnqueue, IsDirectEnqueue); } @Override public boolean isDirectEnqueue() { return get_ValueAsBoolean(COLUMNNAME_IsDirectEnqueue); } @Override public void setIsDirectProcessQueueItem (final boolean IsDirectProcessQueueItem) { set_Value (COLUMNNAME_IsDirectProcessQueueItem, IsDirectProcessQueueItem); } @Override public boolean isDirectProcessQueueItem() { return get_ValueAsBoolean(COLUMNNAME_IsDirectProcessQueueItem); } @Override public void setIsFileSystem (final boolean IsFileSystem) { set_Value (COLUMNNAME_IsFileSystem, IsFileSystem); } @Override public boolean isFileSystem() { return get_ValueAsBoolean(COLUMNNAME_IsFileSystem); } @Override public void setIsReport (final boolean IsReport) { set_Value (COLUMNNAME_IsReport, IsReport); } @Override public boolean isReport() { return get_ValueAsBoolean(COLUMNNAME_IsReport); } @Override public void setName (final java.lang.String Name)
{ set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Archive.java
1
请完成以下Java代码
public class DeleteHistoricBatchCmd implements Command<Object> { protected String batchId; public DeleteHistoricBatchCmd(String batchId) { this.batchId = batchId; } public Object execute(CommandContext commandContext) { EnsureUtil.ensureNotNull(BadUserRequestException.class, "Historic batch id must not be null", "historic batch id", batchId); HistoricBatchEntity historicBatch = commandContext.getHistoricBatchManager().findHistoricBatchById(batchId); EnsureUtil.ensureNotNull(BadUserRequestException.class, "Historic batch for id '" + batchId + "' cannot be found", "historic batch", historicBatch); checkAccess(commandContext, historicBatch); writeUserOperationLog(commandContext, historicBatch.getTenantId());
historicBatch.delete(); return null; } protected void checkAccess(CommandContext commandContext, HistoricBatchEntity batch) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkDeleteHistoricBatch(batch); } } protected void writeUserOperationLog(CommandContext commandContext, String tenantId) { commandContext.getOperationLogManager() .logBatchOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY, batchId, tenantId, PropertyChange.EMPTY_CHANGE); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\history\DeleteHistoricBatchCmd.java
1
请完成以下Java代码
protected Map<String, String> getAsyncLeaveTransitionMetadata() { Map<String, String> metadata = new HashMap<>(); metadata.put(OperationSerializationMetadata.FIELD_PLAN_ITEM_INSTANCE_ID, planItemInstanceEntity.getId()); metadata.put(OperationSerializationMetadata.FIELD_EXIT_CRITERION_ID, exitCriterionId); metadata.put(OperationSerializationMetadata.FIELD_EXIT_TYPE, exitType); metadata.put(OperationSerializationMetadata.FIELD_EXIT_EVENT_TYPE, exitEventType); metadata.put(OperationSerializationMetadata.FIELD_IS_STAGE, isStage != null ? isStage.toString() : Boolean.FALSE.toString()); return metadata; } @Override protected boolean shouldAggregateForSingleInstance() { return false; } @Override protected boolean shouldAggregateForMultipleInstances() { return false; } public boolean isStage() { if (isStage == null) { isStage = isStage(planItemInstanceEntity); } return isStage; } @Override public String getOperationName() { return "[Exit plan item]";
} public String getExitCriterionId() { return exitCriterionId; } public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; } public String getExitType() { return exitType; } public void setExitType(String exitType) { this.exitType = exitType; } public String getExitEventType() { return exitEventType; } public void setExitEventType(String exitEventType) { this.exitEventType = exitEventType; } public Boolean getStage() { return isStage; } public void setStage(Boolean stage) { isStage = stage; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ExitPlanItemInstanceOperation.java
1
请完成以下Java代码
public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } public Integer getKeepAliveSeconds() { return keepAliveSeconds; } public void setKeepAliveSeconds(Integer keepAliveSeconds) { this.keepAliveSeconds = keepAliveSeconds; } public int getQueueCapacity() { return queueCapacity; } public void setQueueCapacity(int queueCapacity) { this.queueCapacity = queueCapacity; } public Integer getLockTimeInMillis() { return lockTimeInMillis; } public void setLockTimeInMillis(Integer lockTimeInMillis) { this.lockTimeInMillis = lockTimeInMillis; } public Integer getMaxJobsPerAcquisition() { return maxJobsPerAcquisition; } public void setMaxJobsPerAcquisition(Integer maxJobsPerAcquisition) { this.maxJobsPerAcquisition = maxJobsPerAcquisition; } public Integer getWaitTimeInMillis() { return waitTimeInMillis; } public void setWaitTimeInMillis(Integer waitTimeInMillis) { this.waitTimeInMillis = waitTimeInMillis; } public Long getMaxWait() { return maxWait; } public void setMaxWait(Long maxWait) { this.maxWait = maxWait; } public Integer getBackoffTimeInMillis() { return backoffTimeInMillis; } public void setBackoffTimeInMillis(Integer backoffTimeInMillis) { this.backoffTimeInMillis = backoffTimeInMillis; } public Long getMaxBackoff() { return maxBackoff; }
public void setMaxBackoff(Long maxBackoff) { this.maxBackoff = maxBackoff; } public Integer getBackoffDecreaseThreshold() { return backoffDecreaseThreshold; } public void setBackoffDecreaseThreshold(Integer backoffDecreaseThreshold) { this.backoffDecreaseThreshold = backoffDecreaseThreshold; } public Float getWaitIncreaseFactor() { return waitIncreaseFactor; } public void setWaitIncreaseFactor(Float waitIncreaseFactor) { this.waitIncreaseFactor = waitIncreaseFactor; } @Override public String toString() { return joinOn(this.getClass()) .add("enabled=" + enabled) .add("deploymentAware=" + deploymentAware) .add("corePoolSize=" + corePoolSize) .add("maxPoolSize=" + maxPoolSize) .add("keepAliveSeconds=" + keepAliveSeconds) .add("queueCapacity=" + queueCapacity) .add("lockTimeInMillis=" + lockTimeInMillis) .add("maxJobsPerAcquisition=" + maxJobsPerAcquisition) .add("waitTimeInMillis=" + waitTimeInMillis) .add("maxWait=" + maxWait) .add("backoffTimeInMillis=" + backoffTimeInMillis) .add("maxBackoff=" + maxBackoff) .add("backoffDecreaseThreshold=" + backoffDecreaseThreshold) .add("waitIncreaseFactor=" + waitIncreaseFactor) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\JobExecutionProperty.java
1
请完成以下Java代码
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) { return writeWith(Flux.from(body).flatMapSequential(p -> p)); } private ClientResponse prepareClientResponse(Publisher<? extends DataBuffer> body, HttpHeaders httpHeaders) { ClientResponse.Builder builder; builder = ClientResponse.create( Objects.requireNonNull(exchange.getResponse().getStatusCode(), "Status code must not be null"), messageReaders); return builder.headers(headers -> headers.putAll(httpHeaders)).body(Flux.from(body)).build(); } private <T> Mono<T> extractBody(ServerWebExchange exchange, ClientResponse clientResponse, Class<T> inClass) { // if inClass is byte[] then just return body, otherwise check if // decoding required if (byte[].class.isAssignableFrom(inClass)) { return clientResponse.bodyToMono(inClass); } List<String> encodingHeaders = exchange.getResponse().getHeaders().getOrEmpty(HttpHeaders.CONTENT_ENCODING); for (String encoding : encodingHeaders) { MessageBodyDecoder decoder = messageBodyDecoders.get(encoding); if (decoder != null) { return clientResponse.bodyToMono(byte[].class) .publishOn(Schedulers.parallel()) .map(decoder::decode) .map(bytes -> exchange.getResponse().bufferFactory().wrap(bytes)) .map(buffer -> prepareClientResponse(Mono.just(buffer), exchange.getResponse().getHeaders())) .flatMap(response -> response.bodyToMono(inClass)); } } return clientResponse.bodyToMono(inClass); }
private Mono<DataBuffer> writeBody(ServerHttpResponse httpResponse, CachedBodyOutputMessage message, Class<?> outClass) { Mono<DataBuffer> response = DataBufferUtils.join(message.getBody()); if (byte[].class.isAssignableFrom(outClass)) { return response; } List<String> encodingHeaders = httpResponse.getHeaders().getOrEmpty(HttpHeaders.CONTENT_ENCODING); for (String encoding : encodingHeaders) { MessageBodyEncoder encoder = messageBodyEncoders.get(encoding); if (encoder != null) { DataBufferFactory dataBufferFactory = httpResponse.bufferFactory(); response = response.publishOn(Schedulers.parallel()).map(buffer -> { byte[] encodedResponse = encoder.encode(buffer); DataBufferUtils.release(buffer); return encodedResponse; }).map(dataBufferFactory::wrap); break; } } return response; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\ModifyResponseBodyGatewayFilterFactory.java
1
请完成以下Java代码
public class WEBUI_Fact_Acct_Repost_ViewRows extends ViewBasedProcessTemplate implements IProcessPrecondition { private final IADTableDAO adTablesRepo = Services.get(IADTableDAO.class); public static final String TABLENAME_RV_UnPosted = "RV_UnPosted"; @Param(parameterName = "IsEnforcePosting", mandatory = true) private boolean forcePosting; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() { StreamUtils.dice(streamDocumentsToRepost(), 1000) .forEach(this::enqueueChunk); return MSG_OK; } private void enqueueChunk(final Collection<DocumentToRepost> documentsToRepost) { FactAcctRepostCommand.builder() .documentsToRepost(documentsToRepost) .forcePosting(forcePosting) .onErrorNotifyUserId(getUserId()) .build() .execute(); } private Stream<DocumentToRepost> streamDocumentsToRepost() { return getView().streamByIds(getSelectedRowIds(), QueryLimit.NO_LIMIT) .map(this::extractDocumentToRepost); } private DocumentToRepost extractDocumentToRepost(@NonNull final IViewRow row) { final String tableName = getTableName(); if (I_Fact_Acct.Table_Name.equals(tableName) || FactAcctFilterDescriptorsProviderFactory.FACT_ACCT_TRANSACTIONS_VIEW.equals(tableName) || TABLENAME_RV_UnPosted.equals(tableName)) { return extractDocumentToRepostFromTableAndRecordIdRow(row);
} else { return extractDocumentToRepostFromRegularRow(row); } } private DocumentToRepost extractDocumentToRepostFromTableAndRecordIdRow(final IViewRow row) { final int adTableId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Table_ID, -1); final int recordId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_Record_ID, -1); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build(); } private DocumentToRepost extractDocumentToRepostFromRegularRow(final IViewRow row) { final int adTableId = adTablesRepo.retrieveTableId(getTableName()); final int recordId = row.getId().toInt(); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build(); } @Override protected void postProcess(final boolean success) { getView().invalidateSelection(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\WEBUI_Fact_Acct_Repost_ViewRows.java
1
请在Spring Boot框架中完成以下Java代码
public UmsMember getCurrentMember() { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication auth = ctx.getAuthentication(); MemberDetails memberDetails = (MemberDetails) auth.getPrincipal(); return memberDetails.getUmsMember(); } @Override public void updateIntegration(Long id, Integer integration) { UmsMember record=new UmsMember(); record.setId(id); record.setIntegration(integration); memberMapper.updateByPrimaryKeySelective(record); memberCacheService.delMember(id); } @Override public UserDetails loadUserByUsername(String username) { UmsMember member = getByUsername(username); if(member!=null){ return new MemberDetails(member); } throw new UsernameNotFoundException("用户名或密码错误"); } @Override public String login(String username, String password) { String token = null; //密码需要客户端加密后传递
try { UserDetails userDetails = loadUserByUsername(username); if(!passwordEncoder.matches(password,userDetails.getPassword())){ throw new BadCredentialsException("密码不正确"); } UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); token = jwtTokenUtil.generateToken(userDetails); } catch (AuthenticationException e) { LOGGER.warn("登录异常:{}", e.getMessage()); } return token; } @Override public String refreshToken(String token) { return jwtTokenUtil.refreshHeadToken(token); } //对输入的验证码进行校验 private boolean verifyAuthCode(String authCode, String telephone){ if(StrUtil.isEmpty(authCode)){ return false; } String realAuthCode = memberCacheService.getAuthCode(telephone); return authCode.equals(realAuthCode); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberServiceImpl.java
2
请完成以下Java代码
public void segment(String text, String normalized, List<String> wordList) { perceptronSegmenter.segment(text, createInstance(normalized), wordList); } private CWSInstance createInstance(String text) { final FeatureTemplate[] featureTemplateArray = model.getFeatureTemplateArray(); return new CWSInstance(text, model.featureMap) { @Override protected int[] extractFeature(String sentence, FeatureMap featureMap, int position) { StringBuilder sbFeature = new StringBuilder(); List<Integer> featureVec = new LinkedList<Integer>(); for (int i = 0; i < featureTemplateArray.length; i++) { Iterator<int[]> offsetIterator = featureTemplateArray[i].offsetList.iterator(); Iterator<String> delimiterIterator = featureTemplateArray[i].delimiterList.iterator(); delimiterIterator.next(); // ignore U0 之类的id while (offsetIterator.hasNext()) { int offset = offsetIterator.next()[0] + position; if (offset < 0) sbFeature.append(FeatureIndex.BOS[-(offset + 1)]); else if (offset >= sentence.length()) sbFeature.append(FeatureIndex.EOS[offset - sentence.length()]); else sbFeature.append(sentence.charAt(offset)); if (delimiterIterator.hasNext()) sbFeature.append(delimiterIterator.next()); else sbFeature.append(i); } addFeatureThenClear(sbFeature, featureVec, featureMap); } return toFeatureArray(featureVec); } };
} @Override protected String getDefaultFeatureTemplate() { return "# Unigram\n" + "U0:%x[-1,0]\n" + "U1:%x[0,0]\n" + "U2:%x[1,0]\n" + "U3:%x[-2,0]%x[-1,0]\n" + "U4:%x[-1,0]%x[0,0]\n" + "U5:%x[0,0]%x[1,0]\n" + "U6:%x[1,0]%x[2,0]\n" + "\n" + "# Bigram\n" + "B"; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFSegmenter.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Auto Approval. @param IsAutoApproval Auto Approval */ @Override public void setIsAutoApproval (boolean IsAutoApproval) { set_Value (COLUMNNAME_IsAutoApproval, Boolean.valueOf(IsAutoApproval)); } /** Get Auto Approval. @return Auto Approval */ @Override public boolean isAutoApproval () { Object oo = get_Value(COLUMNNAME_IsAutoApproval); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */
@Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CreditLimit_Type.java
1
请完成以下Java代码
public String getTaskParentTaskId() { return taskParentTaskId; } public String getCategory() { return category; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } public List<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getProcessDefinitionNameLike() { return processDefinitionNameLike; } public List<String> getProcessCategoryInList() { return processCategoryInList; } public List<String> getProcessCategoryNotInList() { return processCategoryNotInList; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public String getProcessInstanceBusinessKeyLike() { return processInstanceBusinessKeyLike; } public Date getDueDate() { return dueDate; } public Date getDueBefore() { return dueBefore; } public Date getDueAfter() { return dueAfter; } public boolean isWithoutDueDate() { return withoutDueDate; } public SuspensionState getSuspensionState() { return suspensionState; }
public boolean isIncludeTaskLocalVariables() { return includeTaskLocalVariables; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isBothCandidateAndAssigned() { return bothCandidateAndAssigned; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getDescriptionLikeIgnoreCase() { return descriptionLikeIgnoreCase; } public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getLocale() { return locale; } public boolean isOrActive() { return orActive; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
public RoleNotificationsConfig getByRoleId(@NonNull final RoleId adRoleId) { return roleNotificationsConfigsByRoleId.getOrLoad(adRoleId, this::retrieveRoleNotificationsConfig); } private RoleNotificationsConfig retrieveRoleNotificationsConfig(@NonNull final RoleId adRoleId) { final List<UserNotificationsGroup> notificationGroups = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_Role_NotificationGroup.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_Role_NotificationGroup.COLUMN_AD_Role_ID, adRoleId) .create() .stream() .map(this::toNotificationGroup) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); return RoleNotificationsConfig.builder() .roleId(adRoleId) .notificationGroups(notificationGroups) .build(); } private UserNotificationsGroup toNotificationGroup(final I_AD_Role_NotificationGroup record) { final INotificationGroupRepository notificationGroupRepo = Services.get(INotificationGroupRepository.class); final NotificationGroupName groupInternalName = notificationGroupRepo.getNameById(NotificationGroupId.ofRepoId(record.getAD_NotificationGroup_ID())).orElse(null); if (groupInternalName == null) { // group does not exist or it was deactivated return null; } return UserNotificationsGroup.builder() .groupInternalName(groupInternalName) .notificationTypes(UserNotificationsConfigRepository.toNotificationTypes(record.getNotificationType()))
.build(); } @Override public ImmutableSet<RoleId> getRoleIdsContainingNotificationGroupName(@NonNull final NotificationGroupName notificationGroupName) { final INotificationGroupRepository notificationGroupRepo = Services.get(INotificationGroupRepository.class); final NotificationGroupId notificationGroupId = notificationGroupRepo.getNotificationGroupId(notificationGroupName).orElse(null); if(notificationGroupId == null) { return ImmutableSet.of(); } return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_Role_NotificationGroup.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_Role_NotificationGroup.COLUMN_AD_NotificationGroup_ID, notificationGroupId) .create() .listDistinct(I_AD_Role_NotificationGroup.COLUMNNAME_AD_Role_ID, Integer.class) .stream() .map(RoleId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\RoleNotificationsConfigRepository.java
1
请完成以下Java代码
public CaseInstance createCaseInstanceById(String caseDefinitionId, Map<String, Object> variables) { return withCaseDefinition(caseDefinitionId).setVariables(variables).create(); } public CaseInstance createCaseInstanceById(String caseDefinitionId, String businessKey, Map<String, Object> variables) { return withCaseDefinition(caseDefinitionId).businessKey(businessKey) .setVariables(variables).create(); } public void manuallyStartCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).manualStart(); } public void manuallyStartCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).manualStart(); } public void disableCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).disable(); } public void disableCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).disable(); } public void reenableCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).reenable(); } public void reenableCaseExecution(String caseExecutionId, Map<String, Object> variables) {
withCaseExecution(caseExecutionId).setVariables(variables).reenable(); } public void completeCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).complete(); } public void completeCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).complete(); } public void closeCaseInstance(String caseInstanceId) { withCaseExecution(caseInstanceId).close(); } public void terminateCaseExecution(String caseExecutionId) { withCaseExecution(caseExecutionId).terminate(); } public void terminateCaseExecution(String caseExecutionId, Map<String, Object> variables) { withCaseExecution(caseExecutionId).setVariables(variables).terminate(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
private List<String> extractClientIds(List<JSONObject> users) { return users.stream() .map(user -> user.getString("clientId")) .filter(clientId -> oConvertUtils.isNotEmpty(clientId) && !clientId.trim().isEmpty()) .collect(Collectors.toList()); } /** * 根据orgCode找上级 * * @param orgCode * @param sysDepartList * @param level 指定那第几级 从下往上 * @param nowLevel * @return */ public SysDepart getParentCompanyByOrgCode(String orgCode,List<SysDepart> sysDepartList, int level, int nowLevel) { //获取上一级公司的编码 String code = this.getPrefix(orgCode); if(oConvertUtils.isEmpty(code)) { return null; } List<SysDepart> list = sysDepartList.stream().filter(sysDepart -> sysDepart.getOrgCode().equals(code)).toList(); //判断去上级的级别 if(!CollectionUtils.isEmpty(list) && nowLevel == level) { return list.get(0); } else { if(!CollectionUtils.isEmpty(list)) { nowLevel++; } return getParentCompanyByOrgCode(code, sysDepartList, level, nowLevel); } } /** * 根据指定值获取编码前缀(每级固定YouBianCodeUtil.ZHANWEI_LENGTH位) * * @param fullCode 完整编码(如"A01A01A01") * @return 提取后的前缀编码(如"A01A01") */ private String getPrefix(String fullCode) { if(fullCode.length() < YouBianCodeUtil.ZHANWEI_LENGTH){
return ""; } // 计算总层级数,根据ZHANWEI_LENGTH int totalLevels = fullCode.length() / YouBianCodeUtil.ZHANWEI_LENGTH; int keepLevels = totalLevels - 1; // 计算需要截取的长度(保留层级数 × YouBianCodeUtil.ZHANWEI_LENGTH) int prefixLength = keepLevels * YouBianCodeUtil.ZHANWEI_LENGTH; return prefixLength == 0 ? "" : fullCode.substring(0, prefixLength); } /** * 根据部门code或部门id获取部门名称(当前和上级部门) * * @param orgCode 部门编码 * @param depId 部门id * @return String 部门名称 */ @Override public String getDepartPathNameByOrgCode(String orgCode, String depId) { return sysDepartService.getDepartPathNameByOrgCode(orgCode, depId); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysBaseApiImpl.java
2
请完成以下Java代码
public String writeValueAsString(final T object) { try { return jsonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object); } catch (final JsonProcessingException ex) { throw new AdempiereException("Failed converting object to json: " + object, ex); } } public T readValue(final String objectString) { try { return jsonObjectMapper.readValue(objectString, clazz); } catch (IOException ex) { throw new AdempiereException("Failed converting json to class= " + clazz + "; object=" + objectString, ex);
} } public T readValue(final InputStream objectStream) { try { return jsonObjectMapper.readValue(objectStream, clazz); } catch (IOException ex) { throw new AdempiereException("Failed converting json to class= " + clazz + "; object=" + objectStream, ex); } } public T convertValue(final Object object) { return jsonObjectMapper.convertValue(object, clazz); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\JSONObjectMapper.java
1
请完成以下Java代码
private List<CreatePackagesRequest> buildCreatePackageRequest( @NonNull final ShipperId shipperId, @NonNull final CreatePackagesForInOutRequest request, @NonNull final ShippingWeightCalculator weightCalculator) { if (Check.isEmpty(request.getPackageInfos())) { return huInOutDAO.retrieveShippedHandlingUnits(request.getShipment()) .stream() .map(hu -> CreatePackagesRequest.builder() .inOutId(request.getShipmentId()) .shipperId(shipperId) .processed(request.isProcessed()) .weightInKg(weightCalculator.calculateWeightInKg(hu) .map(weight -> weight.toBigDecimal()) .orElse(null)) .packageDimensions(extractPackageDimensions(hu)) .build()) .collect(Collectors.toList()); } else { return request.getPackageInfos() .stream() .map(packageInfo -> CreatePackagesRequest.builder() .inOutId(request.getShipmentId()) .shipperId(shipperId) .processed(request.isProcessed()) // .trackingCode(packageInfo.getTrackingNumber()) .trackingURL(packageInfo.getTrackingUrl()) .weightInKg(packageInfo.getWeight()) .packageDimensions(packageInfo.getPackageDimensions()) .build() ) .collect(ImmutableList.toImmutableList()); } }
private PackageDimensions extractPackageDimensions(final I_M_HU hu) { final PackageDimensions packageDimensions = huPackageBL.getPackageDimensions(hu); if (packageDimensions.isUnspecified()) { throw new AdempiereException(MSG_CANNOT_DETERMINE_HU_PACKAGE_DIMENSIONS, hu.getM_HU_ID()); } return packageDimensions; } private void linkTransportationToShipment(@NonNull final I_M_InOut shipment, @NonNull final ShipperTransportationId shipperTransportationId) { final de.metas.inout.model.I_M_InOut inOutShipment = InterfaceWrapperHelper.create(shipment, de.metas.inout.model.I_M_InOut.class); inOutShipment.setM_ShipperTransportation_ID(shipperTransportationId.getRepoId()); inOutDAO.save(inOutShipment); } private ShippingWeightCalculator newWeightCalculator() { return ShippingWeightCalculator.builder() .weightSourceTypes(getWeightsSourceTypes()) .build(); } private ShippingWeightSourceTypes getWeightsSourceTypes() { return ShippingWeightSourceTypes.ofCommaSeparatedString(sysConfigBL.getValue(SYSCONFIG_WeightSourceTypes)).orElse(ShippingWeightSourceTypes.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\impl\HUShipperTransportationBL.java
1
请完成以下Java代码
public abstract class AbstractManageDLMTableProcess extends JavaProcess implements IProcessPrecondition, IProcessDefaultParametersProvider { @Param(mandatory = true, parameterName = I_AD_Table.COLUMNNAME_AD_Table_ID) protected I_AD_Table table; protected final Boolean isDLMTable(final IProcessPreconditionsContext context) { if (Check.equals(context.getTableName(), I_DLM_Partition_Config_Line.Table_Name)) { final I_DLM_Partition_Config_Line configLine = context.getSelectedModel(I_DLM_Partition_Config_Line.class); final I_AD_Table table = InterfaceWrapperHelper.create(configLine.getDLM_Referencing_Table(), I_AD_Table.class); return table.isDLM(); // if the table is already DLMed, then return false } else if (Check.equals(context.getTableName(), org.compiere.model.I_AD_Table.Table_Name)) { final I_AD_Table table = context.getSelectedModel(I_AD_Table.class); return table.isDLM(); // if the table is already DLMed, then return false } return null; }
@Override public final Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final int configLineId = parameter.getContextAsInt(I_DLM_Partition_Config_Line.COLUMNNAME_DLM_Partition_Config_Line_ID); if (configLineId > 0) { final I_DLM_Partition_Config_Line configLine = InterfaceWrapperHelper.create(getCtx(), configLineId, I_DLM_Partition_Config_Line.class, ITrx.TRXNAME_None); return configLine.getDLM_Referencing_Table_ID(); } final int tableId = parameter.getContextAsInt(I_AD_Table.COLUMNNAME_AD_Table_ID); if (tableId > 0) { return tableId; } return DEFAULT_VALUE_NOTAVAILABLE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\process\AbstractManageDLMTableProcess.java
1
请完成以下Java代码
public class UserOnline implements Serializable{ private static final long serialVersionUID = 3828664348416633856L; // session id private String id; // 用户id private String userId; // 用户名称 private String username; // 用户主机地址 private String host; // 用户登录时系统IP private String systemHost; // 状态 private String status; // session创建时间 private Date startTimestamp; // session最后访问时间 private Date lastAccessTime; // 超时时间 private Long timeout; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getSystemHost() { return systemHost; } public void setSystemHost(String systemHost) { this.systemHost = systemHost;
} public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getStartTimestamp() { return startTimestamp; } public void setStartTimestamp(Date startTimestamp) { this.startTimestamp = startTimestamp; } public Date getLastAccessTime() { return lastAccessTime; } public void setLastAccessTime(Date lastAccessTime) { this.lastAccessTime = lastAccessTime; } public Long getTimeout() { return timeout; } public void setTimeout(Long timeout) { this.timeout = timeout; } }
repos\SpringAll-master\17.Spring-Boot-Shiro-Session\src\main\java\com\springboot\pojo\UserOnline.java
1
请完成以下Java代码
public void setIsApplyToTUs (final boolean IsApplyToTUs) { set_Value (COLUMNNAME_IsApplyToTUs, IsApplyToTUs); } @Override public boolean isApplyToTUs() { return get_ValueAsBoolean(COLUMNNAME_IsApplyToTUs); } @Override public void setIsProvideAsUserAction (final boolean IsProvideAsUserAction) { set_Value (COLUMNNAME_IsProvideAsUserAction, IsProvideAsUserAction); } @Override public boolean isProvideAsUserAction() { return get_ValueAsBoolean(COLUMNNAME_IsProvideAsUserAction); } @Override public de.metas.handlingunits.model.I_M_HU_PI getM_HU_PI() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class); } @Override public void setM_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_HU_PI) { set_ValueFromPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_HU_PI); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_Value (COLUMNNAME_M_HU_PI_ID, null); else set_Value (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); }
@Override public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setM_HU_Process_ID (final int M_HU_Process_ID) { if (M_HU_Process_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Process_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Process_ID, M_HU_Process_ID); } @Override public int getM_HU_Process_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Process_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Process.java
1
请完成以下Java代码
public RemoteCall<TransactionReceipt> enter(BigInteger weiValue) { final Function function = new Function( FUNC_ENTER, Arrays.<Type>asList(), Collections.<TypeReference<?>>emptyList()); return executeRemoteCallTransaction(function, weiValue); } public static RemoteCall<Lottery> deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return deployRemoteCall(Lottery.class, web3j, credentials, contractGasProvider, BINARY, ""); } public static RemoteCall<Lottery> deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return deployRemoteCall(Lottery.class, web3j, transactionManager, contractGasProvider, BINARY, ""); } @Deprecated public static RemoteCall<Lottery> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Lottery.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); } @Deprecated public static RemoteCall<Lottery> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Lottery.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); } @Deprecated public static Lottery load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return new Lottery(contractAddress, web3j, credentials, gasPrice, gasLimit);
} @Deprecated public static Lottery load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return new Lottery(contractAddress, web3j, transactionManager, gasPrice, gasLimit); } public static Lottery load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return new Lottery(contractAddress, web3j, credentials, contractGasProvider); } public static Lottery load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return new Lottery(contractAddress, web3j, transactionManager, contractGasProvider); } }
repos\springboot-demo-master\Blockchain\src\main\java\com\et\bc\model\Lottery.java
1
请在Spring Boot框架中完成以下Java代码
public class MongoApplication implements CommandLineRunner { @Autowired private CustomerRepository customerRepository; public static void main(String[] args) { SpringApplication.run(MongoApplication.class); } @Override public void run(String... args) throws Exception { customerRepository.deleteAll(); customerRepository.save(new Customer("vector", "wang")); customerRepository.save(new Customer("bmhjqs", "wang")); System.out.println("customer fetch with findAll()"); System.out.println("-----------------------------"); for (Customer customer : customerRepository.findAll()) { System.out.println(customer); } System.out.println();
System.out.println("Customer found with findByFirstName('vector'):"); System.out.println("--------------------------------"); System.out.println(customerRepository.findByFirstName("vector")); System.out.println("Customers found with findByLastName('wang'):"); System.out.println("--------------------------------"); for (Customer customer : customerRepository.findByLastName("wang")) { System.out.println(customer); } } }
repos\spring-boot-quick-master\quick-mongodb\src\main\java\com\quick\mongodb\MongoApplication.java
2
请完成以下Java代码
public class FlowableSequenceFlowTakenEventImpl extends FlowableProcessEventImpl implements FlowableSequenceFlowTakenEvent { protected String id; protected String sourceActivityId; protected String sourceActivityName; protected String sourceActivityType; protected String targetActivityId; protected String targetActivityName; protected String targetActivityType; protected String sourceActivityBehaviorClass; protected String targetActivityBehaviorClass; public FlowableSequenceFlowTakenEventImpl(FlowableEngineEventType type) { super(type); } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getSourceActivityId() { return sourceActivityId; } public void setSourceActivityId(String sourceActivityId) { this.sourceActivityId = sourceActivityId; } @Override public String getSourceActivityName() { return sourceActivityName; } public void setSourceActivityName(String sourceActivityName) { this.sourceActivityName = sourceActivityName; } @Override public String getSourceActivityType() { return sourceActivityType; } public void setSourceActivityType(String sourceActivityType) { this.sourceActivityType = sourceActivityType; }
@Override public String getTargetActivityId() { return targetActivityId; } public void setTargetActivityId(String targetActivityId) { this.targetActivityId = targetActivityId; } @Override public String getTargetActivityName() { return targetActivityName; } public void setTargetActivityName(String targetActivityName) { this.targetActivityName = targetActivityName; } @Override public String getTargetActivityType() { return targetActivityType; } public void setTargetActivityType(String targetActivityType) { this.targetActivityType = targetActivityType; } @Override public String getSourceActivityBehaviorClass() { return sourceActivityBehaviorClass; } public void setSourceActivityBehaviorClass(String sourceActivityBehaviorClass) { this.sourceActivityBehaviorClass = sourceActivityBehaviorClass; } @Override public String getTargetActivityBehaviorClass() { return targetActivityBehaviorClass; } public void setTargetActivityBehaviorClass(String targetActivityBehaviorClass) { this.targetActivityBehaviorClass = targetActivityBehaviorClass; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\delegate\event\impl\FlowableSequenceFlowTakenEventImpl.java
1
请完成以下Java代码
public class ProcessDefinitionQueryProperty implements QueryProperty { private static final long serialVersionUID = 1L; private static final Map<String, ProcessDefinitionQueryProperty> properties = new HashMap< String, ProcessDefinitionQueryProperty >(); public static final ProcessDefinitionQueryProperty PROCESS_DEFINITION_KEY = new ProcessDefinitionQueryProperty( "RES.KEY_" ); public static final ProcessDefinitionQueryProperty PROCESS_DEFINITION_CATEGORY = new ProcessDefinitionQueryProperty( "RES.CATEGORY_" ); public static final ProcessDefinitionQueryProperty PROCESS_DEFINITION_ID = new ProcessDefinitionQueryProperty( "RES.ID_" ); public static final ProcessDefinitionQueryProperty PROCESS_DEFINITION_VERSION = new ProcessDefinitionQueryProperty( "RES.VERSION_" ); public static final ProcessDefinitionQueryProperty PROCESS_DEFINITION_APP_VERSION = new ProcessDefinitionQueryProperty("RES.APP_VERSION_");
public static final ProcessDefinitionQueryProperty PROCESS_DEFINITION_NAME = new ProcessDefinitionQueryProperty( "RES.NAME_" ); public static final ProcessDefinitionQueryProperty DEPLOYMENT_ID = new ProcessDefinitionQueryProperty( "RES.DEPLOYMENT_ID_" ); public static final ProcessDefinitionQueryProperty PROCESS_DEFINITION_TENANT_ID = new ProcessDefinitionQueryProperty("RES.TENANT_ID_"); private String name; public ProcessDefinitionQueryProperty(String name) { this.name = name; properties.put(name, this); } public String getName() { return name; } public static ProcessDefinitionQueryProperty findByName(String propertyName) { return properties.get(propertyName); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessDefinitionQueryProperty.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricCaseInstanceRestServiceImpl implements HistoricCaseInstanceRestService { protected ObjectMapper objectMapper; protected ProcessEngine processEngine; public HistoricCaseInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { this.objectMapper = objectMapper; this.processEngine = processEngine; } @Override public HistoricCaseInstanceResource getHistoricCaseInstance(String caseInstanceId) { return new HistoricCaseInstanceResourceImpl(processEngine, caseInstanceId); } @Override public List<HistoricCaseInstanceDto> getHistoricCaseInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { HistoricCaseInstanceQueryDto queryHistoricCaseInstanceDto = new HistoricCaseInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); return queryHistoricCaseInstances(queryHistoricCaseInstanceDto, firstResult, maxResults); } @Override public List<HistoricCaseInstanceDto> queryHistoricCaseInstances(HistoricCaseInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { HistoricCaseInstanceQuery query = queryDto.toQuery(processEngine); List<HistoricCaseInstance> matchingHistoricCaseInstances = QueryUtil.list(query, firstResult, maxResults); List<HistoricCaseInstanceDto> historicCaseInstanceDtoResults = new ArrayList<HistoricCaseInstanceDto>(); for (HistoricCaseInstance historicCaseInstance : matchingHistoricCaseInstances) {
HistoricCaseInstanceDto resultHistoricCaseInstanceDto = HistoricCaseInstanceDto.fromHistoricCaseInstance(historicCaseInstance); historicCaseInstanceDtoResults.add(resultHistoricCaseInstanceDto); } return historicCaseInstanceDtoResults; } @Override public CountResultDto getHistoricCaseInstancesCount(UriInfo uriInfo) { HistoricCaseInstanceQueryDto queryDto = new HistoricCaseInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); return queryHistoricCaseInstancesCount(queryDto); } @Override public CountResultDto queryHistoricCaseInstancesCount(HistoricCaseInstanceQueryDto queryDto) { HistoricCaseInstanceQuery query = queryDto.toQuery(processEngine); long count = query.count(); return new CountResultDto(count); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricCaseInstanceRestServiceImpl.java
2
请完成以下Java代码
public Message newInstance(ModelTypeInstanceContext instanceContext) { return new MessageImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); itemRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_REF) .qNameAttributeReference(ItemDefinition.class) .build(); typeBuilder.build(); } public MessageImpl(ModelTypeInstanceContext context) { super(context); } public String getName() {
return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public ItemDefinition getItem() { return itemRefAttribute.getReferenceTargetElement(this); } public void setItem(ItemDefinition item) { itemRefAttribute.setReferenceTargetElement(this, item); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MessageImpl.java
1
请完成以下Java代码
public Map<Class< ? >, String> getUpdateStatements() { return updateStatements; } public void setUpdateStatements(Map<Class< ? >, String> updateStatements) { this.updateStatements = updateStatements; } public Map<Class< ? >, String> getDeleteStatements() { return deleteStatements; } public void setDeleteStatements(Map<Class< ? >, String> deleteStatements) { this.deleteStatements = deleteStatements; } public Map<Class< ? >, String> getSelectStatements() { return selectStatements; } public void setSelectStatements(Map<Class< ? >, String> selectStatements) { this.selectStatements = selectStatements; } public boolean isDbIdentityUsed() { return isDbIdentityUsed; } public void setDbIdentityUsed(boolean isDbIdentityUsed) { this.isDbIdentityUsed = isDbIdentityUsed; } public boolean isDbHistoryUsed() { return isDbHistoryUsed; } public void setDbHistoryUsed(boolean isDbHistoryUsed) { this.isDbHistoryUsed = isDbHistoryUsed; } public boolean isCmmnEnabled() { return cmmnEnabled; } public void setCmmnEnabled(boolean cmmnEnabled) { this.cmmnEnabled = cmmnEnabled;
} public boolean isDmnEnabled() { return dmnEnabled; } public void setDmnEnabled(boolean dmnEnabled) { this.dmnEnabled = dmnEnabled; } public void setDatabaseTablePrefix(String databaseTablePrefix) { this.databaseTablePrefix = databaseTablePrefix; } public String getDatabaseTablePrefix() { return databaseTablePrefix; } public String getDatabaseSchema() { return databaseSchema; } public void setDatabaseSchema(String databaseSchema) { this.databaseSchema = databaseSchema; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\DbSqlSessionFactory.java
1
请在Spring Boot框架中完成以下Java代码
static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered { private final WebProperties properties; private final DispatcherServletPath dispatcherServletPath; protected ErrorPageCustomizer(WebProperties properties, DispatcherServletPath dispatcherServletPath) { this.properties = properties; this.dispatcherServletPath = dispatcherServletPath; } @Override public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { ErrorPage errorPage = new ErrorPage( this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath())); errorPageRegistry.addErrorPages(errorPage); } @Override public int getOrder() { return 0; } } /** * {@link BeanFactoryPostProcessor} to ensure that the target class of ErrorController * MVC beans are preserved when using AOP. */ static class PreserveErrorControllerTargetClassPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String[] errorControllerBeans = beanFactory.getBeanNamesForType(ErrorController.class, false, false); for (String errorControllerBean : errorControllerBeans) { try { beanFactory.getBeanDefinition(errorControllerBean) .setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE); } catch (Throwable ex) { // Ignore } } } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\error\ErrorMvcAutoConfiguration.java
2
请完成以下Java代码
final class ProxyClassMethodBindingsMap { private final Class<?> interfaceClass; private final LoadingCache<Class<?>, ProxyClassMethodBindings> implClass2bindings = CacheBuilder.newBuilder() .build(new CacheLoader<Class<?>, ProxyClassMethodBindings>() { @Override public ProxyClassMethodBindings load(final Class<?> implClass) throws Exception { return new ProxyClassMethodBindings(interfaceClass, implClass); } }); public ProxyClassMethodBindingsMap(final Class<?> interfaceClass) { super();
this.interfaceClass = interfaceClass; } public ProxyClassMethodBindings getMethodImplementationBindings(final Class<?> implClass) { try { return implClass2bindings.get(implClass); } catch (ExecutionException e) { throw new RuntimeException("Failed loading implementation binding for " + implClass, e.getCause()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\ProxyClassMethodBindingsMap.java
1
请完成以下Java代码
public class RemoveTaskVariablesCmd extends AbstractRemoveVariableCmd { private static final long serialVersionUID = 1L; public RemoveTaskVariablesCmd(String taskId, Collection<String> variableNames, boolean isLocal) { super(taskId, variableNames, isLocal); } protected TaskEntity getEntity() { ensureNotNull("taskId", entityId); TaskEntity task = commandContext .getTaskManager() .findTaskById(entityId); ensureNotNull("Cannot find task with id " + entityId, "task", task); checkRemoveTaskVariables(task); return task; }
@Override protected ExecutionEntity getContextExecution() { return getEntity().getExecution(); } protected void logVariableOperation(AbstractVariableScope scope) { TaskEntity task = (TaskEntity) scope; commandContext.getOperationLogManager().logVariableOperation(getLogEntryOperation(), null, task.getId(), PropertyChange.EMPTY_CHANGE); } protected void checkRemoveTaskVariables(TaskEntity task) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateTaskVariable(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\RemoveTaskVariablesCmd.java
1
请完成以下Java代码
public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Default implementation of <code>ThrowableAnalyzer</code> which is capable of also * unwrapping <code>ServletException</code>s. */
private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer { /** * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap() */ @Override protected void initExtractorMap() { super.initExtractorMap(); registerExtractor(ServletException.class, (throwable) -> { ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class); return ((ServletException) throwable).getRootCause(); }); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\ExceptionTranslationFilter.java
1
请完成以下Java代码
public static Field getField(Class<?> clazz, String fieldName) throws IllegalStateException { Assert.notNull(clazz, "Class required"); Assert.hasText(fieldName, "Field name required"); try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { // Try superclass if (clazz.getSuperclass() != null) { return getField(clazz.getSuperclass(), fieldName); } throw new IllegalStateException("Could not locate field '" + fieldName + "' on class " + clazz); } } /** * Returns the value of a (nested) field on a bean. Intended for testing. * @param bean the object * @param fieldName the field name, with "." separating nested properties * @return the value of the nested field */ public static Object getFieldValue(Object bean, String fieldName) throws IllegalAccessException { Assert.notNull(bean, "Bean cannot be null"); Assert.hasText(fieldName, "Field name required"); String[] nestedFields = StringUtils.tokenizeToStringArray(fieldName, "."); Class<?> componentClass = bean.getClass(); Object value = bean; for (String nestedField : nestedFields) { Field field = getField(componentClass, nestedField); field.setAccessible(true); value = field.get(value); if (value != null) { componentClass = value.getClass(); } } return value;
} public static @Nullable Object getProtectedFieldValue(String protectedField, Object object) { Field field = FieldUtils.getField(object.getClass(), protectedField); try { field.setAccessible(true); return field.get(object); } catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); return null; // unreachable - previous line throws exception } } public static void setProtectedFieldValue(String protectedField, Object object, Object newValue) { Field field = FieldUtils.getField(object.getClass(), protectedField); try { field.setAccessible(true); field.set(object, newValue); } catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\util\FieldUtils.java
1
请完成以下Java代码
public class Delay { public static void main(String args[]) throws InterruptedException { threadSleep(4, 1); timeunitSleep(4, 1); delayedServiceTask(5); fixedRateServiceTask(5); System.out.println("Done."); return; } private static void threadSleep(Integer iterations, Integer secondsToSleep) { for (Integer i = 0; i < iterations; i++) { System.out.println("This is loop iteration number " + i.toString()); try { Thread.sleep(secondsToSleep * 1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } } private static void timeunitSleep(Integer iterations, Integer secondsToSleep) { for (Integer i = 0; i < iterations; i++) { System.out.println("This is loop iteration number " + i.toString()); try { TimeUnit.SECONDS.sleep(secondsToSleep); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } } private static void delayedServiceTask(Integer delayInSeconds) { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS); executorService.shutdown(); }
private static void fixedRateServiceTask(Integer delayInSeconds) { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture<?> sf = executorService.scheduleAtFixedRate(Delay::someTask2, 0, delayInSeconds, TimeUnit.SECONDS); try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } sf.cancel(true); executorService.shutdown(); } private static void someTask1() { System.out.println("Task 1 completed."); } private static void someTask2() { System.out.println("Task 2 completed."); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-basic\src\main\java\com\baeldung\concurrent\delay\Delay.java
1
请完成以下Spring Boot application配置
spring.cloud.gcp.sql.instance-connection-name=baeldung-spring-boot-bootstrap:europe-west2:baeldung-spring-boot-bootstrap-db spring.cloud.gcp.sql.databas
e-name=baeldung_bootstrap_db spring.cloud.gcp.logging.enabled=true
repos\tutorials-master\spring-boot-modules\spring-boot-bootstrap\src\main\resources\application-gcp.properties
2
请完成以下Java代码
public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Tags. @param Tags Tags */ @Override public void setTags (java.lang.String Tags) { set_Value (COLUMNNAME_Tags, Tags); } /** Get Tags. @return Tags */ @Override public java.lang.String getTags () { return (java.lang.String)get_Value(COLUMNNAME_Tags); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) {
set_ValueNoCheck (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ @Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_Log.java
1
请完成以下Java代码
public void setIsDestination (boolean IsDestination) { set_Value (COLUMNNAME_IsDestination, Boolean.valueOf(IsDestination)); } /** Get IsDestination. @return IsDestination */ @Override public boolean isDestination () { Object oo = get_Value(COLUMNNAME_IsDestination); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Beleg soll per EDI übermittelt werden. @param IsEdiEnabled Beleg soll per EDI übermittelt werden */ @Override public void setIsEdiEnabled (boolean IsEdiEnabled) { set_Value (COLUMNNAME_IsEdiEnabled, Boolean.valueOf(IsEdiEnabled)); } /** Get Beleg soll per EDI übermittelt werden. @return Beleg soll per EDI übermittelt werden */ @Override public boolean isEdiEnabled () { Object oo = get_Value(COLUMNNAME_IsEdiEnabled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */
@Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ @Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_AD_InputDataSource.java
1
请在Spring Boot框架中完成以下Java代码
public class DataMessageConverter extends AbstractJsonMessageConverter implements HttpMessageConverter<DataMessage> { private static final Logger LOG = LoggerFactory.getLogger(DataMessageConverter.class); public DataMessageConverter() { } @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { LOG.info("canRead"); if (DataMessage.class.equals(clazz) && (MediaType.APPLICATION_JSON.equals(mediaType) || MediaType.APPLICATION_JSON_UTF8.equals(mediaType))) { return true; } else { return false; } } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { LOG.info("canWrite"); if (DataMessage.class.equals(clazz) && ( MediaType.APPLICATION_JSON.equals(mediaType) || MediaType.APPLICATION_JSON_UTF8.equals(mediaType))) { return true; } else { return false; } } @Override public List<MediaType> getSupportedMediaTypes() { LOG.info("getSupportedMediaTypes"); return getMediaTypes(); }
@Override public DataMessage read(Class<? extends DataMessage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { LOG.info("read"); ObjectMapper objectMapper = getObjectMapper(); JsonNode jsonNode = objectMapper.readTree(inputMessage.getBody()); String data = jsonNode.get("data").textValue(); return new DataMessage(data); } @Override public void write(DataMessage dataMessage, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { LOG.info("write"); ObjectMapper objectMapper = getObjectMapper(); OutputStream stream = outputMessage.getBody(); objectMapper.writeValue(stream, dataMessage); stream.flush(); } }
repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\config\converters\DataMessageConverter.java
2
请完成以下Java代码
public AttributeId getQualityNoteAttributeId() { final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class); return attributeDAO.retrieveActiveAttributeIdByValueOrNull(QualityNoteAttribute); } @Override public AttributeListValue retrieveAttribueValueForQualityNote(final I_M_QualityNote qualityNote) { final AttributeId attributeId = getQualityNoteAttributeId(); return Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(attributeId, qualityNote.getValue()); } @Override public void deleteAttribueValueForQualityNote(final I_M_QualityNote qualityNote) { final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); final AttributeId attributeId = getQualityNoteAttributeId(); attributesRepo.deleteAttributeValueByCode(attributeId, qualityNote.getValue()); } @Override public void modifyAttributeValueName(final I_M_QualityNote qualityNote) {
final AttributeListValue attributeValueForQualityNote = retrieveAttribueValueForQualityNote(qualityNote); if (attributeValueForQualityNote == null) { // shall not happen. All M_QualityNote entries shall have a similar M_AttributeValue return; } final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder() .id(attributeValueForQualityNote.getId()) .name(qualityNote.getName()) .active(qualityNote.isActive()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\impl\QualityNoteDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class SessionId { private final String id; @JsonCreator public SessionId(@JsonProperty("id") String id) { this.id = id; } public String getId() { return id; } public static SessionId from(String sessionId) { return new SessionId(sessionId); } @Override
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SessionId sessionId = (SessionId) o; return Objects.equals(id, sessionId.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return id; } }
repos\spring-examples-java-17\spring-security\src\main\java\itx\examples\springboot\security\springsecurity\services\dto\SessionId.java
2
请在Spring Boot框架中完成以下Java代码
public BigInteger getEDICctop111VID() { return ediCctop111VID; } /** * Sets the value of the ediCctop111VID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setEDICctop111VID(BigInteger value) { this.ediCctop111VID = value; } /** * Gets the value of the mInOutID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getMInOutID() { return mInOutID; } /** * Sets the value of the mInOutID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setMInOutID(BigInteger value) { this.mInOutID = value; } /** * Gets the value of the movementDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getMovementDate() { return movementDate; } /** * Sets the value of the movementDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setMovementDate(XMLGregorianCalendar value) { this.movementDate = value; } /** * Gets the value of the poReference property. * * @return * possible object is * {@link String } * */ public String getPOReference() { return poReference; }
/** * Sets the value of the poReference property. * * @param value * allowed object is * {@link String } * */ public void setPOReference(String value) { this.poReference = value; } /** * Gets the value of the shipmentDocumentno property. * * @return * possible object is * {@link String } * */ public String getShipmentDocumentno() { return shipmentDocumentno; } /** * Sets the value of the shipmentDocumentno property. * * @param value * allowed object is * {@link String } * */ public void setShipmentDocumentno(String value) { this.shipmentDocumentno = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop111VType.java
2
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Dimensionstyp. @param DIM_Dimension_Type_ID Dimensionstyp */ @Override public void setDIM_Dimension_Type_ID (int DIM_Dimension_Type_ID) { if (DIM_Dimension_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Type_ID, Integer.valueOf(DIM_Dimension_Type_ID)); } /** Get Dimensionstyp. @return Dimensionstyp */ @Override public int getDIM_Dimension_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Interner Name. @param InternalName Generally used to give records a name that can be safely referenced from code. */ @Override public void setInternalName (java.lang.String InternalName) { set_ValueNoCheck (COLUMNNAME_InternalName, InternalName); } /** Get Interner Name. @return Generally used to give records a name that can be safely referenced from code. */
@Override public java.lang.String getInternalName () { return (java.lang.String)get_Value(COLUMNNAME_InternalName); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Type.java
1
请完成以下Java代码
public String getPackageName() { if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return this.groupId + "." + this.artifactId; } return null; } /** * Sets the package name. * @param packageName the package name */ public void setPackageName(String packageName) { this.packageName = packageName;
} @Override public String getBaseDirectory() { return this.baseDirectory; } /** * Sets the base directory. * @param baseDirectory the base directory */ public void setBaseDirectory(String baseDirectory) { this.baseDirectory = baseDirectory; } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\MutableProjectDescription.java
1
请在Spring Boot框架中完成以下Java代码
private void markEnqueueingIsDone() { isEnqueueingDone = true; checkIfBatchIsDone(); } public void updateWorkPackagesProgress(@NonNull final AsyncBatchNotifyRequest notifyRequest) { this.wpProgress = getWPsProgress(notifyRequest); checkIfBatchIsDone(); } private void forceCompletionIfNotAlreadyCompleted() { if (checkIfBatchIsDone()) { return; } this.completableFuture.completeExceptionally(new AdempiereException("Forced exceptionally complete!") .appendParametersToMessage() .setParameter("AsyncBatchId", batchId.getRepoId())); } private synchronized boolean checkIfBatchIsDone() { if (wpProgress == null || !isEnqueueingDone) { return false; } if (wpProgress.isProcessedSuccessfully()) { Loggables.withLogger(logger, Level.INFO).addLog("AsyncBatchId={} completed successfully. ", batchId.getRepoId()); this.completableFuture.complete(null); return true; } else if (wpProgress.isProcessedWithError()) { this.completableFuture.completeExceptionally(new AdempiereException("WorkPackage completed with an exception") .appendParametersToMessage() .setParameter("AsyncBatchId", batchId.getRepoId())); return true; } return false; } @NonNull
private static WorkPackagesProgress getWPsProgress(@NonNull final AsyncBatchNotifyRequest request) { return WorkPackagesProgress.builder() .noOfProcessedWPs(request.getNoOfProcessedWPs()) .noOfEnqueuedWPs(request.getNoOfEnqueuedWPs()) .noOfErrorWPs(request.getNoOfErrorWPs()) .build(); } private static class WorkPackagesProgress { @NonNull Integer noOfEnqueuedWPs; @NonNull Integer noOfProcessedWPs; @NonNull Integer noOfErrorWPs; @Builder public WorkPackagesProgress( @NonNull final Integer noOfEnqueuedWPs, @Nullable final Integer noOfProcessedWPs, @Nullable final Integer noOfErrorWPs) { this.noOfEnqueuedWPs = noOfEnqueuedWPs; this.noOfProcessedWPs = CoalesceUtil.coalesceNotNull(noOfProcessedWPs, 0); this.noOfErrorWPs = CoalesceUtil.coalesceNotNull(noOfErrorWPs, 0); Check.assumeGreaterThanZero(noOfEnqueuedWPs, "noOfEnqueuedWPs"); Check.assumeGreaterOrEqualToZero(this.noOfProcessedWPs, this.noOfErrorWPs); } public boolean isProcessedSuccessfully() { return noOfErrorWPs == 0 && noOfProcessedWPs >= noOfEnqueuedWPs; } public boolean isProcessedWithError() { return noOfErrorWPs > 0 && (noOfProcessedWPs + noOfErrorWPs >= noOfEnqueuedWPs); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\service\AsyncBatchObserver.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
repos\tutorials-master\azure-functions\src\main\java\com\baeldung\azure\functions\blob\entity\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Integer getNumber() { return number; }
public void setNumber(Integer number) { this.number = number; } public Long getBignumber() { return bignumber; } public void setBignumber(Long bignumber) { this.bignumber = bignumber; } public Integer getTest1() { return test1; } public void setTest1(Integer test1) { this.test1 = test1; } public Integer getTest2() { return test2; } public void setTest2(Integer test2) { this.test2 = test2; } }
repos\SpringBoot-Learning-master\1.x\Chapter2-1-1\src\main\java\com\didispace\service\BlogProperties.java
2
请完成以下Java代码
private static class SingletonLookupDescriptorProvider implements LookupDescriptorProvider { private final Optional<LookupDescriptor> lookupDescriptor; private SingletonLookupDescriptorProvider(@NonNull final LookupDescriptor lookupDescriptor) { this.lookupDescriptor = Optional.of(lookupDescriptor); } @Override public Optional<LookupDescriptor> provideForScope(final LookupScope scope) { return lookupDescriptor; } } @ToString private static class MemoizingFunctionLookupDescriptorProvider implements LookupDescriptorProvider
{ private final MemoizingFunction<LookupScope, LookupDescriptor> providerFunctionMemoized; private MemoizingFunctionLookupDescriptorProvider(@NonNull final Function<LookupScope, LookupDescriptor> providerFunction) { providerFunctionMemoized = Functions.memoizing(providerFunction); } @Override public Optional<LookupDescriptor> provideForScope(final LookupScope scope) { return Optional.ofNullable(providerFunctionMemoized.apply(scope)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptorProviders.java
1
请完成以下Java代码
public static HuId ofHUValueOrNull(@Nullable final String huValue) { final String huValueNorm = StringUtils.trimBlankToNull(huValue); if (huValueNorm == null) {return null;} try { return ofRepoIdOrNull(NumberUtils.asIntOrZero(huValueNorm)); } catch (final Exception ex) { return null; } } public String toHUValue() {return String.valueOf(repoId);} int repoId; private HuId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final HuId o1, @Nullable final HuId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuId.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(addressLine1, addressLine2, city, country, county, fullName, postalCode, primaryPhone, stateOrProvince); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ReturnAddress {\n"); sb.append(" addressLine1: ").append(toIndentedString(addressLine1)).append("\n"); sb.append(" addressLine2: ").append(toIndentedString(addressLine2)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" country: ").append(toIndentedString(country)).append("\n"); sb.append(" county: ").append(toIndentedString(county)).append("\n"); sb.append(" fullName: ").append(toIndentedString(fullName)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" primaryPhone: ").append(toIndentedString(primaryPhone)).append("\n"); sb.append(" stateOrProvince: ").append(toIndentedString(stateOrProvince)).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\ReturnAddress.java
2
请完成以下Java代码
public static String specialSymbols(String str) { //去除压缩包文件字符串中特殊符号 Pattern p = Pattern.compile("\\s|\t|\r|\n|\\+|#|&|=|�|\\p{P}"); // Pattern p = Pattern.compile("\\s|\\+|#|&|=|\\p{P}"); Matcher m = p.matcher(str); return m.replaceAll(""); } public static boolean isMessyCode(String strName) { //去除字符串中的空格 制表符 换行 回车 strName = specialSymbols(strName); //处理之后转换成字符数组 char[] ch = strName.trim().toCharArray(); for (char c : ch) { //判断是否是数字或者英文字符 if (!judge(c)) { //判断是否是中日韩文 if (!isChinese(c)) { //如果不是数字或者英文字符也不是中日韩文则表示是乱码返回true return true; } } } //表示不是乱码 返回false return false; } /** * 读取文件目录树 */ public static List<ZtreeNodeVo> getTree(String rootPath) { List<ZtreeNodeVo> nodes = new ArrayList<>(); File file = new File(fileDir+rootPath);
ZtreeNodeVo node = traverse(file); nodes.add(node); return nodes; } private static ZtreeNodeVo traverse(File file) { ZtreeNodeVo pathNodeVo = new ZtreeNodeVo(); pathNodeVo.setId(file.getAbsolutePath().replace(fileDir, "").replace("\\", "/")); pathNodeVo.setName(file.getName()); pathNodeVo.setPid(file.getParent().replace(fileDir, "").replace("\\", "/")); if (file.isDirectory()) { List<ZtreeNodeVo> subNodeVos = new ArrayList<>(); File[] subFiles = file.listFiles(); if (subFiles == null) { return pathNodeVo; } for (File subFile : subFiles) { ZtreeNodeVo subNodeVo = traverse(subFile); subNodeVos.add(subNodeVo); } pathNodeVo.setChildren(subNodeVos); } return pathNodeVo; } }
repos\kkFileView-master\server\src\main\java\cn\keking\utils\RarUtils.java
1
请在Spring Boot框架中完成以下Java代码
public void create() { try { Map payload = mapper.readValue(getRequestString(), Map.class); Product p = new Product(); p.fromMap(payload); p.saveIt(); view("message", "Successfully saved product id " + p.get("id"), "code", 200); render("message"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } public void update() { try { Map payload = mapper.readValue(getRequestString(), Map.class); String id = getId(); Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; } p.fromMap(payload); p.saveIt(); view("message", "Successfully updated product id " + id, "code", 200); render("message"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } public void show() { try { String id = getId(); Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; } view("product", p); render("_product"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } public void destroy() { try { String id = getId();
Product p = Product.findById(id); if (p == null) { view("message", "Product id " + id + " not found.", "code", 200); render("message"); return; } p.delete(); view("message", "Successfully deleted product id " + id, "code", 200); render("message"); } catch (Exception e) { view("message", "There was an error.", "code", 200); render("message"); } } @Override protected String getContentType() { return "application/json"; } @Override protected String getLayout() { return null; } }
repos\tutorials-master\web-modules\java-lite\src\main\java\app\controllers\ProductsController.java
2
请完成以下Java代码
public DDOrderCandidate withForwardPPOrderId(@Nullable final PPOrderId newPPOrderId) { final PPOrderRef forwardPPOrderRefNew = PPOrderRef.withPPOrderId(forwardPPOrderRef, newPPOrderId); if (Objects.equals(this.forwardPPOrderRef, forwardPPOrderRefNew)) { return this; } return toBuilder().forwardPPOrderRef(forwardPPOrderRefNew).build(); } public Quantity getQtyToProcess() {return getQtyEntered().subtract(getQtyProcessed());} public void setQtyProcessed(final @NonNull Quantity qtyProcessed) { Quantity.assertSameUOM(this.qtyEntered, qtyProcessed); this.qtyProcessed = qtyProcessed;
updateProcessed(); } @Nullable public OrderId getSalesOrderId() { return salesOrderLineId != null ? salesOrderLineId.getOrderId() : null; } private void updateProcessed() { this.processed = getQtyToProcess().signum() == 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidate.java
1
请在Spring Boot框架中完成以下Java代码
public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers(HttpMethod.OPTIONS, "/**") .antMatchers("/app/**/*.{js,html}") .antMatchers("/i18n/**") .antMatchers("/content/**") .antMatchers("/h2-console/**") .antMatchers("/swagger-ui/index.html") .antMatchers("/test/**"); } @Override public void configure(HttpSecurity http) throws Exception { http .csrf() .disable() .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) .exceptionHandling() .authenticationEntryPoint(problemSupport) .accessDeniedHandler(problemSupport) .and() .headers() .frameOptions() .disable()
.and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/books/purchase/**").authenticated() .antMatchers("/api/register").permitAll() .antMatchers("/api/activate").permitAll() .antMatchers("/api/authenticate").permitAll() .antMatchers("/api/account/reset-password/init").permitAll() .antMatchers("/api/account/reset-password/finish").permitAll() .antMatchers("/api/**").authenticated() .antMatchers("/management/health").permitAll() .antMatchers("/management/info").permitAll() .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN) .and() .apply(securityConfigurerAdapter()); } private JWTConfigurer securityConfigurerAdapter() { return new JWTConfigurer(tokenProvider); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\SecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) { return dataManager.findJobCountByQueryCriteria(jobQuery); } @Override public void delete(JobEntity jobEntity) { delete(jobEntity, false); deleteByteArrayRef(jobEntity.getExceptionByteArrayRef()); deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef()); // Send event FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity), serviceConfiguration.getEngineName()); }
} @Override public void delete(JobEntity entity, boolean fireDeleteEvent) { if (serviceConfiguration.getInternalJobManager() != null) { serviceConfiguration.getInternalJobManager().handleJobDelete(entity); } super.delete(entity, fireDeleteEvent); } @Override public void deleteJobsByExecutionId(String executionId) { dataManager.deleteJobsByExecutionId(executionId); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\JobEntityManagerImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getAdvancedJobHandlerConfiguration() { return advancedJobHandlerConfiguration; } public void setAdvancedJobHandlerConfiguration(String advancedJobHandlerConfiguration) { this.advancedJobHandlerConfiguration = advancedJobHandlerConfiguration; } @ApiModelProperty(example = "custom value") public String getCustomValues() { return customValues; } public void setCustomValues(String customValues) { this.customValues = customValues; } @ApiModelProperty(example = "node1") public String getLockOwner() {
return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobResponse.java
2