instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static class PickFromHUsList { private final ArrayList<PickFromHU> list = new ArrayList<>(); PickFromHUsList() {} public void add(@NonNull final PickFromHU pickFromHU) {list.add(pickFromHU);} public List<I_M_HU> toHUsList() {return list.stream().map(PickFromHU::toM_HU).collect(ImmutableList.toImmutableList());} public PickFromHU getSingleHU() {return CollectionUtils.singleElement(list);} public boolean isSingleHUAlreadyPacked( final boolean checkIfAlreadyPacked, @NonNull final ProductId productId, @NonNull final Quantity qty, @Nullable final HuPackingInstructionsId packingInstructionsId) { if (list.size() != 1) { return false; } final PickFromHU hu = list.get(0); // NOTE we check isGeneratedFromInventory because we want to avoid splitting an HU that we just generated it, even if checkIfAlreadyPacked=false if (checkIfAlreadyPacked || hu.isGeneratedFromInventory()) { return hu.isAlreadyPacked(productId, qty, packingInstructionsId); } else { return false; } } } // // // ------------------------------------ //
// @Value(staticConstructor = "of") @EqualsAndHashCode(doNotUseGetters = true) private static class HuPackingInstructionsIdAndCaptionAndCapacity { @NonNull HuPackingInstructionsId huPackingInstructionsId; @NonNull String caption; @Nullable Capacity capacity; @Nullable public Capacity getCapacityOrNull() {return capacity;} @SuppressWarnings("unused") @NonNull public Optional<Capacity> getCapacity() {return Optional.ofNullable(capacity);} public TUPickingTarget toTUPickingTarget() { return TUPickingTarget.ofPackingInstructions(huPackingInstructionsId, caption); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PackToHUsProducer.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractSalesContracts insuranceContractSalesContracts = (InsuranceContractSalesContracts) o; return Objects.equals(this.name, insuranceContractSalesContracts.name) && Objects.equals(this.careType, insuranceContractSalesContracts.careType); } @Override public int hashCode() { return Objects.hash(name, careType); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractSalesContracts {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" careType: ").append(toIndentedString(careType)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractSalesContracts.java
2
请在Spring Boot框架中完成以下Java代码
public List<IdentityLinkEntity> deleteScopeDefinitionIdentityLink(String scopeDefinitionId, String scopeType, String userId, String groupId) { return getIdentityLinkEntityManager().deleteScopeDefinitionIdentityLink(scopeDefinitionId, scopeType, userId, groupId); } @Override public void deleteIdentityLinksByTaskId(String taskId) { getIdentityLinkEntityManager().deleteIdentityLinksByTaskId(taskId); } @Override public void deleteIdentityLinksByProcessDefinitionId(String processDefinitionId) { getIdentityLinkEntityManager().deleteIdentityLinksByProcDef(processDefinitionId); } @Override public void deleteIdentityLinksByScopeDefinitionIdAndType(String scopeDefinitionId, String scopeType) { getIdentityLinkEntityManager().deleteIdentityLinksByScopeDefinitionIdAndScopeType(scopeDefinitionId, scopeType); } @Override
public void deleteIdentityLinksByScopeIdAndType(String scopeId, String scopeType) { getIdentityLinkEntityManager().deleteIdentityLinksByScopeIdAndScopeType(scopeId, scopeType); } @Override public void deleteIdentityLinksByProcessInstanceId(String processInstanceId) { getIdentityLinkEntityManager().deleteIdentityLinksByProcessInstanceId(processInstanceId); } @Override public void bulkDeleteIdentityLinksForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) { getIdentityLinkEntityManager().bulkDeleteIdentityLinksForScopeIdsAndScopeType(scopeIds, scopeType); } public IdentityLinkEntityManager getIdentityLinkEntityManager() { return configuration.getIdentityLinkEntityManager(); } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\IdentityLinkServiceImpl.java
2
请完成以下Java代码
public java.lang.String getRequestURI() { return get_ValueAsString(COLUMNNAME_RequestURI); } /** * Status AD_Reference_ID=541316 * Reference name: StatusList */ public static final int STATUS_AD_Reference_ID=541316; /** Empfangen = Empfangen */ public static final String STATUS_Empfangen = "Empfangen"; /** Verarbeitet = Verarbeitet */ public static final String STATUS_Verarbeitet = "Verarbeitet"; /** Fehler = Fehler */ public static final String STATUS_Fehler = "Fehler"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); }
@Override public void setTime (final java.sql.Timestamp Time) { set_Value (COLUMNNAME_Time, Time); } @Override public java.sql.Timestamp getTime() { return get_ValueAsTimestamp(COLUMNNAME_Time); } @Override public void setUI_Trace_ExternalId (final @Nullable java.lang.String UI_Trace_ExternalId) { set_Value (COLUMNNAME_UI_Trace_ExternalId, UI_Trace_ExternalId); } @Override public java.lang.String getUI_Trace_ExternalId() { return get_ValueAsString(COLUMNNAME_UI_Trace_ExternalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit.java
1
请完成以下Java代码
public boolean existsByTenantAndKeyAndStatusOneOf(TenantId tenantId, String key, JobStatus... statuses) { return jobRepository.existsByTenantIdAndKeyAndStatusIn(tenantId.getId(), key, Arrays.stream(statuses).toList()); } @Override public boolean existsByTenantIdAndTypeAndStatusOneOf(TenantId tenantId, JobType type, JobStatus... statuses) { return jobRepository.existsByTenantIdAndTypeAndStatusIn(tenantId.getId(), type, Arrays.stream(statuses).toList()); } @Override public boolean existsByTenantIdAndEntityIdAndStatusOneOf(TenantId tenantId, EntityId entityId, JobStatus... statuses) { return jobRepository.existsByTenantIdAndEntityIdAndStatusIn(tenantId.getId(), entityId.getId(), Arrays.stream(statuses).toList()); } @Override public Job findOldestByTenantIdAndTypeAndStatusForUpdate(TenantId tenantId, JobType type, JobStatus status) { return DaoUtil.getData(jobRepository.findOldestByTenantIdAndTypeAndStatusForUpdate(tenantId.getId(), type.name(), status.name())); } @Override public void removeByTenantId(TenantId tenantId) { jobRepository.deleteByTenantId(tenantId.getId()); } @Override
public int removeByEntityId(TenantId tenantId, EntityId entityId) { return jobRepository.deleteByEntityId(entityId.getId()); } @Override public EntityType getEntityType() { return EntityType.JOB; } @Override protected Class<JobEntity> getEntityClass() { return JobEntity.class; } @Override protected JpaRepository<JobEntity, UUID> getRepository() { return jobRepository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\job\JpaJobDao.java
1
请在Spring Boot框架中完成以下Java代码
public PackagingDetailsType getPackagingDetails() { return packagingDetails; } /** * Sets the value of the packagingDetails property. * * @param value * allowed object is * {@link PackagingDetailsType } * */ public void setPackagingDetails(PackagingDetailsType value) { this.packagingDetails = value; } /** * Packaging identification information requested by the customer - details about the packaging items * * @return * possible object is * {@link PackagingIdentificationType } * */ public PackagingIdentificationType getPackagingIdentification() { return packagingIdentification; } /** * Sets the value of the packagingIdentification property. * * @param value * allowed object is * {@link PackagingIdentificationType } * */ public void setPackagingIdentification(PackagingIdentificationType value) { this.packagingIdentification = value; } /** * Planning Quantity Gets the value of the planningQuantity property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the planningQuantity property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPlanningQuantity().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link PlanningQuantityType } * * */ public List<PlanningQuantityType> getPlanningQuantity() { if (planningQuantity == null) { planningQuantity = new ArrayList<PlanningQuantityType>(); } return this.planningQuantity; } /** * Gets the value of the forecastListLineItemExtension property. * * @return * possible object is * {@link ForecastListLineItemExtensionType } * */ public ForecastListLineItemExtensionType getForecastListLineItemExtension() { return forecastListLineItemExtension; } /** * Sets the value of the forecastListLineItemExtension property. * * @param value * allowed object is * {@link ForecastListLineItemExtensionType } * */ public void setForecastListLineItemExtension(ForecastListLineItemExtensionType value) { this.forecastListLineItemExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ForecastListLineItemType.java
2
请完成以下Java代码
public ResponseEntity<PageResult<AppDto>> queryApp(AppQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(appService.queryAll(criteria,pageable),HttpStatus.OK); } @Log("新增应用") @ApiOperation(value = "新增应用") @PostMapping @PreAuthorize("@el.check('app:add')") public ResponseEntity<Object> createApp(@Validated @RequestBody App resources){ appService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @Log("修改应用") @ApiOperation(value = "修改应用")
@PutMapping @PreAuthorize("@el.check('app:edit')") public ResponseEntity<Object> updateApp(@Validated @RequestBody App resources){ appService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除应用") @ApiOperation(value = "删除应用") @DeleteMapping @PreAuthorize("@el.check('app:del')") public ResponseEntity<Object> deleteApp(@RequestBody Set<Long> ids){ appService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\AppController.java
1
请完成以下Java代码
public static Image getImage2(final String fileNameWithoutExtension) { final ImageIcon imageIcon = getImageIcon2(fileNameWithoutExtension); if(imageIcon == null) { return null; } return imageIcon.getImage(); } /** * Loads {@link Image} of given <code>url</code> and apply theme's RGB filter if any. * * @param url * @return {@link Image} or null */ private static final Optional<Image> loadImage(final URL url)
{ if (url == null) { return Optional.absent(); } final Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = toolkit.getImage(url); if (image == null) { return Optional.absent(); } return Optional.fromNullable(image); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\images\Images.java
1
请完成以下Java代码
public void setIsProcessing (final boolean IsProcessing) { set_Value (COLUMNNAME_IsProcessing, IsProcessing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_IsProcessing); } @Override public void setLastEnqueued (final @Nullable java.sql.Timestamp LastEnqueued) { set_Value (COLUMNNAME_LastEnqueued, LastEnqueued); } @Override public java.sql.Timestamp getLastEnqueued() { return get_ValueAsTimestamp(COLUMNNAME_LastEnqueued); } @Override public void setLastProcessed (final @Nullable java.sql.Timestamp LastProcessed) { set_Value (COLUMNNAME_LastProcessed, LastProcessed); } @Override public java.sql.Timestamp getLastProcessed() { return get_ValueAsTimestamp(COLUMNNAME_LastProcessed); } @Override public de.metas.async.model.I_C_Queue_WorkPackage getLastProcessed_WorkPackage() { return get_ValueAsPO(COLUMNNAME_LastProcessed_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class); } @Override public void setLastProcessed_WorkPackage(final de.metas.async.model.I_C_Queue_WorkPackage LastProcessed_WorkPackage) { set_ValueFromPO(COLUMNNAME_LastProcessed_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, LastProcessed_WorkPackage); } @Override public void setLastProcessed_WorkPackage_ID (final int LastProcessed_WorkPackage_ID) { if (LastProcessed_WorkPackage_ID < 1) set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, null); else set_Value (COLUMNNAME_LastProcessed_WorkPackage_ID, LastProcessed_WorkPackage_ID); } @Override public int getLastProcessed_WorkPackage_ID() { return get_ValueAsInt(COLUMNNAME_LastProcessed_WorkPackage_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 de.metas.async.model.I_C_Async_Batch getParent_Async_Batch() { return get_ValueAsPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class); }
@Override public void setParent_Async_Batch(final de.metas.async.model.I_C_Async_Batch Parent_Async_Batch) { set_ValueFromPO(COLUMNNAME_Parent_Async_Batch_ID, de.metas.async.model.I_C_Async_Batch.class, Parent_Async_Batch); } @Override public void setParent_Async_Batch_ID (final int Parent_Async_Batch_ID) { if (Parent_Async_Batch_ID < 1) set_Value (COLUMNNAME_Parent_Async_Batch_ID, null); else set_Value (COLUMNNAME_Parent_Async_Batch_ID, Parent_Async_Batch_ID); } @Override public int getParent_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_Parent_Async_Batch_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch.java
1
请完成以下Java代码
public void setCategoryType (String CategoryType) { set_Value (COLUMNNAME_CategoryType, CategoryType); } /** Get Category Type. @return Source of the Journal with this category */ public String getCategoryType () { return (String)get_Value(COLUMNNAME_CategoryType); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set GL Category. @param GL_Category_ID General Ledger Category */ public void setGL_Category_ID (int GL_Category_ID) { if (GL_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID)); } /** Get GL Category. @return General Ledger Category */ public int getGL_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); }
/** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Category.java
1
请在Spring Boot框架中完成以下Java代码
public final class BPartnerEmailParams implements IEmailParameters { private static final Logger logger = LogManager.getLogger(BPartnerEmailParams.class); private final String attachmentPrefix; private final static MADBoilerPlate DEFAULT_TEXT_PRESET = null; private final String exportFilePrefix; private final I_AD_User from; private final static String MESSAGE = null; private final String subject; private final String title; private final String to; public BPartnerEmailParams(final ProcessInfo pi, final IParams params) { to = updateTo(params); attachmentPrefix = pi.getTitle(); title = pi.getTitle(); subject = pi.getTitle(); exportFilePrefix = pi.getTitle(); from = Services.get(IUserDAO.class).retrieveUserOrNull(Env.getCtx(), Env.getAD_User_ID(Env.getCtx())); } private String updateTo(final IParams params) { String toTmp = ""; if (!params.hasParameter(I_C_BPartner.COLUMNNAME_C_BPartner_ID)) { throw new IllegalArgumentException("Process instance doesn't contain a business partner as parameter"); } // find the C_BPartner_ID parameter final int bpartnerId = params.getParameterAsInt(I_C_BPartner.COLUMNNAME_C_BPartner_ID, -1); if (bpartnerId <= 0) { logger.info("Process parameter " + I_C_BPartner.COLUMNNAME_C_BPartner_ID + " didn't contain a value"); } else { final int userId = MBPartner.getDefaultContactId(bpartnerId); if (userId > 0) { final I_AD_User contanct = Services.get(IUserDAO.class).retrieveUserOrNull(Env.getCtx(), userId); if (contanct.getEMail() == null || "".equals(contanct.getEMail())) { logger.info("Default contact " + contanct + " doesn't have an email address"); } else { toTmp = contanct.getEMail(); } } } return toTmp; } /** * @param defaultValue * ignored * @return the title of the process */
@Override public String getAttachmentPrefix(final String defaultValue) { return attachmentPrefix; } /** * @return <code>null</code> */ @Override public MADBoilerPlate getDefaultTextPreset() { return DEFAULT_TEXT_PRESET; } /** * @return the title of the process */ @Override public String getExportFilePrefix() { return exportFilePrefix; } @Override public I_AD_User getFrom() { return from; } /** * @return <code>null</code> */ @Override public String getMessage() { return MESSAGE; } /** * @return the title of the process */ @Override public String getSubject() { return subject; } /** * @return the title of the process */ @Override public String getTitle() { return title; } @Override public String getTo() { return to; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\BPartnerEmailParams.java
2
请在Spring Boot框架中完成以下Java代码
public class QueuePackageProcessorId implements RepoIdAware { int repoId; @JsonCreator public static QueuePackageProcessorId ofRepoId(final int repoId) { return new QueuePackageProcessorId(repoId); } @Nullable public static QueuePackageProcessorId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new QueuePackageProcessorId(repoId) : null; } public static int toRepoId(@Nullable final QueuePackageProcessorId queuePackageProcessorId)
{ return queuePackageProcessorId != null ? queuePackageProcessorId.getRepoId() : -1; } private QueuePackageProcessorId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, I_C_Queue_PackageProcessor.COLUMNNAME_C_Queue_PackageProcessor_ID); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\QueuePackageProcessorId.java
2
请完成以下Java代码
public class HandlerMethodArgumentResolverComposite implements HandlerMethodArgumentResolver { private final List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); private final Map<MethodParameter, HandlerMethodArgumentResolver> argumentResolverCache = new ConcurrentHashMap<>(256); /** * Add the given {@link HandlerMethodArgumentResolver}. * @param resolver the argument resolver */ public void addResolver(HandlerMethodArgumentResolver resolver) { this.argumentResolvers.add(resolver); } /** * Return a read-only list with the contained resolvers, or an empty list. */ public List<HandlerMethodArgumentResolver> getResolvers() { return Collections.unmodifiableList(this.argumentResolvers); } /** * Whether the given {@linkplain MethodParameter method parameter} is * supported by any registered {@link HandlerMethodArgumentResolver}. */ @Override public boolean supportsParameter(MethodParameter parameter) { return (getArgumentResolver(parameter) != null); } /** * Iterate over registered
* {@link HandlerMethodArgumentResolver HandlerMethodArgumentResolvers} * and invoke the one that supports it. * @throws IllegalArgumentException if no suitable argument resolver is found */ @Override public @Nullable Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception { HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter); if (resolver == null) { throw new IllegalArgumentException("Unsupported parameter [%s].".formatted(parameter)); } return resolver.resolveArgument(parameter, environment); } /** * Find a registered {@link HandlerMethodArgumentResolver} that supports * the given method parameter. * @param parameter the method parameter */ public @Nullable HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) { return this.argumentResolverCache.computeIfAbsent(parameter, (p) -> { for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) { if (resolver.supportsParameter(parameter)) { return resolver; } } return null; }); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\HandlerMethodArgumentResolverComposite.java
1
请完成以下Java代码
public boolean isStrictMode() { return strictMode; } public DmnEngineConfiguration setStrictMode(boolean strictMode) { this.strictMode = strictMode; return this; } @Override public DmnEngineConfiguration setClock(Clock clock) { this.clock = clock; return this; } @Override public DmnEngineConfiguration setDatabaseSchemaUpdate(String databaseSchemaUpdate) { this.databaseSchemaUpdate = databaseSchemaUpdate; return this; } public void setHitPolicyBehaviors(Map<String, AbstractHitPolicy> hitPolicyBehaviors) { this.hitPolicyBehaviors = hitPolicyBehaviors; } public Map<String, AbstractHitPolicy> getHitPolicyBehaviors() { return hitPolicyBehaviors; } public void setCustomHitPolicyBehaviors(Map<String, AbstractHitPolicy> customHitPolicyBehaviors) { this.customHitPolicyBehaviors = customHitPolicyBehaviors; } public Map<String, AbstractHitPolicy> getCustomHitPolicyBehaviors() { return customHitPolicyBehaviors; } public DecisionRequirementsDiagramGenerator getDecisionRequirementsDiagramGenerator() { return decisionRequirementsDiagramGenerator; } public DmnEngineConfiguration setDecisionRequirementsDiagramGenerator(DecisionRequirementsDiagramGenerator decisionRequirementsDiagramGenerator) {
this.decisionRequirementsDiagramGenerator = decisionRequirementsDiagramGenerator; return this; } public boolean isCreateDiagramOnDeploy() { return isCreateDiagramOnDeploy; } public DmnEngineConfiguration setCreateDiagramOnDeploy(boolean isCreateDiagramOnDeploy) { this.isCreateDiagramOnDeploy = isCreateDiagramOnDeploy; return this; } public String getDecisionFontName() { return decisionFontName; } public DmnEngineConfiguration setDecisionFontName(String decisionFontName) { this.decisionFontName = decisionFontName; return this; } public String getLabelFontName() { return labelFontName; } public DmnEngineConfiguration setLabelFontName(String labelFontName) { this.labelFontName = labelFontName; return this; } public String getAnnotationFontName() { return annotationFontName; } public DmnEngineConfiguration setAnnotationFontName(String annotationFontName) { this.annotationFontName = annotationFontName; return this; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngineConfiguration.java
1
请完成以下Java代码
public int getC_Year_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_ID); if (ii == null) return 0; return ii.intValue(); } /** Set End Date. @param EndDate Last effective date (inclusive) */ public void setEndDate (Timestamp EndDate) { set_Value (COLUMNNAME_EndDate, EndDate); } /** Get End Date. @return Last effective date (inclusive) */ public Timestamp getEndDate () { return (Timestamp)get_Value(COLUMNNAME_EndDate); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Period No. @param PeriodNo Unique Period Number */ public void setPeriodNo (int PeriodNo) { set_Value (COLUMNNAME_PeriodNo, Integer.valueOf(PeriodNo)); } /** Get Period No. @return Unique Period Number */ public int getPeriodNo () { Integer ii = (Integer)get_Value(COLUMNNAME_PeriodNo); if (ii == null) return 0; return ii.intValue(); } /** PeriodType AD_Reference_ID=115 */ public static final int PERIODTYPE_AD_Reference_ID=115; /** Standard Calendar Period = S */ public static final String PERIODTYPE_StandardCalendarPeriod = "S"; /** Adjustment Period = A */ public static final String PERIODTYPE_AdjustmentPeriod = "A"; /** Set Period Type. @param PeriodType Period Type */ public void setPeriodType (String PeriodType) { set_ValueNoCheck (COLUMNNAME_PeriodType, PeriodType);
} /** Get Period Type. @return Period Type */ public String getPeriodType () { return (String)get_Value(COLUMNNAME_PeriodType); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Period.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } public List<Author> fetchFirst5() { return authorRepository.findFirst5By(); } public List<Author> fetchFirst5ByAge(int age) { return authorRepository.findFirst5ByAge(age); } public List<Author> fetchFirst5ByAgeGreaterThanEqual(int age) { return authorRepository.findFirst5ByAgeGreaterThanEqual(age); } public List<Author> fetchFirst5ByAgeLessThan(int age) { return authorRepository.findFirst5ByAgeLessThan(age); } public List<Author> fetchFirst5ByAgeOrderByNameDesc(int age) {
return authorRepository.findFirst5ByAgeOrderByNameDesc(age); } public List<Author> fetchFirst5ByGenreOrderByAgeAsc(String genre) { return authorRepository.findFirst5ByGenreOrderByAgeAsc(genre); } public List<Author> fetchFirst5ByAgeGreaterThanEqualOrderByNameAsc(int age) { return authorRepository.findFirst5ByAgeGreaterThanEqualOrderByNameAsc(age); } public List<Author> fetchFirst5ByGenreAndAgeLessThanOrderByNameDesc(String genre, int age) { return authorRepository.findFirst5ByGenreAndAgeLessThanOrderByNameDesc(genre, age); } public List<AuthorDto> fetchFirst5ByOrderByAgeAsc() { return authorRepository.findFirst5ByOrderByAgeAsc(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLimitResultSizeViaQueryCreator\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public class M_Material_Tracking { @Init public void setupCallouts() { CopyRecordFactory.enableForTableName(I_M_Material_Tracking.Table_Name); // Setup callout M_Material_Tracking final IProgramaticCalloutProvider calloutProvider = Services.get(IProgramaticCalloutProvider.class); calloutProvider.registerAnnotatedCallout(new de.metas.materialtracking.ch.lagerkonf.callout.M_Material_Tracking()); } /** * Note: ifColumnsChanged is adapted to the BL that is called. if you change the BL, pls check if ifColumnsChanged also needs to be changed */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_M_Material_Tracking.COLUMNNAME_Lot, I_M_Material_Tracking.COLUMNNAME_C_BPartner_ID, I_M_Material_Tracking.COLUMNNAME_M_Product_ID }) public void createMaterialTrackingAttributeValue(final I_M_Material_Tracking materialTracking) { final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class); materialTrackingAttributeBL.createOrUpdateMaterialTrackingAttributeValue(materialTracking); // NOTE: in case of a new material tracking, the generated M_AttributeValue.Value will be "0" (or a random number) because M_Material_Tracking is not yet saved // so we will need to update it after save (new) } /** * After a new material tracking is saved, we need to make sure M_AttributeValue.Value is correct */ @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW }) public void updateMaterialTrackingAttributeValue_Value(final I_M_Material_Tracking materialTracking)
{ final AttributeValueId attributeValueId = AttributeValueId.ofRepoId(materialTracking.getM_AttributeValue_ID()); final IMaterialTrackingAttributeBL materialTrackingAttributeBL = Services.get(IMaterialTrackingAttributeBL.class); final String attributeValue_Value = materialTrackingAttributeBL.getMaterialTrackingIdStr(materialTracking); Services.get(IAttributeDAO.class).changeAttributeValue(AttributeListValueChangeRequest.builder() .id(attributeValueId) .value(Optional.ofNullable(attributeValue_Value)) .build()); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void deleteMaterialTrackingAttributeValue(final I_M_Material_Tracking materialTracking) { final AttributeValueId attributeValueId = AttributeValueId.ofRepoIdOrNull(materialTracking.getM_AttributeValue_ID()); if (attributeValueId == null) { // nothing to do return; } // NOTE: instead of deleting attribute value, just inactivate it because it might be that is used Services.get(IAttributeDAO.class).changeAttributeValue(AttributeListValueChangeRequest.builder() .id(attributeValueId) .active(false) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\M_Material_Tracking.java
1
请完成以下Java代码
public Set<Class> findAllClassesUsingClassLoader(String packageName) { InputStream stream = ClassLoader.getSystemClassLoader() .getResourceAsStream(packageName.replaceAll("[.]", "/")); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); return reader.lines() .filter(line -> line.endsWith(".class")) .map(line -> getClass(line, packageName)) .collect(Collectors.toSet()); } private Class getClass(String className, String packageName) { try { return Class.forName(packageName + "." + className.substring(0, className.lastIndexOf('.'))); } catch (ClassNotFoundException e) { LOG.error("<<Class not found>>"); } return null; } public Set<Class> findAllClassesUsingReflectionsLibrary(String packageName) { Reflections reflections = new Reflections(packageName, new SubTypesScanner(false));
return reflections.getSubTypesOf(Object.class) .stream() .collect(Collectors.toSet()); } public Set<Class> findAllClassesUsingGoogleGuice(String packageName) throws IOException { return ClassPath.from(ClassLoader.getSystemClassLoader()) .getAllClasses() .stream() .filter(clazz -> clazz.getPackageName() .equalsIgnoreCase(packageName)) .map(clazz -> clazz.load()) .collect(Collectors.toSet()); } }
repos\tutorials-master\core-java-modules\core-java-reflection\src\main\java\com\baeldung\reflection\access\packages\AccessingAllClassesInPackage.java
1
请完成以下Java代码
public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed; } } public static class Truck extends Vehicle {
private double payloadCapacity; @JsonCreator public Truck(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("payload") double payloadCapacity) { super(make, model); this.payloadCapacity = payloadCapacity; } public double getPayloadCapacity() { return payloadCapacity; } public void setPayloadCapacity(double payloadCapacity) { this.payloadCapacity = payloadCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\SubTypeConstructorStructure.java
1
请完成以下Java代码
public void setPOL_ID (final int POL_ID) { if (POL_ID < 1) set_Value (COLUMNNAME_POL_ID, null); else set_Value (COLUMNNAME_POL_ID, POL_ID); } @Override public int getPOL_ID() { return get_ValueAsInt(COLUMNNAME_POL_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); }
@Override public void setShipper_BPartner_ID (final int Shipper_BPartner_ID) { if (Shipper_BPartner_ID < 1) set_Value (COLUMNNAME_Shipper_BPartner_ID, null); else set_Value (COLUMNNAME_Shipper_BPartner_ID, Shipper_BPartner_ID); } @Override public int getShipper_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_BPartner_ID); } @Override public void setShipper_Location_ID (final int Shipper_Location_ID) { if (Shipper_Location_ID < 1) set_Value (COLUMNNAME_Shipper_Location_ID, null); else set_Value (COLUMNNAME_Shipper_Location_ID, Shipper_Location_ID); } @Override public int getShipper_Location_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_Location_ID); } @Override public void setTrackingID (final @Nullable java.lang.String TrackingID) { set_Value (COLUMNNAME_TrackingID, TrackingID); } @Override public java.lang.String getTrackingID() { return get_ValueAsString(COLUMNNAME_TrackingID); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { set_Value (COLUMNNAME_VesselName, VesselName); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShipperTransportation.java
1
请完成以下Java代码
public class ServiceAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, ServiceAuthenticationDetails> { private final Pattern artifactPattern; private ServiceProperties serviceProperties; /** * Creates an implementation that uses the specified ServiceProperties and the default * CAS artifactParameterName. * @param serviceProperties The ServiceProperties to use to construct the serviceUrl. */ public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties) { this(serviceProperties, ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER); } /** * Creates an implementation that uses the specified artifactParameterName * @param serviceProperties The ServiceProperties to use to construct the serviceUrl. * @param artifactParameterName the artifactParameterName that is removed from the * current URL. The result becomes the service url. Cannot be null and cannot be an * empty String. */ public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties, String artifactParameterName) { Assert.notNull(serviceProperties, "serviceProperties cannot be null"); this.serviceProperties = serviceProperties; this.artifactPattern = DefaultServiceAuthenticationDetails.createArtifactPattern(artifactParameterName); } /**
* @param context the {@code HttpServletRequest} object. * @return the {@code ServiceAuthenticationDetails} containing information about the * current request */ @Override public ServiceAuthenticationDetails buildDetails(HttpServletRequest context) { try { return new DefaultServiceAuthenticationDetails(this.serviceProperties.getService(), context, this.artifactPattern); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\authentication\ServiceAuthenticationDetailsSource.java
1
请在Spring Boot框架中完成以下Java代码
public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\EventSubscriptionResponse.java
2
请完成以下Java代码
final String constructFirstPageUri(final UriComponentsBuilder uriBuilder, final int size) { return uriBuilder.replaceQueryParam(PAGE, 0) .replaceQueryParam("size", size) .build() .encode() .toUriString(); } final String constructLastPageUri(final UriComponentsBuilder uriBuilder, final int totalPages, final int size) { return uriBuilder.replaceQueryParam(PAGE, totalPages) .replaceQueryParam("size", size) .build() .encode() .toUriString(); } final boolean hasNextPage(final int page, final int totalPages) { return page < (totalPages - 1); } final boolean hasPreviousPage(final int page) { return page > 0;
} final boolean hasFirstPage(final int page) { return hasPreviousPage(page); } final boolean hasLastPage(final int page, final int totalPages) { return (totalPages > 1) && hasNextPage(page, totalPages); } // template protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) { final String resourceName = clazz.getSimpleName() .toLowerCase() + "s"; uriBuilder.path("/" + resourceName); } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\hateoas\listener\PaginatedResultsRetrievedDiscoverabilityListener.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true #spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect #spring.jpa.prop
erties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.datasource.initialization-mode=always spring.datasource.platform=mysql spring.jpa.open-in-view=false
repos\Hibernate-SpringBoot-master\HibernateSpringBootPesimisticForceIncrement\src\main\resources\application.properties
2
请完成以下Java代码
public Optional<Object> get_ValueIfExists(final @NonNull String variableName, final @NonNull Class<?> targetType) { if (excludeVariableName.equals(variableName)) { return Optional.empty(); } return parent.get_ValueIfExists(variableName, targetType); } } @ToString private static class RangeAwareParamsAsEvaluatee implements Evaluatee2 { private final IRangeAwareParams params; private RangeAwareParamsAsEvaluatee(@NonNull final IRangeAwareParams params) { this.params = params; } @Override public boolean has_Variable(final String variableName) { return params.hasParameter(variableName); } @SuppressWarnings("unchecked") @Override public <T> T get_ValueAsObject(final String variableName) { return (T)params.getParameterAsObject(variableName); } @Override public BigDecimal get_ValueAsBigDecimal(final String variableName, final BigDecimal defaultValue) { final BigDecimal value = params.getParameterAsBigDecimal(variableName); return value != null ? value : defaultValue; }
@Override public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED) { return params.getParameterAsBool(variableName); } @Override public Date get_ValueAsDate(final String variableName, final Date defaultValue) { final Timestamp value = params.getParameterAsTimestamp(variableName); return value != null ? value : defaultValue; } @Override public Integer get_ValueAsInt(final String variableName, final Integer defaultValue) { final int defaultValueInt = defaultValue != null ? defaultValue : 0; return params.getParameterAsInt(variableName, defaultValueInt); } @Override public String get_ValueAsString(final String variableName) { return params.getParameterAsString(variableName); } @Override public String get_ValueOldAsString(final String variableName) { return get_ValueAsString(variableName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java
1
请完成以下Java代码
public void setCM_ChatType_ID (int CM_ChatType_ID) { if (CM_ChatType_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID)); } /** Get Chat Type. @return Type of discussion / chat */ public int getCM_ChatType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Self-Service. @param IsSelfService This is a Self-Service entry or this entry can be changed via Self-Service */ public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); }
/** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatTypeUpdate.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } public I_M_Product getSubstitute() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getSubstitute_ID(), get_TrxName()); } /** Set Substitute. @param Substitute_ID Entity which can be used in place of this entity
*/ public void setSubstitute_ID (int Substitute_ID) { if (Substitute_ID < 1) set_ValueNoCheck (COLUMNNAME_Substitute_ID, null); else set_ValueNoCheck (COLUMNNAME_Substitute_ID, Integer.valueOf(Substitute_ID)); } /** Get Substitute. @return Entity which can be used in place of this entity */ public int getSubstitute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Substitute_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Substitute.java
1
请完成以下Java代码
public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } @Override public String getJobHandlerConfiguration() { return jobHandlerConfiguration; } public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) {
this.endDate = endDate; } @Override public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH); } @Override public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getCorrelationId() { // v5 Jobs have no correlationId return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java
1
请完成以下Java代码
public ImmutableList<String> getDetailGroupKeysForType(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider) { return streamEligibleConfigs(attributeType, valueProvider) .map(JsonMappingConfig::getGroupKey) .filter(Check::isNotBlank) .distinct() .collect(ImmutableList.toImmutableList()); } public List<JsonDetail> getDetailsForGroupAndType( @NonNull final String attributeGroupKey, @NonNull final String attributeType, @NonNull final Function<String, String> valueProvider) { final Map<Integer, String> detailsByKindId = streamEligibleConfigs(attributeType, valueProvider) .filter(config -> attributeGroupKey.equals(config.getGroupKey())) .filter(config -> Check.isNotBlank(config.getAttributeKey()))
.map(config -> new AbstractMap.SimpleImmutableEntry<>( Integer.parseInt(config.getAttributeKey()), valueProvider.apply(config.getAttributeValue()))) .filter(entry -> Check.isNotBlank(entry.getValue())) .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.joining(" ")))); return detailsByKindId.entrySet().stream() .map(entry -> JsonDetail.builder() .kindId(entry.getKey()) .value(entry.getValue()) .build()) .collect(Collectors.toList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftMappingConfigs.java
1
请完成以下Java代码
public void addChild(final Node<T> child) { this.children.add(child); } public boolean isLeaf() { return getChildren().isEmpty(); } /** * Creates and returns an ordered list with {@code this} and all * the nodes found below it on the same branch in the tree. * * e.g given the following tree: * ----1---- * ---/-\--- * --2---3-- * --|---|-- * --4---5-- * /-|-\---- * 6-7-8---- * * if {@code listAllNodes()} it's called for node 1, * it will return: [1,2,4,6,7,8,3,5] */ @NonNull public ImmutableList<Node<T>> listAllNodesBelow() { final ArrayList<Node<T>> list = new ArrayList<>(); listAllNodesBelow_rec(this, list); return ImmutableList.copyOf(list); } /** * Creates and returns an ordered list with {@code this} and all * the nodes found above it on the same branch in the tree. * * e.g given the following tree: * ----1---- * ---/-\--- * --2---3-- * --|---|-- * --4---5-- * /-|-\---- * 6-7-8---- * * if {@code getUpStream()} it's called for node 8, * it will return: [8,4,2,1] */ public ArrayList<Node<T>> getUpStream() { Node<T> currentNode = this; final ArrayList<Node<T>> upStream = new ArrayList<>(); upStream.add(currentNode); while (currentNode.parent != null) { upStream.add(currentNode.parent); currentNode = currentNode.parent; }
return upStream; } /** * Tries to found a node among the ones found below {@code this} on the same branch * in the tree with {@code value} equal to the given one. * * e.g given the following tree: * ----1---- * ---/-\--- * --2---3-- * --|---|-- * --4---5-- * /-|-\---- * 6-7-8---- * * if {@code getNode(4)} it's called for node 1, * it will return: Optional.of(Node(4)). */ @NonNull public Optional<Node<T>> getNode(final T value) { return Optional.ofNullable(getNode_rec(this, value)); } @NonNull public String toString() { return this.getValue().toString(); } @Nullable private Node<T> getNode_rec(final Node<T> currentNode, final T value) { if (currentNode.value.equals(value)) { return currentNode; } else { final Iterator<Node<T>> iterator = currentNode.getChildren().iterator(); Node<T> requestedNode = null; while (requestedNode == null && iterator.hasNext()) { requestedNode = getNode_rec(iterator.next(), value); } return requestedNode; } } private void listAllNodesBelow_rec(final Node<T> currentNode, final List<Node<T>> nodeList) { nodeList.add(currentNode); if (!currentNode.isLeaf()) { currentNode.getChildren().forEach(child -> listAllNodesBelow_rec(child, nodeList)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Node.java
1
请完成以下Java代码
public Optional<NotificationGroup> getNotificationGroupByName(final NotificationGroupName notificationGroupName) {return getMap().getByName(notificationGroupName);} @Override public Set<NotificationGroupName> getActiveNames() {return getMap().getNames();} private NotificationGroupMap getMap() {return notificationGroupNames.getOrLoad(0, this::retrieveMap);} private NotificationGroupMap retrieveMap() { final Map<NotificationGroupId, NotificationGroupCCs> ccsByGroupId = queryBL.createQueryBuilderOutOfTrx(I_AD_NotificationGroup_CC.class) .addOnlyActiveRecordsFilter() .create() .stream() .collect(Collectors.groupingBy( record -> NotificationGroupId.ofRepoId(record.getAD_NotificationGroup_ID()), Collectors.mapping(NotificationGroupRepository::extractRecipient, NotificationGroupCCs.collect()) )); return queryBL.createQueryBuilderOutOfTrx(I_AD_NotificationGroup.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(record -> toNotificationGroup(record, ccsByGroupId))
.collect(NotificationGroupMap.collect()); } private static Recipient extractRecipient(final I_AD_NotificationGroup_CC record) { return Recipient.user(UserId.ofRepoId(record.getAD_User_ID())); } private static NotificationGroup toNotificationGroup(final I_AD_NotificationGroup record, Map<NotificationGroupId, NotificationGroupCCs> ccsById) { final NotificationGroupId id = NotificationGroupId.ofRepoId(record.getAD_NotificationGroup_ID()); return NotificationGroup.builder() .id(id) .name(NotificationGroupName.of(record.getInternalName())) .ccs(ccsById.getOrDefault(id, NotificationGroupCCs.EMPTY)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationGroupRepository.java
1
请完成以下Java代码
public void beforeSave(final I_SAP_GLJournal record, final ModelChangeType timing) { if (InterfaceWrapperHelper.isUIAction(record)) { if (isConversionCtxChanged(record, timing)) { glJournalService.updateWhileSaving( record, glJournal -> glJournal.updateLineAcctAmounts(glJournalService.getCurrencyConverter())); } } } private static boolean isConversionCtxChanged(final I_SAP_GLJournal record, final ModelChangeType timing) { if (timing.isNew()) { return true; } final SAPGLJournalCurrencyConversionCtx conversionCtx = SAPGLJournalLoaderAndSaver.extractConversionCtx(record); final SAPGLJournalCurrencyConversionCtx conversionCtxOld = SAPGLJournalLoaderAndSaver.extractConversionCtx(InterfaceWrapperHelper.createOld(record, I_SAP_GLJournal.class)); return !SAPGLJournalCurrencyConversionCtx.equals(conversionCtx, conversionCtxOld); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_SAP_GLJournal record) { if (InterfaceWrapperHelper.isUIAction(record)) { // shall not happen if (record.isProcessed()) { throw new AdempiereException("Record is processed"); } glJournalService.updateWhileSaving(record, SAPGLJournal::removeAllLines);
} } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void afterComplete(final I_SAP_GLJournal record) { glJournalService.fireAfterComplete(record); } @DocValidate(timings = ModelValidator.TIMING_AFTER_REACTIVATE) public void beforeReactivate(final I_SAP_GLJournal record) { glJournalService.fireAfterReactivate(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\interceptor\SAP_GLJournal.java
1
请完成以下Java代码
private void putInstance(@NonNull final HUReportProcessInstance instance) { instances.cleanUp(); instances.put(instance.getInstanceId(), instance.copyReadonly()); } private HUReportProcessInstance getInstance(final DocumentId instanceId) { final HUReportProcessInstance instance = instances.getIfPresent(instanceId); if (instance == null) { throw new EntityNotFoundException("No HU Report instance found for " + instanceId); } return instance; } @Override public <R> R forProcessInstanceReadonly(final DocumentId pinstanceId, @NonNull final Function<IProcessInstanceController, R> processor) { try (final IAutoCloseable ignored = getInstance(pinstanceId).lockForReading()) { final HUReportProcessInstance processInstance = getInstance(pinstanceId) .copyReadonly(); return processor.apply(processInstance); } } @Override public <R> R forProcessInstanceWritable(final DocumentId pinstanceId, final IDocumentChangesCollector changesCollector, @NonNull final Function<IProcessInstanceController, R> processor) { try (final IAutoCloseable ignored = getInstance(pinstanceId).lockForWriting()) { final HUReportProcessInstance processInstance = getInstance(pinstanceId) .copyReadWrite(changesCollector); final R result = processor.apply(processInstance); putInstance(processInstance); return result; } } @Override public void cacheReset() { processDescriptors.reset(); instances.cleanUp();
} private DocumentId nextPInstanceId() { return DocumentId.ofString(UUID.randomUUID().toString()); } private static final class IndexedWebuiHUProcessDescriptors { private final ImmutableMap<ProcessId, WebuiHUProcessDescriptor> descriptorsByProcessId; private IndexedWebuiHUProcessDescriptors(final List<WebuiHUProcessDescriptor> descriptors) { descriptorsByProcessId = Maps.uniqueIndex(descriptors, WebuiHUProcessDescriptor::getProcessId); } public WebuiHUProcessDescriptor getByProcessId(final ProcessId processId) { final WebuiHUProcessDescriptor descriptor = descriptorsByProcessId.get(processId); if (descriptor == null) { throw new EntityNotFoundException("No HU process descriptor found for " + processId); } return descriptor; } public Collection<WebuiHUProcessDescriptor> getAll() { return descriptorsByProcessId.values(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\report\HUReportProcessInstancesRepository.java
1
请在Spring Boot框架中完成以下Java代码
DataSource dataSource() { return new DataSource() { @Override public Connection getConnection() throws SQLException { return null; } @Override public Connection getConnection(String username, String password) throws SQLException { return null; } @Override public PrintWriter getLogWriter() throws SQLException { return null; } @Override public void setLogWriter(PrintWriter out) throws SQLException { } @Override public void setLoginTimeout(int seconds) throws SQLException { } @Override public int getLoginTimeout() throws SQLException { return 0; }
@Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }; } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\activej\config\PersonModule.java
2
请完成以下Java代码
private static void getExistingPairs(int[] input, int sum) { List<Integer> pairs = new ArrayList<>(); System.out.println("~ All existing pairs ~"); /* Traditional FOR loop */ // Call method pairs = ExistingPairs.findPairsWithForLoop(input, sum); // Create a pretty printing final StringBuilder output1 = new StringBuilder(); pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, ")); // Print result System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2)); /* Java 8 stream API */ // Call the method pairs = ExistingPairs.findPairsWithStreamApi(input, sum); // Create a pretty printing final StringBuilder output2 = new StringBuilder(); pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, ")); // Print result System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2)); } /** * Print all different pairs for the given inputs: input array & sum number */
private static void getDifferentPairs(int[] input, int sum) { List<Integer> pairs = new ArrayList<>(); System.out.println("~ All different pairs ~"); /* Traditional FOR loop */ // Call method pairs = DifferentPairs.findPairsWithForLoop(input, sum); // Create a pretty printing final StringBuilder output3 = new StringBuilder(); pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, ")); // Print result System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2)); /* Java 8 stream API */ // Call method pairs = DifferentPairs.findPairsWithStreamApi(input, sum); // Create a pretty printing final StringBuilder output4 = new StringBuilder(); pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, ")); // Print result System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2)); } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\pairsaddupnumber\FindPairs.java
1
请完成以下Java代码
public void deleteHistoricDetailsByTaskId(String taskId) { if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.FULL)) { List<HistoricDetailEntity> details = historicDetailDataManager.findHistoricDetailsByTaskId(taskId); for (HistoricDetail detail : details) { delete((HistoricDetailEntity) detail); } } } @Override public List<HistoricDetail> findHistoricDetailsByNativeQuery( Map<String, Object> parameterMap, int firstResult, int maxResults ) { return historicDetailDataManager.findHistoricDetailsByNativeQuery(parameterMap, firstResult, maxResults);
} @Override public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) { return historicDetailDataManager.findHistoricDetailCountByNativeQuery(parameterMap); } public HistoricDetailDataManager getHistoricDetailDataManager() { return historicDetailDataManager; } public void setHistoricDetailDataManager(HistoricDetailDataManager historicDetailDataManager) { this.historicDetailDataManager = historicDetailDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityManagerImpl.java
1
请完成以下Java代码
public class MAccessProfile extends X_CM_AccessProfile { /** * */ private static final long serialVersionUID = -7399451749843773853L; /** * Access to Container * @param ctx context * @param CM_Container_ID * @param AD_User_ID user to check * @return true if access to container */ public static boolean isAccessContainer (Properties ctx, int CM_Container_ID, int AD_User_ID) { // NIT return true; } // isAccessContainer /** * Access to Container * @param ctx context * @param CM_Container_ID * @param AD_Role_ID 0 or role to checl * @param C_BPGroup_ID 0 or bpartner to check * @return true if access to container */ public static boolean isAccessContainer (Properties ctx, int CM_Container_ID, int AD_Role_ID, int C_BPGroup_ID) { // NIT return true; } // isAccessContainer /************************************************************************** * Standard Constructor * @param ctx context * @param CM_AccessProfile_ID id * @param trxName transaction
*/ public MAccessProfile (Properties ctx, int CM_AccessProfile_ID, String trxName) { super (ctx, CM_AccessProfile_ID, trxName); } // MAccessProfile /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MAccessProfile (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MAccessProfile } // MAccessProfile
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAccessProfile.java
1
请在Spring Boot框架中完成以下Java代码
public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .passwordEncoder(passwordEncoder()) .dataSource(dataSource); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests() .antMatchers("/anonymous*").anonymous() .antMatchers("/login*").permitAll()
.anyRequest().authenticated() .and() .formLogin() .and() .logout() .logoutUrl("/logout.do") .invalidateHttpSession(true) .clearAuthentication(true); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/themes/**"); } }
repos\tutorials-master\spring-web-modules\spring-mvc-views\src\main\java\com\baeldung\themes\config\SecurityConfig.java
2
请完成以下Java代码
private StockDataAggregateItem recordRowToStockDataItem(@NonNull final I_T_MD_Stock_WarehouseAndProduct record) { return StockDataAggregateItem.builder() .productCategoryId(record.getM_Product_Category_ID()) .productId(record.getM_Product_ID()) .productValue(record.getProductValue()) .warehouseId(record.getM_Warehouse_ID()) .qtyOnHand(record.getQtyOnHand()) .build(); } public Stream<StockDataItem> streamStockDataItems(@NonNull final StockDataMultiQuery multiQuery) { final IQuery<I_MD_Stock> query = multiQuery .getStockDataQueries() .stream() .map(this::createStockDataItemQuery) .reduce(IQuery.unionDistict()) .orElse(null); if (query == null) { return Stream.empty(); } return query .iterateAndStream() .map(this::recordToStockDataItem); } private IQuery<I_MD_Stock> createStockDataItemQuery(@NonNull final StockDataQuery query) { final IQueryBuilder<I_MD_Stock> queryBuilder = queryBL.createQueryBuilder(I_MD_Stock.class); queryBuilder.addEqualsFilter(I_MD_Stock.COLUMNNAME_M_Product_ID, query.getProductId()); if (!query.getWarehouseIds().isEmpty())
{ queryBuilder.addInArrayFilter(I_MD_Stock.COLUMNNAME_M_Warehouse_ID, query.getWarehouseIds()); } // // Storage Attributes Key { final AttributesKeyQueryHelper<I_MD_Stock> helper = AttributesKeyQueryHelper.createFor(I_MD_Stock.COLUMN_AttributesKey); final IQueryFilter<I_MD_Stock> attributesKeysFilter = helper.createFilter(ImmutableList.of(AttributesKeyPatternsUtil.ofAttributeKey(query.getStorageAttributesKey()))); queryBuilder.filter(attributesKeysFilter); } return queryBuilder.create(); } private StockDataItem recordToStockDataItem(@NonNull final I_MD_Stock record) { return StockDataItem.builder() .productId(ProductId.ofRepoId(record.getM_Product_ID())) .warehouseId(WarehouseId.ofRepoId(record.getM_Warehouse_ID())) .storageAttributesKey(AttributesKey.ofString(record.getAttributesKey())) .qtyOnHand(record.getQtyOnHand()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\StockRepository.java
1
请在Spring Boot框架中完成以下Java代码
public void create(@NonNull final OrderPayScheduleCreateRequest request) { final SeqNoProvider seqNoProvider = SeqNoProvider.ofInt(10); request.getLines() .forEach(line -> createLine(line, request.getOrderId(), seqNoProvider.getAndIncrement())); } private static void createLine(@NonNull final OrderPayScheduleCreateRequest.Line request, @NonNull final OrderId orderId, @NonNull final SeqNo seqNo) { final I_C_OrderPaySchedule record = newInstance(I_C_OrderPaySchedule.class); record.setC_Order_ID(orderId.getRepoId()); record.setC_PaymentTerm_ID(request.getPaymentTermBreakId().getPaymentTermId().getRepoId()); record.setC_PaymentTerm_Break_ID(request.getPaymentTermBreakId().getRepoId()); record.setDueAmt(request.getDueAmount().toBigDecimal()); record.setC_Currency_ID(request.getDueAmount().getCurrencyId().getRepoId()); record.setDueDate(TimeUtil.asTimestamp(request.getDueDate())); record.setPercent(request.getPercent().toInt()); record.setReferenceDateType(request.getReferenceDateType().getCode()); record.setOffsetDays(request.getOffsetDays()); record.setSeqNo(seqNo.toInt()); record.setStatus(OrderPayScheduleStatus.toCodeOrNull(request.getOrderPayScheduleStatus())); saveRecord(record); } @NonNull
public Optional<OrderPaySchedule> getByOrderId(@NonNull final OrderId orderId) { return newLoaderAndSaver().loadByOrderId(orderId); } public void deleteByOrderId(@NonNull final OrderId orderId) { queryBL.createQueryBuilder(I_C_OrderPaySchedule.class) .addEqualsFilter(I_C_OrderPaySchedule.COLUMNNAME_C_Order_ID, orderId) .create() .delete(); } public void save(final OrderPaySchedule orderPaySchedule) {newLoaderAndSaver().save(orderPaySchedule);} public void updateById(@NonNull final OrderId orderId, @NonNull final Consumer<OrderPaySchedule> updater) { newLoaderAndSaver().updateById(orderId, updater); } public void updateByIds(@NonNull final Set<OrderId> orderIds, @NonNull final Consumer<OrderPaySchedule> updater) { newLoaderAndSaver().updateByIds(orderIds, updater); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\repository\OrderPayScheduleRepository.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteIdentityLink(@ApiParam(name = "caseInstanceId") @PathVariable("caseInstanceId") String caseInstanceId, @ApiParam(name = "identityId") @PathVariable("identityId") String identityId, @ApiParam(name = "type") @PathVariable("type") String type) { CaseInstance caseInstance = getCaseInstanceFromRequestWithoutAccessCheck(caseInstanceId); validateIdentityLinkArguments(identityId, type); IdentityLink link = getIdentityLink(identityId, type, caseInstance.getId()); if (restApiInterceptor != null) { restApiInterceptor.deleteCaseInstanceIdentityLink(caseInstance, link); } runtimeService.deleteUserIdentityLink(caseInstance.getId(), identityId, type); } protected void validateIdentityLinkArguments(String identityId, String type) { if (identityId == null) { throw new FlowableIllegalArgumentException("IdentityId is required."); } if (type == null) {
throw new FlowableIllegalArgumentException("Type is required."); } } protected IdentityLink getIdentityLink(String identityId, String type, String caseInstanceId) { // Perhaps it would be better to offer getting a single identity link // from the API List<IdentityLink> allLinks = runtimeService.getIdentityLinksForCaseInstance(caseInstanceId); for (IdentityLink link : allLinks) { if (identityId.equals(link.getUserId()) && link.getType().equals(type)) { return link; } } throw new FlowableObjectNotFoundException("Could not find the requested identity link.", IdentityLink.class); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceIdentityLinkResource.java
2
请完成以下Java代码
public <ModelType> ModelType retrieveModel(final Properties ctx, final String tableName, final Class<?> modelClass, final ResultSet rs, final String trxName) { final PO po = getPO(ctx, tableName, rs, trxName); // // Case: we have a modelClass specified if (modelClass != null) { final Class<? extends PO> poClass = po.getClass(); if (poClass.isAssignableFrom(modelClass)) { @SuppressWarnings("unchecked") final ModelType model = (ModelType)po; return model; } else { @SuppressWarnings("unchecked") final ModelType model = (ModelType)InterfaceWrapperHelper.create(po, modelClass); return model; } }
// // Case: no "clazz" and no "modelClass" else { if (log.isDebugEnabled()) { final AdempiereException ex = new AdempiereException("Query does not have a modelClass defined and no 'clazz' was specified as parameter." + "We need to avoid this case, but for now we are trying to do a force casting" + "\nQuery: " + this + "\nPO: " + po); log.debug(ex.getLocalizedMessage(), ex); } @SuppressWarnings("unchecked") final ModelType model = (ModelType)po; return model; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\TableModelLoader.java
1
请完成以下Java代码
public Void call() throws Exception { ((SignallableActivityBehavior) activityBehaviorInstance).signal(execution, signalName, signalData); return null; } }); } @Override public void performExecution(final ActivityExecution execution) throws Exception { Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { // Note: we can't cache the result of the expression, because the // execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}' Object delegate = expression.getValue(execution); applyFieldDeclaration(fieldDeclarations, delegate); if (delegate instanceof ActivityBehavior) { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new ActivityBehaviorInvocation((ActivityBehavior) delegate, execution)); } else if (delegate instanceof JavaDelegate) { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new JavaDelegateInvocation((JavaDelegate) delegate, execution)); leave(execution); } else { throw LOG.resolveDelegateExpressionException(expression, ActivityBehavior.class, JavaDelegate.class); } return null; } };
executeWithErrorPropagation(execution, callable); } protected ActivityBehavior getActivityBehaviorInstance(ActivityExecution execution, Object delegateInstance) { if (delegateInstance instanceof ActivityBehavior) { return new CustomActivityBehavior((ActivityBehavior) delegateInstance); } else if (delegateInstance instanceof JavaDelegate) { return new ServiceTaskJavaDelegateActivityBehavior((JavaDelegate) delegateInstance); } else { throw LOG.missingDelegateParentClassException(delegateInstance.getClass().getName(), JavaDelegate.class.getName(), ActivityBehavior.class.getName()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ServiceTaskDelegateExpressionActivityBehavior.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof CustomerSlim)) { return false; } CustomerSlim other = (CustomerSlim) obj; return Objects.equals(address, other.address) && id == other.id && Objects.equals(name, other.name); } @Override public String toString() { return "CustomerSlim [id=" + id + ", name=" + name + ", address=" + address + "]"; } public static CustomerSlim[] fromCustomers(Customer[] customers) {
CustomerSlim[] feedback = new CustomerSlim[customers.length]; for (int i = 0; i < customers.length; i++) { Customer aCustomer = customers[i]; CustomerSlim newOne = new CustomerSlim(); newOne.setId(aCustomer.getId()); newOne.setName(aCustomer.getFirstName() + " " + aCustomer.getLastName()); newOne.setAddress(aCustomer.getStreet() + ", " + aCustomer.getCity() + " " + aCustomer.getState() + " " + aCustomer.getPostalCode()); feedback[i] = newOne; } return feedback; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonoptimization\CustomerSlim.java
1
请在Spring Boot框架中完成以下Java代码
public SmsTwoFaAccountConfig generateNewAccountConfig(User user, SmsTwoFaProviderConfig providerConfig) { return new SmsTwoFaAccountConfig(); } @Override protected void sendVerificationCode(SecurityUser user, String verificationCode, SmsTwoFaProviderConfig providerConfig, SmsTwoFaAccountConfig accountConfig) throws ThingsboardException { Map<String, String> messageData = Map.of( "code", verificationCode, "userEmail", user.getEmail() ); String message = TbNodeUtils.processTemplate(providerConfig.getSmsVerificationMessageTemplate(), messageData); String phoneNumber = accountConfig.getPhoneNumber(); try { smsService.sendSms(user.getTenantId(), user.getCustomerId(), new String[]{phoneNumber}, message); auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), user, ActionType.SMS_SENT, null, phoneNumber); } catch (ThingsboardException e) { auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), user.getId(), user, ActionType.SMS_SENT, e, phoneNumber); throw e; } }
@Override public void check(TenantId tenantId) throws ThingsboardException { if (!smsService.isConfigured(tenantId)) { throw new ThingsboardException("SMS service is not configured", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } } @Override public TwoFaProviderType getType() { return TwoFaProviderType.SMS; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\SmsTwoFaProvider.java
2
请完成以下Java代码
public void setCalY(int calY) { this.calY = calY; } public String getPrintService() { return printService; } /** * @param printService the printService to set */ public void setPrintService(String printService) { this.printService = printService; } public String getTray() { return tray; } /** * @param tray the tray to set */ public void setTray(String tray) { this.tray = tray; } public int getPageFrom() { return pageFrom; } /** * @param pageFrom the pageFrom to set */ public void setPageFrom(int pageFrom) { this.pageFrom = pageFrom; } public int getPageTo() { return pageTo; } /** * @param pageTo the pageTo to set */ public void setPageTo(int pageTo) { this.pageTo = pageTo; } @Override public String toString() { return "PrintPackageInfo [printService=" + printService + ", tray=" + tray + ", pageFrom=" + pageFrom + ", pageTo=" + pageTo + ", calX=" + calX + ", calY=" + calY + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + calX; result = prime * result + calY; result = prime * result + pageFrom; result = prime * result + pageTo; result = prime * result + ((printService == null) ? 0 : printService.hashCode()); result = prime * result + ((tray == null) ? 0 : tray.hashCode());
result = prime * result + trayNumber; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrintPackageInfo other = (PrintPackageInfo)obj; if (calX != other.calX) return false; if (calY != other.calY) return false; if (pageFrom != other.pageFrom) return false; if (pageTo != other.pageTo) return false; if (printService == null) { if (other.printService != null) return false; } else if (!printService.equals(other.printService)) return false; if (tray == null) { if (other.tray != null) return false; } else if (!tray.equals(other.tray)) return false; if (trayNumber != other.trayNumber) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackageInfo.java
1
请完成以下Java代码
public class AtomicOperationCaseExecutionDisable extends AbstractCmmnEventAtomicOperation { public String getCanonicalName() { return "case-execution-disable"; } protected String getEventName() { return DISABLE; } protected CmmnExecution eventNotificationsStarted(CmmnExecution execution) { CmmnActivityBehavior behavior = getActivityBehavior(execution); behavior.onDisable(execution); execution.setCurrentState(DISABLED);
return execution; } protected void preTransitionNotification(CmmnExecution execution) { CmmnExecution parent = execution.getParent(); if (parent != null) { CmmnActivityBehavior behavior = getActivityBehavior(parent); if (behavior instanceof CmmnCompositeActivityBehavior) { CmmnCompositeActivityBehavior compositeBehavior = (CmmnCompositeActivityBehavior) behavior; compositeBehavior.handleChildDisabled(parent, execution); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\operation\AtomicOperationCaseExecutionDisable.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskDefinitionKey() { return taskDefinitionKey; } public void setTaskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } public String getScopeDefinitionId() { return scopeDefinitionId; }
public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public void saveData(RpAccountCheckBatch rpAccountCheckBatch) { rpAccountCheckBatchDao.insert(rpAccountCheckBatch); } @Override public void updateData(RpAccountCheckBatch rpAccountCheckBatch) { rpAccountCheckBatchDao.update(rpAccountCheckBatch); } @Override public RpAccountCheckBatch getDataById(String id) { return rpAccountCheckBatchDao.getById(id); } @Override
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) { return rpAccountCheckBatchDao.listPage(pageParam, paramMap); } /** * 根据条件查询实体 * * @param paramMap */ public List<RpAccountCheckBatch> listBy(Map<String, Object> paramMap) { return rpAccountCheckBatchDao.listBy(paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\service\impl\RpAccountCheckBatchServiceImpl.java
2
请完成以下Java代码
public String getMisfireStrategy() { return misfireStrategy; } public void setMisfireStrategy(String misfireStrategy) { this.misfireStrategy = misfireStrategy; } public String getExecutorRouteStrategy() { return executorRouteStrategy; } public void setExecutorRouteStrategy(String executorRouteStrategy) { this.executorRouteStrategy = executorRouteStrategy; } public String getExecutorHandler() { return executorHandler; } public void setExecutorHandler(String executorHandler) { this.executorHandler = executorHandler; } public String getExecutorParam() { return executorParam; } public void setExecutorParam(String executorParam) { this.executorParam = executorParam; } public String getExecutorBlockStrategy() { return executorBlockStrategy; } public void setExecutorBlockStrategy(String executorBlockStrategy) { this.executorBlockStrategy = executorBlockStrategy; } public int getExecutorTimeout() { return executorTimeout; } public void setExecutorTimeout(int executorTimeout) { this.executorTimeout = executorTimeout; } public int getExecutorFailRetryCount() { return executorFailRetryCount; } public void setExecutorFailRetryCount(int executorFailRetryCount) { this.executorFailRetryCount = executorFailRetryCount; } public String getGlueType() { return glueType; } public void setGlueType(String glueType) { this.glueType = glueType; }
public String getGlueSource() { return glueSource; } public void setGlueSource(String glueSource) { this.glueSource = glueSource; } public String getGlueRemark() { return glueRemark; } public void setGlueRemark(String glueRemark) { this.glueRemark = glueRemark; } public Date getGlueUpdatetime() { return glueUpdatetime; } public void setGlueUpdatetime(Date glueUpdatetime) { this.glueUpdatetime = glueUpdatetime; } public String getChildJobId() { return childJobId; } public void setChildJobId(String childJobId) { this.childJobId = childJobId; } public int getTriggerStatus() { return triggerStatus; } public void setTriggerStatus(int triggerStatus) { this.triggerStatus = triggerStatus; } public long getTriggerLastTime() { return triggerLastTime; } public void setTriggerLastTime(long triggerLastTime) { this.triggerLastTime = triggerLastTime; } public long getTriggerNextTime() { return triggerNextTime; } public void setTriggerNextTime(long triggerNextTime) { this.triggerNextTime = triggerNextTime; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java
1
请完成以下Java代码
private static class ProtocolResolvingResourceLoader implements ResourceLoader { private final ResourceLoader resourceLoader; private final List<ProtocolResolver> protocolResolvers; private final List<FilePathResolver> filePathResolvers; ProtocolResolvingResourceLoader(ResourceLoader resourceLoader, List<ProtocolResolver> protocolResolvers, List<FilePathResolver> filePathResolvers) { this.resourceLoader = resourceLoader; this.protocolResolvers = protocolResolvers; this.filePathResolvers = filePathResolvers; } @Override public @Nullable ClassLoader getClassLoader() { return this.resourceLoader.getClassLoader(); } @Override public Resource getResource(String location) { if (StringUtils.hasLength(location)) { for (ProtocolResolver protocolResolver : this.protocolResolvers) { Resource resource = protocolResolver.resolve(location, this); if (resource != null) { return resource; } } } Resource resource = this.resourceLoader.getResource(location);
String filePath = getFilePath(location, resource); return (filePath != null) ? new ApplicationResource(filePath) : resource; } private @Nullable String getFilePath(String location, Resource resource) { for (FilePathResolver filePathResolver : this.filePathResolvers) { String filePath = filePathResolver.resolveFilePath(location, resource); if (filePath != null) { return filePath; } } return null; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\io\ApplicationResourceLoader.java
1
请完成以下Java代码
protected String getDelayedExecutionJobHandlerType() { return null; } protected JobHandlerConfiguration getJobHandlerConfiguration() { return null; } protected AbstractSetStateCmd getNextCommand() { return null; } /** * @return the id of the associated deployment, only necessary if the command * can potentially be executed in a scheduled way (i.e. if an * {@link #executionDate} can be set) so the job executor responsible * for that deployment can execute the resulting job */ protected String getDeploymentId(CommandContext commandContext) { return null; } protected abstract void checkAuthorization(CommandContext commandContext); protected abstract void checkParameters(CommandContext commandContext); protected abstract void updateSuspensionState(CommandContext commandContext, SuspensionState suspensionState); protected abstract void logUserOperation(CommandContext commandContext); protected abstract String getLogEntryOperation(); protected abstract SuspensionState getNewSuspensionState(); protected String getDeploymentIdByProcessDefinition(CommandContext commandContext, String processDefinitionId) { ProcessDefinitionEntity definition = commandContext.getProcessDefinitionManager().getCachedResourceDefinitionEntity(processDefinitionId); if (definition == null) { definition = commandContext.getProcessDefinitionManager().findLatestDefinitionById(processDefinitionId); } if (definition != null) { return definition.getDeploymentId(); } return null; } protected String getDeploymentIdByProcessDefinitionKey(CommandContext commandContext, String processDefinitionKey, boolean tenantIdSet, String tenantId) { ProcessDefinitionEntity definition = null;
if (tenantIdSet) { definition = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionByKeyAndTenantId(processDefinitionKey, tenantId); } else { // randomly use a latest process definition's deployment id from one of the tenants List<ProcessDefinitionEntity> definitions = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionsByKey(processDefinitionKey); definition = definitions.isEmpty() ? null : definitions.get(0); } if (definition != null) { return definition.getDeploymentId(); } return null; } protected String getDeploymentIdByJobDefinition(CommandContext commandContext, String jobDefinitionId) { JobDefinitionManager jobDefinitionManager = commandContext.getJobDefinitionManager(); JobDefinitionEntity jobDefinition = jobDefinitionManager.findById(jobDefinitionId); if (jobDefinition != null) { if (jobDefinition.getProcessDefinitionId() != null) { return getDeploymentIdByProcessDefinition(commandContext, jobDefinition.getProcessDefinitionId()); } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetStateCmd.java
1
请在Spring Boot框架中完成以下Java代码
public PickingJob closeTUPickingTarget( @NonNull final PickingJob pickingJob, @Nullable final PickingJobLineId lineId) { final TUPickingTarget pickingTarget = getTUPickingTarget(pickingJob, lineId).orElse(null); if (pickingTarget == null) { return pickingJob; } return setTUPickingTarget(pickingJob, lineId, null); } private Optional<TUPickingTarget> getTUPickingTarget( @NonNull final PickingJob pickingJob, @Nullable final PickingJobLineId lineId) { return pickingJob.getTuPickingTarget(lineId); } public void reopenPickingJobs(@NonNull final ReopenPickingJobRequest request) { final Map<ShipmentScheduleId, List<PickingJobId>> scheduleId2JobIds = pickingJobRepository .getPickingJobIdsByScheduleId(request.getShipmentScheduleIds()); final PickingJobReopenCommand.PickingJobReopenCommandBuilder commandBuilder = PickingJobReopenCommand.builder() .pickingSlotService(pickingSlotService) .pickingJobRepository(pickingJobRepository) .shipmentScheduleService(shipmentScheduleService) .huService(huService); scheduleId2JobIds.values().stream() .flatMap(List::stream) .collect(ImmutableSet.toImmutableSet()) .stream() .map(this::getById) .filter(pickingJob -> pickingJob.getAllPickedHuIds() .stream() .anyMatch(huId -> request.getHuIds().contains(huId))) .map(job -> commandBuilder .jobToReopen(job) .huIdsToPick(request.getHuInfoList()) .build()) .forEach(PickingJobReopenCommand::execute); } public PickingSlotSuggestions getPickingSlotsSuggestions(final @NonNull PickingJob pickingJob)
{ final Set<DocumentLocation> deliveryLocations = bpartnerService.getDocumentLocations(pickingJob.getDeliveryBPLocationIds()); return pickingSlotService.getPickingSlotsSuggestions(deliveryLocations); } public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return PickingJobPickAllCommand.builder() .pickingJobService(this) // .pickingJobId(pickingJobId) .callerId(callerId) // .build().execute(); } public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return PickingJobGetQtyAvailableCommand.builder() .pickingJobService(this) .warehouseService(warehouseService) .huService(huService) // .pickingJobId(pickingJobId) .callerId(callerId) // .build().execute(); } public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(@NonNull GetNextEligibleLineToPackRequest request) { return GetNextEligibleLineToPackCommand.builder() .pickingJobService(this) .huService(huService) .shipmentSchedules(shipmentScheduleService.newLoadingCache()) .request(request) .build().execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobService.java
2
请完成以下Java代码
public void setAD_Val_Rule_ID (final int AD_Val_Rule_ID) { if (AD_Val_Rule_ID < 1) set_Value (COLUMNNAME_AD_Val_Rule_ID, null); else set_Value (COLUMNNAME_AD_Val_Rule_ID, AD_Val_Rule_ID); } @Override public int getAD_Val_Rule_ID() { return get_ValueAsInt(COLUMNNAME_AD_Val_Rule_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 setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board.java
1
请完成以下Java代码
private List<I_M_HU> getTUsToAssign() { Check.assumeNotEmpty(_tusToAssign, "_tusToAssign not empty"); return _tusToAssign; } public final LUTUAssignBuilder setHUPlanningReceiptOwnerPM(final boolean isHUPlanningReceiptOwnerPM) { assertConfigurable(); _isHUPlanningReceiptOwnerPM = isHUPlanningReceiptOwnerPM; return this; } private final boolean isHUPlanningReceiptOwnerPM() { return _isHUPlanningReceiptOwnerPM; } public LUTUAssignBuilder setDocumentLine(final IHUDocumentLine documentLine) { assertConfigurable(); _documentLine = documentLine; return this; } private IHUDocumentLine getDocumentLine() { return _documentLine; // null is ok } public LUTUAssignBuilder setC_BPartner(final I_C_BPartner bpartner) { assertConfigurable(); this._bpartnerId = bpartner != null ? BPartnerId.ofRepoId(bpartner.getC_BPartner_ID()) : null; return this; } private final BPartnerId getBPartnerId() { return _bpartnerId; } public LUTUAssignBuilder setC_BPartner_Location_ID(final int bpartnerLocationId) { assertConfigurable(); _bpLocationId = bpartnerLocationId; return this; } private final int getC_BPartner_Location_ID() { return _bpLocationId; }
public LUTUAssignBuilder setM_Locator(final I_M_Locator locator) { assertConfigurable(); _locatorId = LocatorId.ofRecordOrNull(locator); return this; } private LocatorId getLocatorId() { Check.assumeNotNull(_locatorId, "_locatorId not null"); return _locatorId; } public LUTUAssignBuilder setHUStatus(final String huStatus) { assertConfigurable(); _huStatus = huStatus; return this; } private String getHUStatus() { Check.assumeNotEmpty(_huStatus, "_huStatus not empty"); return _huStatus; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\LUTUAssignBuilder.java
1
请完成以下Java代码
public static String escapeEntities(String s) { if (s == null || s.length() == 0) { return s; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') { sb.append(ch); } else if (ch == '<') { sb.append("&lt;"); } else if (ch == '>') { sb.append("&gt;"); } else if (ch == '&') { sb.append("&amp;"); } else if (Character.isWhitespace(ch)) { sb.append("&#").append((int) ch).append(";"); } else if (Character.isISOControl(ch)) { // ignore control chars } else if (Character.isHighSurrogate(ch)) { if (i + 1 >= s.length()) {
// Unexpected end throw new IllegalArgumentException("Missing low surrogate character at end of string"); } char low = s.charAt(i + 1); if (!Character.isLowSurrogate(low)) { throw new IllegalArgumentException( "Expected low surrogate character but found value = " + (int) low); } int codePoint = Character.toCodePoint(ch, low); if (Character.isDefined(codePoint)) { sb.append("&#").append(codePoint).append(";"); } i++; // skip the next character as we have already dealt with it } else if (Character.isLowSurrogate(ch)) { throw new IllegalArgumentException("Unexpected low surrogate character, value = " + (int) ch); } else if (Character.isDefined(ch)) { sb.append("&#").append((int) ch).append(";"); } // Ignore anything else } return sb.toString(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\TextEscapeUtils.java
1
请完成以下Java代码
public @Nullable PersistentRememberMeToken getTokenForSeries(String seriesId) { try { return getTemplate().queryForObject(this.tokensBySeriesSql, this::createRememberMeToken, seriesId); } catch (EmptyResultDataAccessException ex) { this.logger.debug(LogMessage.format("Querying token for series '%s' returned no results.", seriesId), ex); } catch (IncorrectResultSizeDataAccessException ex) { this.logger.error(LogMessage.format( "Querying token for series '%s' returned more than one value. Series" + " should be unique", seriesId)); } catch (DataAccessException ex) { this.logger.error("Failed to load token for series " + seriesId, ex); } return null; } private PersistentRememberMeToken createRememberMeToken(ResultSet rs, int rowNum) throws SQLException { return new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4)); } @Override public void removeUserTokens(String username) { getTemplate().update(this.removeUserTokensSql, username); } /** * Intended for convenience in debugging. Will create the persistent_tokens database
* table when the class is initialized during the initDao method. * @param createTableOnStartup set to true to execute the */ public void setCreateTableOnStartup(boolean createTableOnStartup) { this.createTableOnStartup = createTableOnStartup; } private JdbcTemplate getTemplate() { @Nullable JdbcTemplate result = super.getJdbcTemplate(); if (result == null) { throw new IllegalStateException("JdbcTemplate was removed"); } return result; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\JdbcTokenRepositoryImpl.java
1
请完成以下Java代码
public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public Map<String, Object> getTransientVariables() { return transientVariables; } public void setTransientVariables(Map<String, Object> transientVariables) { this.transientVariables = transientVariables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getAssigneeId() { return assigneeId;
} public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; } public String getInitiatorVariableName() { return initiatorVariableName; } public void setInitiatorVariableName(String initiatorVariableName) { this.initiatorVariableName = initiatorVariableName; } public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } public String getPredefinedCaseInstanceId() { return predefinedCaseInstanceId; } public void setPredefinedCaseInstanceId(String predefinedCaseInstanceId) { this.predefinedCaseInstanceId = predefinedCaseInstanceId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\StartCaseInstanceBeforeContext.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { cancelB_actionPerformed(e); } }); buttonsPanel.add(okB); buttonsPanel.add(cancelB); this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH); } void okB_actionPerformed(ActionEvent e) { this.dispose(); } void cancelB_actionPerformed(ActionEvent e) { CANCELLED = true; this.dispose(); } void bgColorB_actionPerformed(ActionEvent e) { // Fix until Sun's JVM supports more locales... UIManager.put( "ColorChooser.swatchesNameText", Local.getString("Swatches")); UIManager.put("ColorChooser.hsbNameText", Local.getString("HSB")); UIManager.put("ColorChooser.rgbNameText", Local.getString("RGB")); UIManager.put( "ColorChooser.swatchesRecentText", Local.getString("Recent:")); UIManager.put("ColorChooser.previewText", Local.getString("Preview")); UIManager.put( "ColorChooser.sampleText", Local.getString("Sample Text") + " "
+ Local.getString("Sample Text")); UIManager.put("ColorChooser.okText", Local.getString("OK")); UIManager.put("ColorChooser.cancelText", Local.getString("Cancel")); UIManager.put("ColorChooser.resetText", Local.getString("Reset")); UIManager.put("ColorChooser.hsbHueText", Local.getString("H")); UIManager.put("ColorChooser.hsbSaturationText", Local.getString("S")); UIManager.put("ColorChooser.hsbBrightnessText", Local.getString("B")); UIManager.put("ColorChooser.hsbRedText", Local.getString("R")); UIManager.put("ColorChooser.hsbGreenText", Local.getString("G")); UIManager.put("ColorChooser.hsbBlueText", Local.getString("B2")); UIManager.put("ColorChooser.rgbRedText", Local.getString("Red")); UIManager.put("ColorChooser.rgbGreenText", Local.getString("Green")); UIManager.put("ColorChooser.rgbBlueText", Local.getString("Blue")); Color initColor = Util.decodeColor(bgcolorField.getText()); Color c = JColorChooser.showDialog( this, Local.getString("Table background color"), initColor); if (c == null) return; bgcolorField.setText( "#" + Integer.toHexString(c.getRGB()).substring(2).toUpperCase()); Util.setBgcolorField(bgcolorField); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\TableDialog.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringApp { public static void main(String[] args) { SpringApplication.run(SpringApp.class, args); } @Bean public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration() { TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() .timeoutDuration(Duration.ofSeconds(4)) .build(); CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() .failureRateThreshold(50) .waitDurationInOpenState(Duration.ofMillis(1000)) .slidingWindowSize(2) .build(); return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id) .timeLimiterConfig(timeLimiterConfig) .circuitBreakerConfig(circuitBreakerConfig) .build()); } @Bean public Customizer<Resilience4JCircuitBreakerFactory> specificCustomConfiguration1() { TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() .timeoutDuration(Duration.ofSeconds(4))
.build(); CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() .failureRateThreshold(50) .waitDurationInOpenState(Duration.ofMillis(1000)) .slidingWindowSize(2) .build(); return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) .timeLimiterConfig(timeLimiterConfig).build(), "circuitBreaker"); } @Bean public Customizer<Resilience4JCircuitBreakerFactory> specificCustomConfiguration2() { TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() .timeoutDuration(Duration.ofSeconds(4)) .build(); CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() .failureRateThreshold(50) .waitDurationInOpenState(Duration.ofMillis(1000)) .slidingWindowSize(2) .build(); return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) .timeLimiterConfig(timeLimiterConfig).build(), "circuitBreaker1", "circuitBreaker2", "circuitBreaker3"); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-circuit-breaker\src\main\java\com\baeldung\circuitbreaker\SpringApp.java
2
请完成以下Java代码
protected void prepare() { final IEventBusFactory eventBusFactory = SpringContextHolder.instance.getBean(IEventBusFactory.class); eventBus = eventBusFactory.getEventBus(C_Location.EVENTS_TOPIC); } @Override @RunOutOfTrx protected String doIt() { Set<LocationId> locationIds = retrieveLocationIdsToUpdate(FETCH_SIZE); while (!locationIds.isEmpty()) { scheduleUpdates(locationIds); locationIds = retrieveLocationIdsToUpdate(FETCH_SIZE); } return "Scheduled " + countScheduled + " C_Location(s)"; } private ImmutableSet<LocationId> retrieveLocationIdsToUpdate(final int limit) { return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_Location.class) // .addOnlyActiveRecordsFilter() .addInArrayOrAllFilter(I_C_Location.COLUMN_GeocodingStatus, Arrays.asList(X_C_Location.GEOCODINGSTATUS_Error, X_C_Location.GEOCODINGSTATUS_NotChecked)) // .addCompareFilter(I_C_Location.COLUMN_C_Location_ID, Operator.GREATER, LocationId.toRepoIdOr(maxLocationIdScheduled, 0)) .orderBy(I_C_Location.COLUMN_C_Location_ID) // .setLimit(limit) // .create() .idsAsSet(LocationId::ofRepoId); } private void scheduleUpdates(@NonNull final Set<LocationId> locationIds) { locationIds.forEach(this::scheduleUpdate);
} private void scheduleUpdate(@NonNull final LocationId locationId) { eventBus.enqueueObject(LocationGeocodeEventRequest.of(locationId)); countScheduled++; if (maxLocationIdScheduled == null) { maxLocationIdScheduled = locationId; } else { maxLocationIdScheduled = Collections.max(Arrays.asList(maxLocationIdScheduled, locationId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\process\C_Location_Geocoding_ScheduleUpdate.java
1
请完成以下Java代码
public Date resolveDuedate(String duedateDescription, Task task) { return resolveDuedate(duedateDescription); } public Date resolveDuedate(String duedateDescription) { return resolveDuedate(duedateDescription, (Date)null); } public Date resolveDuedate(String duedateDescription, Date startDate) { return resolveDuedate(duedateDescription, startDate, 0L); } public Date resolveDuedate(String duedateDescription, Date startDate, long repeatOffset) { try { if (duedateDescription.startsWith("R")) { DurationHelper durationHelper = new DurationHelper(duedateDescription, startDate);
durationHelper.setRepeatOffset(repeatOffset); return durationHelper.getDateAfter(startDate); } else { CronTimer cronTimer = CronTimer.parse(duedateDescription); return cronTimer.getDueDate(startDate == null ? ClockUtil.getCurrentTime() : startDate); } } catch (Exception e) { throw LOG.exceptionWhileParsingCycleExpresison(duedateDescription, e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\calendar\CycleBusinessCalendar.java
1
请在Spring Boot框架中完成以下Java代码
public String getClientInfo(String name) throws SQLException { return delegate.getClientInfo(name); } @Override public Properties getClientInfo() throws SQLException { return delegate.getClientInfo(); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return delegate.createArrayOf(typeName, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return delegate.createStruct(typeName, attributes); } @Override public void setSchema(String schema) throws SQLException { delegate.setSchema(schema); } @Override public String getSchema() throws SQLException { return delegate.getSchema(); } @Override public void abort(Executor executor) throws SQLException
{ delegate.abort(executor); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { delegate.setNetworkTimeout(executor, milliseconds); } @Override public int getNetworkTimeout() throws SQLException { return delegate.getNetworkTimeout(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\JasperJdbcConnection.java
2
请完成以下Java代码
public static boolean isCancelledContract(@NonNull final I_C_Flatrate_Term term) { return X_C_Flatrate_Term.CONTRACTSTATUS_Quit.equals(term.getContractStatus()) || X_C_Flatrate_Term.CONTRACTSTATUS_Voided.equals(term.getContractStatus()); } private static final CCache<Integer, I_C_Flatrate_Term> IC_2_TERM = CCache .<Integer, I_C_Flatrate_Term>builder() .cacheName(I_C_Invoice_Candidate.Table_Name + "#by#" + I_C_Invoice_Candidate.COLUMNNAME_AD_Table_ID + "#" + I_C_Invoice_Candidate.COLUMNNAME_Record_ID) .tableName(I_C_Invoice_Candidate.Table_Name) .additionalTableNameToResetFor(I_C_Flatrate_Term.Table_Name) .build(); public static I_C_Flatrate_Term retrieveTerm(@NonNull final I_C_Invoice_Candidate ic) { return IC_2_TERM.getOrLoad(ic.getC_Invoice_Candidate_ID(), () -> retrieveTermForCache(ic)); } private static I_C_Flatrate_Term retrieveTermForCache(@NonNull final I_C_Invoice_Candidate ic) { final int flatrateTermTableId = getTableId(I_C_Flatrate_Term.class); Check.assume(ic.getAD_Table_ID() == flatrateTermTableId, "{} has AD_Table_ID={}", ic, flatrateTermTableId); final I_C_Flatrate_Term term = TableRecordReference .ofReferenced(ic) .getModel(getContextAware(ic), I_C_Flatrate_Term.class); return Check.assumeNotNull(term, "The given invoice candidate references a {}; ic={}", I_C_Flatrate_Term.class.getSimpleName(), ic); } /** * <ul> * <li>QtyDelivered := QtyOrdered * <li>DeliveryDate := DateOrdered * <li>M_InOut_ID: untouched * </ul> * * @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate) */ public static void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic) { // note: we can assume that #setQtyOrdered() was already called ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially ic.setQtyDeliveredInUOM(ic.getQtyEntered()); ic.setDeliveryDate(ic.getDateOrdered()); }
public static void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Flatrate_Term term = retrieveTerm(ic); InvoiceCandidateLocationAdapterFactory .billLocationAdapter(ic) .setFrom(ContractLocationHelper.extractBillLocation(term)); } public static UomId retrieveUomId(@NonNull final I_C_Invoice_Candidate icRecord) { final I_C_Flatrate_Term term = retrieveTerm(icRecord); if (term.getC_UOM_ID() > 0) { return UomId.ofRepoId(term.getC_UOM_ID()); } if (term.getM_Product_ID() > 0) { final IProductBL productBL = Services.get(IProductBL.class); return productBL.getStockUOMId(term.getM_Product_ID()); } throw new AdempiereException("The term of param 'icRecord' needs to have a UOM; C_Invoice_Candidate_ID=" + icRecord.getC_Invoice_Candidate_ID()) .appendParametersToMessage() .setParameter("term", term) .setParameter("icRecord", icRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\invoicecandidate\HandlerTools.java
1
请在Spring Boot框架中完成以下Java代码
public PatientNoteMapping patientNotePatch(String apiKey, String id, PatientNote body) throws ApiException { ApiResponse<PatientNoteMapping> resp = patientNotePatchWithHttpInfo(apiKey, id, body); return resp.getData(); } /** * PatientenNotiz ändern * Szenario - das WaWi ändert eine PatientenNotiz in Alberta * @param apiKey (required) * @param id Id des Patienten in Alberta (required) * @param body patientNote to update (optional) * @return ApiResponse&lt;PatientNoteMapping&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<PatientNoteMapping> patientNotePatchWithHttpInfo(String apiKey, String id, PatientNote body) throws ApiException { com.squareup.okhttp.Call call = patientNotePatchValidateBeforeCall(apiKey, id, body, null, null); Type localVarReturnType = new TypeToken<PatientNoteMapping>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * PatientenNotiz ändern (asynchronously) * Szenario - das WaWi ändert eine PatientenNotiz in Alberta * @param apiKey (required) * @param id Id des Patienten in Alberta (required) * @param body patientNote to update (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */
public com.squareup.okhttp.Call patientNotePatchAsync(String apiKey, String id, PatientNote body, final ApiCallback<PatientNoteMapping> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = patientNotePatchValidateBeforeCall(apiKey, id, body, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<PatientNoteMapping>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\PatientNoteApi.java
2
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } @Transactional(readOnly = true) public void fetchAuthorWithAllBooks() { Author author = authorRepository.findById(1L).orElseThrow(); List<Book> books = author.getBooks(); System.out.println(books); }
@Transactional(readOnly = true) public void fetchAuthorWithCheapBooks() { Author author = authorRepository.findById(1L).orElseThrow(); List<Book> books = author.getCheapBooks(); System.out.println(books); } @Transactional(readOnly = true) public void fetchAuthorWithRestOfBooks() { Author author = authorRepository.findById(1L).orElseThrow(); List<Book> books = author.getRestOfBooks(); System.out.println(books); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFilterAssociation\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public class CartItemEvent { private String itemId; private int quantity; public CartItemEvent(String itemId, int quantity) { this.itemId = itemId; this.quantity = quantity; } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId;
} public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @Override public String toString() { return "CartItemEvent{" + "itemId='" + itemId + '\'' + ", quantity=" + quantity + '}'; } }
repos\tutorials-master\messaging-modules\apache-rocketmq\src\main\java\com\baeldung\rocketmq\event\CartItemEvent.java
1
请完成以下Java代码
private final List<I_M_Movement> retrieveMovementsForInOut(final I_M_InOut inout) { Check.assumeNotNull(inout, "inout not null"); return Services.get(IQueryBL.class) .createQueryBuilder(I_M_Movement.class, inout) .addEqualsFilter(I_M_Movement.COLUMNNAME_M_InOut_ID, inout.getM_InOut_ID()) .create() .list(I_M_Movement.class); } @Override public void reverseMovements(final I_M_InOut inout) { final IDocumentBL docActionBL = Services.get(IDocumentBL.class); //
// Iterate all linked movements and reverse them one by one (if not already reversed) final List<I_M_Movement> movements = retrieveMovementsForInOut(inout); for (final I_M_Movement movement : movements) { // Skip those movements which were already reversed if (docActionBL.isDocumentReversedOrVoided(movement)) { // already reversed, nothing to do continue; } // Reverse movement docActionBL.processEx(movement, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\api\impl\InOutMovementBL.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { List<SignalEventSubscriptionEntity> signalEvents = null; EventSubscriptionEntityManager eventSubscriptionEntityManager = commandContext.getEventSubscriptionEntityManager(); if (executionId == null) { signalEvents = eventSubscriptionEntityManager.findSignalEventSubscriptionsByEventName(eventName, tenantId); } else { ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId); if (execution == null) { throw new ActivitiObjectNotFoundException( "Cannot find execution with id '" + executionId + "'", Execution.class ); } if (execution.isSuspended()) { throw new ActivitiException( "Cannot throw signal event '" + eventName + "' because execution '" + executionId + "' is suspended" ); } signalEvents = eventSubscriptionEntityManager.findSignalEventSubscriptionsByNameAndExecution( eventName, executionId
); if (signalEvents.isEmpty()) { throw new ActivitiException( "Execution '" + executionId + "' has not subscribed to a signal event with name '" + eventName + "'." ); } } for (SignalEventSubscriptionEntity signalEventSubscriptionEntity : signalEvents) { // We only throw the event to globally scoped signals. // Process instance scoped signals must be thrown within the process itself if (signalEventSubscriptionEntity.isGlobalScoped()) { eventSubscriptionEntityManager.eventReceived(signalEventSubscriptionEntity, payload, async); } } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SignalEventReceivedCmd.java
1
请完成以下Java代码
public void setTemplateXST (String TemplateXST) { set_Value (COLUMNNAME_TemplateXST, TemplateXST); } /** Get TemplateXST. @return Contains the template code itself */ public String getTemplateXST () { return (String)get_Value(COLUMNNAME_TemplateXST); } /** Set Search Key. @param Value
Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template.java
1
请在Spring Boot框架中完成以下Java代码
public UserSummary getCurrentUser(@CurrentUser UserPrincipal currentUser) { UserSummary userSummary = new UserSummary(currentUser.getId(), currentUser.getUsername(),currentUser.getSurname(), currentUser.getName(), currentUser.getLastname(), currentUser.getCity()); return userSummary; } @GetMapping("/user/checkUsernameAvailability") public UserIdentityAvailability checkUsernameAvailability(@RequestParam(value = "username") String username) { Boolean isAvailable = !userRepository.existsByUsername(username); return new UserIdentityAvailability(isAvailable); } @GetMapping("/user/checkEmailAvialability") public UserIdentityAvailability checkEmailAvailability(@RequestParam(value = "email") String email) { Boolean isAvailable = !userRepository.existsByEmail(email); return new UserIdentityAvailability(isAvailable); } @PostMapping("/users/getBySearch") public Optional<User> getUserBySearch(@RequestParam(value = "username") String username) { return userRepository.findByUsername(username); } @GetMapping("/users/getAllUsers") public List<String> getAllUsers(@PathVariable(value = "id") Long id)
{ return userRepository.findAllUsers(); } @GetMapping("/users/{id}") public UserProfile getUserProfile(@PathVariable(value = "id") Long id) { User user = userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User", "username", id)); UserProfile userProfile = new UserProfile(user.getId(), user.getSurname(), user.getName(), user.getLastname(), user.getUsername(), user.getCreatedAt(), user.getPhone(), user.getEmail(), user.getPassword(), user.getCity()); userUtils.initUserAvatar(userProfile, user); return userProfile; } @PostMapping("/users/saveUserProfile") public ResponseEntity<?> saveUserProfile(@CurrentUser UserPrincipal userPrincipal, @RequestBody UserProfile userProfileForm) { return userService.saveUserProfile(userPrincipal, userProfileForm); } @PostMapping("/users/saveCity") public Boolean saveCity(@CurrentUser UserPrincipal userPrincipal, @RequestBody String city) { return userService.saveCity(userPrincipal, city); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\controller\UserController.java
2
请完成以下Java代码
public void afterRegionDestroy(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.DESTROY); } @Override public void afterRegionInvalidate(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.INVALIDATE); } @Override public void afterRegionLive(RegionEvent<K, V> event) { processRegionEvent(event, RegionEventType.LIVE); } protected void processRegionEvent(RegionEvent<K, V> event, RegionEventType eventType) { } public enum EntryEventType {
CREATE, DESTROY, INVALIDATE, UPDATE; } public enum RegionEventType { CLEAR, CREATE, DESTROY, INVALIDATE, LIVE; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\cache\AbstractCommonEventProcessingCacheListener.java
1
请完成以下Java代码
public OAuth2DeviceCode generate(OAuth2TokenContext context) { if (context.getTokenType() == null || !OAuth2ParameterNames.DEVICE_CODE.equals(context.getTokenType().getValue())) { return null; } Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt .plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive()); return new OAuth2DeviceCode(this.deviceCodeGenerator.generateKey(), issuedAt, expiresAt); } } private static final class UserCodeStringKeyGenerator implements StringKeyGenerator { // @formatter:off private static final char[] VALID_CHARS = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z' }; // @formatter:on private final BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(8); @Override public String generateKey() { byte[] bytes = this.keyGenerator.generateKey(); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { int offset = Math.abs(b % 20);
sb.append(VALID_CHARS[offset]); } sb.insert(4, '-'); return sb.toString(); } } private static final class OAuth2UserCodeGenerator implements OAuth2TokenGenerator<OAuth2UserCode> { private final StringKeyGenerator userCodeGenerator = new UserCodeStringKeyGenerator(); @Nullable @Override public OAuth2UserCode generate(OAuth2TokenContext context) { if (context.getTokenType() == null || !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) { return null; } Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt .plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive()); return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
1
请完成以下Java代码
public void setOperation (final java.lang.String Operation) { set_Value (COLUMNNAME_Operation, Operation); } @Override public java.lang.String getOperation() { return get_ValueAsString(COLUMNNAME_Operation); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @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); } @Override public void setValue2 (final java.lang.String Value2) { set_Value (COLUMNNAME_Value2, Value2); } @Override public java.lang.String getValue2() { return get_ValueAsString(COLUMNNAME_Value2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NextCondition.java
1
请完成以下Java代码
public class RelatedDocumentsEvaluationContext { @Getter private final RelatedDocumentsPermissions permissions; @Getter private final RelatedDocumentsId onlyRelatedDocumentsId; @Nullable private final HashMap<RelatedDocumentsTargetWindow, Priority> alreadySeenWindows; @Builder private RelatedDocumentsEvaluationContext( @NonNull final RelatedDocumentsPermissions permissions, @Nullable final RelatedDocumentsId onlyRelatedDocumentsId, final boolean doNotTrackSeenWindows) { this.permissions = permissions; this.onlyRelatedDocumentsId = onlyRelatedDocumentsId; this.alreadySeenWindows = doNotTrackSeenWindows ? null : new HashMap<>();
} public Priority getPriorityOrNull(final RelatedDocumentsTargetWindow window) { return alreadySeenWindows != null ? alreadySeenWindows.get(window) : null; } public void putAlreadySeenWindow(@NonNull final RelatedDocumentsTargetWindow targetWindow, @NonNull final Priority priority) { if (alreadySeenWindows != null) { alreadySeenWindows.put(targetWindow, priority); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\RelatedDocumentsEvaluationContext.java
1
请完成以下Java代码
default I_PP_Product_BOM getById(final int productBomId) { return productBomId > 0 ? getById(ProductBOMId.ofRepoId(productBomId)) : null; } List<I_PP_Product_BOM> getByIds(Collection<ProductBOMId> bomIds); I_PP_Product_BOMLine getBOMLineById(int productBOMLineId); ImmutableList<I_PP_Product_BOMLine> retrieveLines(I_PP_Product_BOM productBOM); List<I_PP_Product_BOMLine> retrieveLinesByBOMIds(Collection<ProductBOMId> bomIds); int retrieveLastLineNo(int ppProductBOMId); Optional<I_PP_Product_BOM> getDefaultBOMByProductId(ProductId productId); Optional<ProductBOMId> getDefaultBOMIdByProductId(ProductId productId); boolean hasBOMs(ProductId productId); List<I_PP_Product_BOMLine> retrieveBOMLinesByComponentIdInTrx(ProductId productId); List<I_PP_Product_BOM> retrieveBOMsContainingExactProducts(Collection<Integer> productIds);
default List<I_PP_Product_BOM> retrieveBOMsContainingExactProducts(final Integer... productIds) { return retrieveBOMsContainingExactProducts(Arrays.asList(productIds)); } void save(I_PP_Product_BOMLine bomLine); I_PP_Product_BOM createBOM(ProductBOMVersionsId versionsId, BOMCreateRequest request); ProductId getBOMProductId(ProductBOMId bomId); Optional<ProductBOMId> getLatestBOMByVersion(@NonNull ProductBOMVersionsId bomVersionsId); Optional<I_PP_Product_BOM> getLatestBOMRecordByVersionId(ProductBOMVersionsId bomVersionsId); Optional<I_PP_Product_BOM> getPreviousVersion(I_PP_Product_BOM bomVersion, DocStatus docStatus); boolean isComponent(ProductId productId); Optional<ProductBOMLineId> getBomLineByProductId(@NonNull ProductBOMId productBOMId, @NonNull ProductId productId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\IProductBOMDAO.java
1
请完成以下Java代码
public String getClimate() { return climate; } public void setClimate(String climate) { this.climate = climate; } public Double getPopulation() { return population; } public void setPopulation(Double population) { this.population = population; } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeUTF(climate); community = new Community(); community.setId(5);
out.writeObject(community); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); this.climate = in.readUTF(); community = (Community) in.readObject(); } @Override public String toString() { return "Region = {" + "country='" + super.toString() + '\'' + "community='" + community.toString() + '\'' + "climate='" + climate + '\'' + ", population=" + population + '}'; } }
repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\externalizable\Region.java
1
请完成以下Java代码
public void unLog() { super.unLog(); for (float[][] m : transition_probability2) { for (float[] v : m) { for (int i = 0; i < v.length; i++) { v[i] = (float) Math.exp(v[i]); } } } } @Override
public boolean similar(HiddenMarkovModel model) { if (!(model instanceof SecondOrderHiddenMarkovModel)) return false; SecondOrderHiddenMarkovModel hmm2 = (SecondOrderHiddenMarkovModel) model; for (int i = 0; i < transition_probability.length; i++) { for (int j = 0; j < transition_probability.length; j++) { if (!similar(transition_probability2[i][j], hmm2.transition_probability2[i][j])) return false; } } return super.similar(model); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\SecondOrderHiddenMarkovModel.java
1
请完成以下Java代码
private Iterator<PO> fetchRecords(final MTable table, final List<String> addressColumnNames) { final StringBuilder whereClause = new StringBuilder("1=1"); final List<Object> params = new ArrayList<>(); if (p_AD_Org_ID != null) { whereClause.append(" AND AD_Org_ID = ?"); params.add(p_AD_Org_ID); } final StringBuilder whereAddresses = new StringBuilder(); for (String columnName : addressColumnNames) { if (table.getColumn(columnName) == null) { continue; } if (whereAddresses.length() > 0) { whereAddresses.append(" OR "); } whereAddresses.append(columnName).append(" IS NULL");
} if (whereAddresses.length() == 0) { throw new AdempiereException("Table " + table.getTableName() + " does not have address columns"); } else { whereClause.append(" AND ( ").append(whereAddresses).append(" )"); } return new Query(getCtx(), table.getTableName(), whereClause.toString(), get_TrxName()) .setClient_ID() .setOnlyActiveRecords(true) .setParameters(params) .iterate(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\UpdateAddresses.java
1
请完成以下Java代码
public void updateVisible() { if (container == null) { return; } boolean hasVisibleComponents = false; for (final Component comp : getContentPane().getComponents()) { // Ignore layout components if (comp instanceof Box.Filler) { continue; } if (comp.isVisible()) { hasVisibleComponents = true; break; } } container.setVisible(hasVisibleComponents); } private VPanelLayoutCallback getLayoutCallback() { return VPanelLayoutCallback.forContainer(contentPanel); } private void setLayoutCallback(final VPanelLayoutCallback layoutCallback) { VPanelLayoutCallback.setup(contentPanel, layoutCallback); } public void addIncludedFieldGroup(final VPanelFieldGroup childGroupPanel) { // If it's not an included tab we shall share the same layout constraints as the parent. // This will enforce same minimum widths to all labels and editors of this field group and also to child group panel. if (!childGroupPanel.isIncludedTab()) { childGroupPanel.setLayoutCallback(getLayoutCallback()); } final CC constraints = new CC() .spanX() .growX()
.newline(); contentPanel.add(childGroupPanel.getComponent(), constraints); } public void addLabelAndEditor(final CLabel fieldLabel, final VEditor fieldEditor, final boolean sameLine) { final GridField gridField = fieldEditor.getField(); final GridFieldLayoutConstraints gridFieldConstraints = gridField.getLayoutConstraints(); final boolean longField = gridFieldConstraints != null && gridFieldConstraints.isLongField(); final JComponent editorComp = swingEditorFactory.getEditorComponent(fieldEditor); // // Update layout callback. final VPanelLayoutCallback layoutCallback = getLayoutCallback(); layoutCallback.updateMinWidthFrom(fieldLabel); // NOTE: skip if long field because in that case the minimum length shall not influence the other fields. if (!longField) { layoutCallback.updateMinWidthFrom(fieldEditor); } // // Link Label to Field if (fieldLabel != null) { fieldLabel.setLabelFor(editorComp); fieldLabel.setVerticalAlignment(SwingConstants.TOP); } // // Add label final CC labelConstraints = layoutFactory.createFieldLabelConstraints(sameLine); contentPanel.add(fieldLabel, labelConstraints); // // Add editor final CC editorConstraints = layoutFactory.createFieldEditorConstraints(gridFieldConstraints); contentPanel.add(editorComp, editorConstraints); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFieldGroup.java
1
请完成以下Java代码
public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) { return executeWithinProcessApplication(callback, processApplicationReference, null); } public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference, InvocationContext invocationContext) { String paName = processApplicationReference.getName(); try { ProcessApplicationInterface processApplication = processApplicationReference.getProcessApplication(); setCurrentProcessApplication(processApplicationReference); try { // wrap callback ProcessApplicationClassloaderInterceptor<T> wrappedCallback = new ProcessApplicationClassloaderInterceptor<T>(callback); // execute wrapped callback return processApplication.execute(wrappedCallback, invocationContext); } catch (Exception e) {
// unwrap exception if(e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); }else { throw new ProcessEngineException("Unexpected exeption while executing within process application ", e); } } finally { removeCurrentProcessApplication(); } } catch (ProcessApplicationUnavailableException e) { throw new ProcessEngineException("Cannot switch to process application '"+paName+"' for execution: "+e.getMessage(), e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\context\Context.java
1
请完成以下Java代码
public static HuId ofObject(@NonNull final Object object) { return RepoIdAwares.ofObject(object, HuId.class); } @Nullable public static HuId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final HuId huId) { return huId != null ? huId.getRepoId() : -1; } public static Set<HuId> ofRepoIds(@NonNull final Collection<Integer> repoIds) { return repoIds.stream().map(HuId::ofRepoId).collect(ImmutableSet.toImmutableSet()); } public static Set<Integer> toRepoIds(@NonNull final Collection<HuId> huIds) { return huIds.stream().map(HuId::getRepoId).collect(ImmutableSet.toImmutableSet()); } public static Set<HuId> fromRepoIds(@Nullable final Collection<Integer> huRepoIds) { if (huRepoIds == null || huRepoIds.isEmpty()) { return ImmutableSet.of(); } return huRepoIds.stream().map(HuId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } public static HuId ofHUValue(@NonNull final String huValue) { try { return ofRepoId(Integer.parseInt(huValue)); } catch (final Exception ex) { final AdempiereException metasfreshException = new AdempiereException("Invalid HUValue `" + huValue + "`. It cannot be converted to M_HU_ID."); metasfreshException.addSuppressed(ex); throw metasfreshException;
} } 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
请完成以下Java代码
public synchronized String getNextId() { if (lastId<nextId) { getNewBlock(); } long _nextId = nextId++; return Long.toString(_nextId); } protected synchronized void getNewBlock() { // TODO http://jira.codehaus.org/browse/ACT-45 use a separate 'requiresNew' command executor IdBlock idBlock = commandExecutor.execute(new GetNextIdBlockCmd(idBlockSize)); this.nextId = idBlock.getNextId(); this.lastId = idBlock.getLastId(); } public int getIdBlockSize() { return idBlockSize; } public void setIdBlockSize(int idBlockSize) { this.idBlockSize = idBlockSize; } public CommandExecutor getCommandExecutor() {
return commandExecutor; } public void setCommandExecutor(CommandExecutor commandExecutor) { this.commandExecutor = commandExecutor; } /** * Reset inner state so that the generator fetches a new block of IDs from the database * when the next ID generation request is received. */ public void reset() { nextId = 0; lastId = -1; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\DbIdGenerator.java
1
请完成以下Java代码
public static HUReservationDocRef ofPickingJobStepId(@NonNull final PickingJobStepId pickingJobStepId) {return HUReservationDocRef.builder().pickingJobStepId(pickingJobStepId).build();} public static HUReservationDocRef ofDDOrderLineId(@NonNull final DDOrderLineId ddOrderLineId) {return HUReservationDocRef.builder().ddOrderLineId(ddOrderLineId).build();} @Builder private HUReservationDocRef( @Nullable final OrderLineId salesOrderLineId, @Nullable final ProjectId projectId, @Nullable final PickingJobStepId pickingJobStepId, @Nullable DDOrderLineId ddOrderLineId) { if (CoalesceUtil.countNotNulls(salesOrderLineId, projectId, pickingJobStepId, ddOrderLineId) != 1) { throw new AdempiereException("One and only one document shall be set") .appendParametersToMessage() .setParameter("salesOrderLineId", salesOrderLineId) .setParameter("projectId", projectId) .setParameter("pickingJobStepId", pickingJobStepId) .setParameter("ddOrderLineId", ddOrderLineId); } this.salesOrderLineId = salesOrderLineId; this.projectId = projectId; this.pickingJobStepId = pickingJobStepId; this.ddOrderLineId = ddOrderLineId; } public static boolean equals(@Nullable final HUReservationDocRef ref1, @Nullable final HUReservationDocRef ref2) {return Objects.equals(ref1, ref2);} public interface CaseMappingFunction<R> { R salesOrderLineId(@NonNull OrderLineId salesOrderLineId); R projectId(@NonNull ProjectId projectId); R pickingJobStepId(@NonNull PickingJobStepId pickingJobStepId);
R ddOrderLineId(@NonNull DDOrderLineId ddOrderLineId); } public <R> R map(@NonNull final CaseMappingFunction<R> mappingFunction) { if (salesOrderLineId != null) { return mappingFunction.salesOrderLineId(salesOrderLineId); } else if (projectId != null) { return mappingFunction.projectId(projectId); } else if (pickingJobStepId != null) { return mappingFunction.pickingJobStepId(pickingJobStepId); } else if (ddOrderLineId != null) { return mappingFunction.ddOrderLineId(ddOrderLineId); } else { throw new IllegalStateException("Unknown state: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationDocRef.java
1
请完成以下Java代码
void stop() { this.webServer.stop(); } WebServer getWebServer() { return this.webServer; } HttpHandler getHandler() { return this.handler; } /** * A delayed {@link HttpHandler} that doesn't initialize things too early. */ static final class DelayedInitializationHttpHandler implements HttpHandler { private final Supplier<HttpHandler> handlerSupplier; private final boolean lazyInit; private volatile HttpHandler delegate = this::handleUninitialized; private DelayedInitializationHttpHandler(Supplier<HttpHandler> handlerSupplier, boolean lazyInit) { this.handlerSupplier = handlerSupplier; this.lazyInit = lazyInit; } private Mono<Void> handleUninitialized(ServerHttpRequest request, ServerHttpResponse response) { throw new IllegalStateException("The HttpHandler has not yet been initialized"); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.handle(request, response); } void initializeHandler() { this.delegate = this.lazyInit ? new LazyHttpHandler(this.handlerSupplier) : this.handlerSupplier.get(); } HttpHandler getHandler() { return this.delegate; } }
/** * {@link HttpHandler} that initializes its delegate on first request. */ private static final class LazyHttpHandler implements HttpHandler { private final Mono<HttpHandler> delegate; private LazyHttpHandler(Supplier<HttpHandler> handlerSupplier) { this.delegate = Mono.fromSupplier(handlerSupplier); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.flatMap((handler) -> handler.handle(request, response)); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\WebServerManager.java
1
请在Spring Boot框架中完成以下Java代码
public class Owner extends Person { @Column @NotBlank private String address; @Column @NotBlank private String city; @Column @NotBlank @Pattern(regexp = "\\d{10}", message = "{telephone.invalid}") private String telephone; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "owner_id") @OrderBy("name") private final List<Pet> pets = new ArrayList<>(); public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } public String getTelephone() { return this.telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public List<Pet> getPets() { return this.pets; } public void addPet(Pet pet) { if (pet.isNew()) { getPets().add(pet); } } /** * Return the Pet with the given name, or null if none found for this Owner. * @param name to test * @return the Pet with the given name, or null if no such Pet exists for this Owner */ public Pet getPet(String name) { return getPet(name, false); } /** * Return the Pet with the given id, or null if none found for this Owner. * @param id to test * @return the Pet with the given id, or null if no such Pet exists for this Owner */ public Pet getPet(Integer id) { for (Pet pet : getPets()) { if (!pet.isNew()) {
Integer compId = pet.getId(); if (Objects.equals(compId, id)) { return pet; } } } return null; } /** * Return the Pet with the given name, or null if none found for this Owner. * @param name to test * @param ignoreNew whether to ignore new pets (pets that are not saved yet) * @return the Pet with the given name, or null if no such Pet exists for this Owner */ public Pet getPet(String name, boolean ignoreNew) { for (Pet pet : getPets()) { String compName = pet.getName(); if (compName != null && compName.equalsIgnoreCase(name)) { if (!ignoreNew || !pet.isNew()) { return pet; } } } return null; } @Override public String toString() { return new ToStringCreator(this).append("id", this.getId()) .append("new", this.isNew()) .append("lastName", this.getLastName()) .append("firstName", this.getFirstName()) .append("address", this.address) .append("city", this.city) .append("telephone", this.telephone) .toString(); } /** * Adds the given {@link Visit} to the {@link Pet} with the given identifier. * @param petId the identifier of the {@link Pet}, must not be {@literal null}. * @param visit the visit to add, must not be {@literal null}. */ public void addVisit(Integer petId, Visit visit) { Assert.notNull(petId, "Pet identifier must not be null!"); Assert.notNull(visit, "Visit must not be null!"); Pet pet = getPet(petId); Assert.notNull(pet, "Invalid Pet identifier!"); pet.addVisit(visit); } }
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\Owner.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getIban() { return iban; } public void setIban(String iban) { this.iban = iban; }
public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public File getMainDirectory() { return mainDirectory; } public void setMainDirectory(File mainDirectory) { this.mainDirectory = mainDirectory; } }
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\bval\model\User.java
1
请完成以下Java代码
private void writeService(IndentingWriter writer, ComposeService service) { writer.indented(() -> { writer.println(service.getName() + ":"); writer.indented(() -> { writer.println("image: '%s:%s'".formatted(service.getImage(), service.getImageTag())); writerServiceEnvironment(writer, service.getEnvironment()); writerServiceLabels(writer, service.getLabels()); writerServicePorts(writer, service.getPorts()); writeServiceCommand(writer, service.getCommand()); }); }); } private void writerServiceEnvironment(IndentingWriter writer, Map<String, String> environment) { if (environment.isEmpty()) { return; } writer.println("environment:"); writer.indented(() -> { for (Map.Entry<String, String> env : environment.entrySet()) { writer.println("- '%s=%s'".formatted(env.getKey(), env.getValue())); } }); } private void writerServicePorts(IndentingWriter writer, Set<Integer> ports) { if (ports.isEmpty()) { return; } writer.println("ports:"); writer.indented(() -> { for (Integer port : ports) { writer.println("- '%d'".formatted(port)); } }); }
private void writeServiceCommand(IndentingWriter writer, String command) { if (!StringUtils.hasText(command)) { return; } writer.println("command: '%s'".formatted(command)); } private void writerServiceLabels(IndentingWriter writer, Map<String, String> labels) { if (labels.isEmpty()) { return; } writer.println("labels:"); writer.indented(() -> { for (Map.Entry<String, String> label : labels.entrySet()) { writer.println("- \"%s=%s\"".formatted(label.getKey(), label.getValue())); } }); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeFileWriter.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableList<MatchInv> deleteAndReturn(@NonNull final MatchInvQuery query) { final ImmutableList<I_M_MatchInv> records = toSqlQuery(query).list(); if (records.isEmpty()) { return ImmutableList.of(); } final ImmutableList<MatchInv> matchInvs = records.stream().map(MatchInvoiceRepository::fromRecord).collect(ImmutableList.toImmutableList()); InterfaceWrapperHelper.deleteAll(records, false); return matchInvs; } private IQueryBuilder<I_M_MatchInv> toSqlQuery(final MatchInvQuery query) { final IQueryBuilder<I_M_MatchInv> sqlQueryBuilder = queryBL.createQueryBuilder(I_M_MatchInv.class) .orderBy(I_M_MatchInv.COLUMN_M_MatchInv_ID); if (query.isOnlyActive()) { sqlQueryBuilder.addOnlyActiveRecordsFilter(); } if (query.getType() != null) { sqlQueryBuilder.addEqualsFilter(I_M_MatchInv.COLUMNNAME_Type, query.getType()); } if (query.getInvoiceId() != null) { sqlQueryBuilder.addEqualsFilter(I_M_MatchInv.COLUMNNAME_C_Invoice_ID, query.getInvoiceId()); } if (query.getInvoiceAndLineId() != null) { sqlQueryBuilder.addEqualsFilter(I_M_MatchInv.COLUMNNAME_C_InvoiceLine_ID, query.getInvoiceAndLineId()); } if (query.getInoutId() != null) { sqlQueryBuilder.addEqualsFilter(I_M_MatchInv.COLUMNNAME_M_InOut_ID, query.getInoutId()); } if (query.getInoutLineId() != null) { sqlQueryBuilder.addEqualsFilter(I_M_MatchInv.COLUMNNAME_M_InOutLine_ID, query.getInoutLineId()); } if (query.getInoutCostId() != null)
{ sqlQueryBuilder.addEqualsFilter(I_M_MatchInv.COLUMNNAME_M_InOut_Cost_ID, query.getInoutCostId()); } if (query.getAsiId() != null) { sqlQueryBuilder.addEqualsFilter(I_M_MatchInv.COLUMNNAME_M_AttributeSetInstance_ID, query.getAsiId()); } return sqlQueryBuilder; } public Set<MatchInvId> getIdsProcessedButNotPostedByInOutLineIds(@NonNull final Set<InOutLineId> inoutLineIds) { if (inoutLineIds.isEmpty()) { return ImmutableSet.of(); } return queryBL .createQueryBuilder(I_M_MatchInv.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_M_MatchInv.COLUMN_M_InOutLine_ID, inoutLineIds) .addEqualsFilter(I_M_MatchInv.COLUMN_Processed, true) .addNotEqualsFilter(I_M_MatchInv.COLUMN_Posted, true) .create() .idsAsSet(MatchInvId::ofRepoId); } public Set<MatchInvId> getIdsProcessedButNotPostedByInvoiceLineIds(@NonNull final Set<InvoiceAndLineId> invoiceAndLineIds) { if (invoiceAndLineIds.isEmpty()) { return ImmutableSet.of(); } return queryBL .createQueryBuilder(I_M_MatchInv.class) .addOnlyActiveRecordsFilter() .addInArrayOrAllFilter(I_M_MatchInv.COLUMN_C_InvoiceLine_ID, invoiceAndLineIds) .addEqualsFilter(I_M_MatchInv.COLUMN_Processed, true) .addNotEqualsFilter(I_M_MatchInv.COLUMN_Posted, true) .create() .idsAsSet(MatchInvId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\service\MatchInvoiceRepository.java
2
请完成以下Java代码
public boolean equalsByMatchCriteria(@NonNull final PricingConditionsBreak reference) { if (this == reference) { return true; } return Objects.equals(matchCriteria, reference.matchCriteria); } public boolean isTemporaryPricingConditionsBreak() { return hasChanges || id == null; } public PricingConditionsBreak toTemporaryPricingConditionsBreak() { if (isTemporaryPricingConditionsBreak()) { return this; }
return toBuilder().id(null).build(); } public PricingConditionsBreak toTemporaryPricingConditionsBreakIfPriceRelevantFieldsChanged(@NonNull final PricingConditionsBreak reference) { if (isTemporaryPricingConditionsBreak()) { return this; } if (equalsByPriceRelevantFields(reference)) { return this; } return toTemporaryPricingConditionsBreak(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreak.java
1
请完成以下Java代码
public int getNoProductCount () { Integer ii = (Integer)get_Value(COLUMNNAME_NoProductCount); if (ii == null) return 0; return ii.intValue(); } /** Set Number of runs. @param NumberOfRuns Frequency of processing Perpetual Inventory */ public void setNumberOfRuns (int NumberOfRuns) { set_Value (COLUMNNAME_NumberOfRuns, Integer.valueOf(NumberOfRuns)); } /** Get Number of runs. @return Frequency of processing Perpetual Inventory */ public int getNumberOfRuns () { Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfRuns); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
} /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PerpetualInv.java
1
请在Spring Boot框架中完成以下Java代码
public void process(final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final String remoteUrl = request.getParameters().get(ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL); if (Check.isBlank(remoteUrl)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL); } final String routingKey = request.getParameters().get(ExternalSystemConstants.PARAM_RABBITMQ_HTTP_ROUTING_KEY); if (Check.isBlank(routingKey)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_RABBITMQ_HTTP_ROUTING_KEY); } final String authToken = request.getParameters().get(ExternalSystemConstants.PARAM_RABBIT_MQ_AUTH_TOKEN); if (Check.isBlank(authToken)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_RABBIT_MQ_AUTH_TOKEN); } final ExportBPartnerRouteContext exportBPartnerRouteContext = ExportBPartnerRouteContext.builder() .remoteUrl(remoteUrl) .routingKey(routingKey) .authToken(authToken) .build(); exchange.setProperty(ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, exportBPartnerRouteContext);
final String bPartnerIdentifier = request.getParameters().get(ExternalSystemConstants.PARAM_BPARTNER_ID); if (Check.isBlank(bPartnerIdentifier)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_BPARTNER_ID); } final JsonMetasfreshId externalSystemConfigId = request.getExternalSystemConfigId(); final JsonMetasfreshId adPInstanceId = request.getAdPInstanceId(); final BPRetrieveCamelRequest retrieveCamelRequest = BPRetrieveCamelRequest.builder() .bPartnerIdentifier(bPartnerIdentifier) .externalSystemConfigId(externalSystemConfigId) .adPInstanceId(adPInstanceId) .build(); exchange.getIn().setBody(retrieveCamelRequest); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-rabbitmq\src\main\java\de\metas\camel\externalsystems\rabbitmq\bpartner\processor\ExportBPartnerProcessor.java
2
请完成以下Java代码
public int hashCode() { return Objects.hash(this.text); } @Override public String toString() { return this.text; } /** * Load {@link PemContent} from the given content (either the PEM content itself or a * reference to the resource to load). * @param content the content to load * @param resourceLoader the resource loader used to load content * @return a new {@link PemContent} instance or {@code null} * @throws IOException on IO error */ static @Nullable PemContent load(@Nullable String content, ResourceLoader resourceLoader) throws IOException { if (!StringUtils.hasLength(content)) { return null; } if (isPresentInText(content)) { return new PemContent(content); } try (InputStream in = resourceLoader.getResource(content).getInputStream()) { return load(in); } catch (IOException | UncheckedIOException ex) { throw new IOException("Error reading certificate or key from file '%s'".formatted(content), ex); } } /** * Load {@link PemContent} from the given {@link Path}. * @param path a path to load the content from * @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(Path path) throws IOException { Assert.notNull(path, "'path' must not be null"); try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { return load(in); } } /** * Load {@link PemContent} from the given {@link InputStream}. * @param in an input stream to load the content from
* @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(InputStream in) throws IOException { return of(StreamUtils.copyToString(in, StandardCharsets.UTF_8)); } /** * Return a new {@link PemContent} instance containing the given text. * @param text the text containing PEM encoded content * @return a new {@link PemContent} instance */ @Contract("!null -> !null") public static @Nullable PemContent of(@Nullable String text) { return (text != null) ? new PemContent(text) : null; } /** * Return if PEM content is present in the given text. * @param text the text to check * @return if the text includes PEM encoded content. */ public static boolean isPresentInText(@Nullable String text) { return text != null && PEM_HEADER.matcher(text).find() && PEM_FOOTER.matcher(text).find(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemContent.java
1
请在Spring Boot框架中完成以下Java代码
default boolean isMember(ObservationHandler<?> handler) { return handlerType().isInstance(handler); } /** * Register group members against the given {@link ObservationConfig}. * @param config the config used to register members * @param members the group members to register */ default void registerMembers(ObservationConfig config, List<ObservationHandler<?>> members) { config.observationHandler(new FirstMatchingCompositeObservationHandler(members)); } @Override default int compareTo(ObservationHandlerGroup other) { return 0; } /** * Return the primary type of handler that this group accepts. * @return the accepted handler type */
Class<?> handlerType(); /** * Static factory method to create an {@link ObservationHandlerGroup} with members of * the given handler type. * @param <H> the handler type * @param handlerType the handler type * @return a new {@link ObservationHandlerGroup} */ static <H extends ObservationHandler<?>> ObservationHandlerGroup of(Class<H> handlerType) { Assert.notNull(handlerType, "'handlerType' must not be null"); return () -> handlerType; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationHandlerGroup.java
2
请在Spring Boot框架中完成以下Java代码
public class FooController { @Autowired private FooDao fooDao; @GetMapping(value = "/{id}") public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { return fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); } // Note: the global filter overrides the ETag value we set here. We can still // analyze its behaviour in the Integration Test. @GetMapping(value = "/{id}/custom-etag") public ResponseEntity<Foo> findByIdWithCustomEtag(@PathVariable("id") final Long id, final HttpServletResponse response) { final Foo foo = fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); return ResponseEntity.ok().eTag(Long.toString(foo.getVersion())).body(foo); } @PostMapping
@ResponseStatus(HttpStatus.CREATED) public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { return fooDao.save(resource); } @PutMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { fooDao.save(resource); } @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable("id") final Long id) { fooDao.deleteById(id); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-3\src\main\java\com\baeldung\etag\FooController.java
2
请完成以下Java代码
public class RoleVO extends Role implements INode<RoleVO> { @Serial private static final long serialVersionUID = 1L; /** * 主键ID */ @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 父节点ID */ @JsonSerialize(using = ToStringSerializer.class) private Long parentId; /** * 子孙节点 */
@JsonInclude(JsonInclude.Include.NON_EMPTY) private List<RoleVO> children; @Override public List<RoleVO> getChildren() { if (this.children == null) { this.children = new ArrayList<>(); } return this.children; } /** * 上级角色 */ private String parentName; }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\vo\RoleVO.java
1
请完成以下Java代码
public void setAdditionalText(final @Nullable String AdditionalText) { set_Value(COLUMNNAME_AdditionalText, AdditionalText); } @Override public @NotNull String getAdditionalText() { return get_ValueAsString(COLUMNNAME_AdditionalText); } @Override public I_C_BPartner_DocType getC_BPartner_DocType() { return get_ValueAsPO(COLUMNNAME_C_BPartner_DocType_ID, I_C_BPartner_DocType.class); } @Override public void setC_BPartner_DocType(final I_C_BPartner_DocType C_BPartner_DocType) { set_ValueFromPO(COLUMNNAME_C_BPartner_DocType_ID, I_C_BPartner_DocType.class, C_BPartner_DocType); } @Override public void setC_BPartner_DocType_ID(final int C_BPartner_DocType_ID) { if (C_BPartner_DocType_ID < 1) set_Value(COLUMNNAME_C_BPartner_DocType_ID, null); else set_Value(COLUMNNAME_C_BPartner_DocType_ID, C_BPartner_DocType_ID); } @Override public int getC_BPartner_DocType_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_DocType_ID); } @Override public void setC_BPartner_ID(final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value(COLUMNNAME_C_BPartner_ID, null); else set_Value(COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_BPartner_Report_Text_ID(final int C_BPartner_Report_Text_ID)
{ if (C_BPartner_Report_Text_ID < 1) set_ValueNoCheck(COLUMNNAME_C_BPartner_Report_Text_ID, null); else set_ValueNoCheck(COLUMNNAME_C_BPartner_Report_Text_ID, C_BPartner_Report_Text_ID); } @Override public int getC_BPartner_Report_Text_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Report_Text_ID); } @Override public void setValue(final String Value) { set_Value(COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\partnerreporttext\model\X_C_BPartner_Report_Text.java
1
请完成以下Java代码
public class PDFMerge { public void mergeUsingPDFBox(List<String> pdfFiles, String outputFile) throws IOException { PDFMergerUtility pdfMergerUtility = new PDFMergerUtility(); pdfMergerUtility.setDestinationFileName(outputFile); pdfFiles.forEach(file -> { try { pdfMergerUtility.addSource(new File(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } }); pdfMergerUtility.mergeDocuments(RandomAccessStreamCacheImpl::new); } public void mergeUsingIText(List<String> pdfFiles, String outputFile) throws IOException, DocumentException { List<PdfReader> pdfReaders = List.of(new PdfReader(pdfFiles.get(0)), new PdfReader(pdfFiles.get(1))); Document document = new Document(); FileOutputStream fos = new FileOutputStream(outputFile); PdfWriter writer = PdfWriter.getInstance(document, fos); document.open(); PdfContentByte directContent = writer.getDirectContent();
PdfImportedPage pdfImportedPage; for (PdfReader pdfReader : pdfReaders) { int currentPdfReaderPage = 1; while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) { document.newPage(); pdfImportedPage = writer.getImportedPage(pdfReader, currentPdfReaderPage); directContent.addTemplate(pdfImportedPage, 0, 0); currentPdfReaderPage++; } } fos.flush(); document.close(); fos.close(); } }
repos\tutorials-master\text-processing-libraries-modules\pdf-2\src\main\java\com\baeldung\pdfmerge\PDFMerge.java
1
请在Spring Boot框架中完成以下Java代码
public class HelloResource { // @ApiOperation(value = "return Hello world") @ApiResponses( value = { @ApiResponse(code =100, message = "100 is the message"), @ApiResponse(code = 200, message = "Successful Hello world") } ) @GetMapping public String hello(){ return "Hello World"; }
@ApiOperation(value = "Return Hello World") @PostMapping("/post") public String helloPost(@RequestBody final String hello){ return hello; } @ApiOperation(value = "Return Hello World") @PutMapping("/put") public String helloPut(@RequestBody final String hello) { return hello; } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringSwaggerProjectAgain\src\main\java\spring\swagger\resource\HelloResource.java
2
请在Spring Boot框架中完成以下Java代码
public class JavaProjectGenerationConfiguration { private final ProjectDescription description; public JavaProjectGenerationConfiguration(ProjectDescription description) { this.description = description; } @Bean JavaSourceCodeWriter javaSourceCodeWriter(IndentingWriterFactory indentingWriterFactory) { return new JavaSourceCodeWriter(indentingWriterFactory); } @Bean MainSourceCodeProjectContributor<JavaTypeDeclaration, JavaCompilationUnit, JavaSourceCode> mainJavaSourceCodeProjectContributor( ObjectProvider<MainApplicationTypeCustomizer<?>> mainApplicationTypeCustomizers, ObjectProvider<MainCompilationUnitCustomizer<?, ?>> mainCompilationUnitCustomizers,
ObjectProvider<MainSourceCodeCustomizer<?, ?, ?>> mainSourceCodeCustomizers, JavaSourceCodeWriter javaSourceCodeWriter) { return new MainSourceCodeProjectContributor<>(this.description, JavaSourceCode::new, javaSourceCodeWriter, mainApplicationTypeCustomizers, mainCompilationUnitCustomizers, mainSourceCodeCustomizers); } @Bean TestSourceCodeProjectContributor<JavaTypeDeclaration, JavaCompilationUnit, JavaSourceCode> testJavaSourceCodeProjectContributor( ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers, ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers, JavaSourceCodeWriter javaSourceCodeWriter) { return new TestSourceCodeProjectContributor<>(this.description, JavaSourceCode::new, javaSourceCodeWriter, testApplicationTypeCustomizers, testSourceCodeCustomizers); } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\java\JavaProjectGenerationConfiguration.java
2