instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class GetRenderedStartFormCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; protected String formEngineName; public GetRenderedStartFormCmd(String processDefinitionId, String formEngineName) { this.processDefinitionId = processDefinitionId; this.formEngineName = formEngineName; } @Override public Object execute(CommandContext commandContext) { ProcessDefinition processDefinition = CommandContextUtil.getProcessEngineConfiguration(commandContext).getDeploymentManager().findDeployedProcessDefinitionById(processDefinitionId); if (processDefinition == null) { throw new FlowableObjectNotFoundException("Process Definition '" + processDefinitionId + "' not found", ProcessDefinition.class); } if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) { return Flowable5Util.getFlowable5CompatibilityHandler().getRenderedStartForm(processDefinitionId, formEngineName); } FormHandlerHelper formHandlerHelper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getFormHandlerHelper();
StartFormHandler startFormHandler = formHandlerHelper.getStartFormHandler(commandContext, processDefinition); if (startFormHandler == null) { return null; } FormEngine formEngine = CommandContextUtil.getProcessEngineConfiguration(commandContext).getFormEngines().get(formEngineName); if (formEngine == null) { throw new FlowableException("No formEngine '" + formEngineName + "' defined process engine configuration"); } StartFormData startForm = startFormHandler.createStartFormData(processDefinition); return formEngine.renderStartForm(startForm); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetRenderedStartFormCmd.java
1
请完成以下Java代码
public ModelQuery orderByModelId() { return orderBy(ModelQueryProperty.MODEL_ID); } @Override public ModelQuery orderByModelKey() { return orderBy(ModelQueryProperty.MODEL_KEY); } @Override public ModelQuery orderByModelVersion() { return orderBy(ModelQueryProperty.MODEL_VERSION); } @Override public ModelQuery orderByModelName() { return orderBy(ModelQueryProperty.MODEL_NAME); } @Override public ModelQuery orderByCreateTime() { return orderBy(ModelQueryProperty.MODEL_CREATE_TIME); } @Override public ModelQuery orderByLastUpdateTime() { return orderBy(ModelQueryProperty.MODEL_LAST_UPDATE_TIME); } @Override public ModelQuery orderByTenantId() { return orderBy(ModelQueryProperty.MODEL_TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getModelEntityManager(commandContext).findModelCountByQueryCriteria(this); } @Override public List<Model> executeList(CommandContext commandContext) { return CommandContextUtil.getModelEntityManager(commandContext).findModelsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; }
public String getCategoryLike() { return categoryLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; } public String getKey() { return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ModelQueryImpl.java
1
请完成以下Java代码
public class X_Carrier_Product extends org.compiere.model.PO implements I_Carrier_Product, org.compiere.model.I_Persistent { private static final long serialVersionUID = 720899627L; /** Standard Constructor */ public X_Carrier_Product (final Properties ctx, final int Carrier_Product_ID, @Nullable final String trxName) { super (ctx, Carrier_Product_ID, trxName); } /** Load Constructor */ public X_Carrier_Product (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setCarrier_Product_ID (final int Carrier_Product_ID) { if (Carrier_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_Carrier_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_Carrier_Product_ID, Carrier_Product_ID); } @Override public int getCarrier_Product_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_Product_ID); } @Override
public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Product.java
1
请完成以下Java代码
public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } public Map<Object, DataSource> getDataSources() { return dataSources; } public void setDataSources(Map<Object, DataSource> dataSources) { this.dataSources = dataSources; } // Unsupported ////////////////////////////////////////////////////////// @Override
public PrintWriter getLogWriter() throws SQLException { throw new UnsupportedOperationException(); } @Override public void setLogWriter(PrintWriter out) throws SQLException { throw new UnsupportedOperationException(); } @Override public void setLoginTimeout(int seconds) throws SQLException { throw new UnsupportedOperationException(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\multitenant\TenantAwareDataSource.java
1
请完成以下Java代码
public BPartnerId getVendorId() { return getVendorProductInfo().getVendorId(); } public String getVendorProductNo() { return getVendorProductInfo().getVendorProductNo(); } public ProductId getProductId() { return getVendorProductInfo().getProductId(); } public AttributeSetInstanceId getAttributeSetInstanceId() { return attributeSetInstanceId; } public boolean isAggregatePOs() { if (!isAllowPOAggregation()) { return false;
} return getVendorProductInfo().isAggregatePOs(); } public PurchaseCandidatesGroup allowingPOAggregation(final boolean allowPOAggregation) { if (this.isAllowPOAggregation() == allowPOAggregation) { return this; } return toBuilder().allowPOAggregation(allowPOAggregation).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidatesGroup.java
1
请完成以下Java代码
public Date getEnableTime() { return enableTime; } public void setEnableTime(Date enableTime) { this.enableTime = enableTime; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getMemberLevel() { return memberLevel; } public void setMemberLevel(Integer memberLevel) { this.memberLevel = memberLevel; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", type=").append(type); sb.append(", name=").append(name); sb.append(", platform=").append(platform); sb.append(", count=").append(count); sb.append(", amount=").append(amount); sb.append(", perLimit=").append(perLimit);
sb.append(", minPoint=").append(minPoint); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", useType=").append(useType); sb.append(", note=").append(note); sb.append(", publishCount=").append(publishCount); sb.append(", useCount=").append(useCount); sb.append(", receiveCount=").append(receiveCount); sb.append(", enableTime=").append(enableTime); sb.append(", code=").append(code); sb.append(", memberLevel=").append(memberLevel); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCoupon.java
1
请完成以下Java代码
public static <T> ExplainedOptional<T> of(@NonNull final T value) { return new ExplainedOptional<>(value, null); } private final T value; private final ITranslatableString explanation; private ExplainedOptional(@Nullable final T value, @Nullable final ITranslatableString explanation) { this.value = value; this.explanation = TranslatableStrings.nullToEmpty(explanation); } @Override public String toString() { final String explanationStr = !TranslatableStrings.isBlank(explanation) ? explanation.getDefaultValue() : null; return MoreObjects.toStringHelper(this) .omitNullValues() .addValue(value) .add("explanation", explanationStr) .toString(); } public ITranslatableString getExplanation() { return explanation != null ? explanation : TranslatableStrings.empty(); } public String getExplanationAsString() { return explanation != null ? explanation.getDefaultValue() : null; } @Nullable public T orElse(@Nullable final T other) { return value != null ? value : other; } public T orElseGet(@NonNull final Supplier<? extends T> other) { return value != null ? value : other.get(); } public T orElseThrow() { return orElseThrow(AdempiereException::new); } public T orElseThrow(@NonNull final AdMessageKey adMessageKey) { return orElseThrow(message -> new AdempiereException(adMessageKey).setParameter("detail", message)); } public T orElseThrow(@NonNull final Function<ITranslatableString, RuntimeException> exceptionFactory) { if (value != null) { return value; } else { throw exceptionFactory.apply(explanation); } } public T get() { return orElseThrow(); } public boolean isPresent() { return value != null; } public <U> ExplainedOptional<U> map(@NonNull final Function<? super T, ? extends U> mapper) { if (!isPresent()) { return emptyBecause(explanation); } else { final U newValue = mapper.apply(value); if (newValue == null) { return emptyBecause(explanation); } else { return of(newValue); } }
} public ExplainedOptional<T> ifPresent(@NonNull final Consumer<T> consumer) { if (isPresent()) { consumer.accept(value); } return this; } @SuppressWarnings("UnusedReturnValue") public ExplainedOptional<T> ifAbsent(@NonNull final Consumer<ITranslatableString> consumer) { if (!isPresent()) { consumer.accept(explanation); } return this; } /** * @see #resolve(Function, Function) */ public <R> Optional<R> mapIfAbsent(@NonNull final Function<ITranslatableString, R> mapper) { return isPresent() ? Optional.empty() : Optional.ofNullable(mapper.apply(getExplanation())); } /** * @see #mapIfAbsent(Function) */ public <R> R resolve( @NonNull final Function<T, R> mapPresent, @NonNull final Function<ITranslatableString, R> mapAbsent) { return isPresent() ? mapPresent.apply(value) : mapAbsent.apply(explanation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ExplainedOptional.java
1
请完成以下Java代码
public void setFailureHandler(AuthenticationFailureHandler failureHandler) { Assert.notNull(failureHandler, "failureHandler cannot be null"); this.failureHandler = failureHandler; } /** * @param switchUserAuthorityChanger to use to fine-tune the authorities granted to * subclasses (may be null if SwitchUserFilter should not fine-tune the authorities) */ public void setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger) { this.switchUserAuthorityChanger = switchUserAuthorityChanger; } /** * Sets the {@link UserDetailsChecker} that is called on the target user whenever the * user is switched. * @param userDetailsChecker the {@link UserDetailsChecker} that checks the status of * the user that is being switched to. Defaults to * {@link AccountStatusUserDetailsChecker}. */ public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) { this.userDetailsChecker = userDetailsChecker; } /** * Allows the parameter containing the username to be customized. * @param usernameParameter the parameter name. Defaults to {@code username} */ public void setUsernameParameter(String usernameParameter) { this.usernameParameter = usernameParameter; } /** * Allows the role of the switchAuthority to be customized. * @param switchAuthorityRole the role name. Defaults to * {@link #ROLE_PREVIOUS_ADMINISTRATOR} */ public void setSwitchAuthorityRole(String switchAuthorityRole) { Assert.notNull(switchAuthorityRole, "switchAuthorityRole cannot be null"); this.switchAuthorityRole = switchAuthorityRole; }
/** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * switch user success. The default is * {@link RequestAttributeSecurityContextRepository}. * @param securityContextRepository the {@link SecurityContextRepository} to use. * Cannot be null. * @since 5.7.7 */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } private static RequestMatcher createMatcher(String pattern) { return pathPattern(HttpMethod.POST, pattern); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilter.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Image URL. @param ImageURL URL of image */ public void setImageURL (String ImageURL) { set_Value (COLUMNNAME_ImageURL, ImageURL); } /** Get Image URL. @return URL of image */ public String getImageURL () { return (String)get_Value(COLUMNNAME_ImageURL); } public I_M_Product_Category getM_Product_Category() throws RuntimeException { return (I_M_Product_Category)MTable.get(getCtx(), I_M_Product_Category.Table_Name) .getPO(getM_Product_Category_ID(), get_TrxName()); } /** Set Product Category. @param M_Product_Category_ID Category of a Product */ public void setM_Product_Category_ID (int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, Integer.valueOf(M_Product_Category_ID)); } /** Get Product Category. @return Category of a Product */ public int getM_Product_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set 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 Training. @param S_Training_ID Repeated Training */ public void setS_Training_ID (int S_Training_ID) { if (S_Training_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID)); } /** Get Training. @return Repeated Training */ public int getS_Training_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_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_S_Training.java
1
请在Spring Boot框架中完成以下Java代码
public class SmsCouponController { @Autowired private SmsCouponService couponService; @ApiOperation("添加优惠券") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult add(@RequestBody SmsCouponParam couponParam) { int count = couponService.create(couponParam); if(count>0){ return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除优惠券") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = couponService.delete(id); if(count>0){ return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改优惠券") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody
public CommonResult update(@PathVariable Long id,@RequestBody SmsCouponParam couponParam) { int count = couponService.update(id,couponParam); if(count>0){ return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("根据优惠券名称和类型分页获取优惠券列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsCoupon>> list( @RequestParam(value = "name",required = false) String name, @RequestParam(value = "type",required = false) Integer type, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsCoupon> couponList = couponService.list(name,type,pageSize,pageNum); return CommonResult.success(CommonPage.restPage(couponList)); } @ApiOperation("获取单个优惠券的详细信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsCouponParam> getItem(@PathVariable Long id) { SmsCouponParam couponParam = couponService.getItem(id); return CommonResult.success(couponParam); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsCouponController.java
2
请在Spring Boot框架中完成以下Java代码
public void setProductService(ProductService productService) { this.productService = productService; } @RequestMapping({"/product/list", "/product"}) public String listProducts(Model model){ model.addAttribute("products", productService.listAll()); return "/product/list"; } @RequestMapping("/product/show/{id}") public String getProduct(@PathVariable String id, Model model){ model.addAttribute("product", productService.getById(Long.valueOf(id))); return "product/show"; } @RequestMapping("product/edit/{id}") public String edit(@PathVariable String id, Model model){ Product product = productService.getById(Long.valueOf(id)); ProductForm productForm = productToProductForm.convert(product); model.addAttribute("productForm", productForm); return "product/productform"; } @RequestMapping("/product/new") public String newProduct(Model model){ model.addAttribute("productForm", new ProductForm()); return "product/productform"; } @RequestMapping(value = "/product", method = RequestMethod.POST)
public String saveOrUpdateProduct(@Valid ProductForm productForm, BindingResult bindingResult){ if(bindingResult.hasErrors()){ return "product/productform"; } Product savedProduct = productService.saveOrUpdateProductForm(productForm); return "redirect:/product/show/" + savedProduct.getId(); } @RequestMapping("/product/delete/{id}") public String delete(@PathVariable String id){ productService.delete(Long.valueOf(id)); return "redirect:/product/list"; } }
repos\SpringBootVulExploit-master\repository\springboot-mysql-jdbc-rce\src\main\java\code\landgrey\controllers\ProductController.java
2
请在Spring Boot框架中完成以下Java代码
public void setMaxPageSize(int maxPageSize) { this.maxPageSize = maxPageSize; } public PageSerializationMode getSerializationMode() { return this.serializationMode; } public void setSerializationMode(PageSerializationMode serializationMode) { this.serializationMode = serializationMode; } } /** * Sort properties. */ public static class Sort {
/** * Sort parameter name. */ private String sortParameter = "sort"; public String getSortParameter() { return this.sortParameter; } public void setSortParameter(String sortParameter) { this.sortParameter = sortParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebProperties.java
2
请完成以下Java代码
protected void scheduleEventAsync(EventSubscriptionEntity eventSubscriptionEntity, Object payload) { JobEntity message = getJobEntityManager().create(); message.setJobType(JobEntity.JOB_TYPE_MESSAGE); message.setJobHandlerType(ProcessEventJobHandler.TYPE); message.setJobHandlerConfiguration(eventSubscriptionEntity.getId()); message.setTenantId(eventSubscriptionEntity.getTenantId()); // TODO: support payload // if(payload != null) { // message.setEventPayload(payload); // } getJobManager().scheduleAsyncJob(message); } protected List<SignalEventSubscriptionEntity> toSignalEventSubscriptionEntityList( List<EventSubscriptionEntity> result ) { List<SignalEventSubscriptionEntity> signalEventSubscriptionEntities = new ArrayList< SignalEventSubscriptionEntity >(result.size()); for (EventSubscriptionEntity eventSubscriptionEntity : result) { signalEventSubscriptionEntities.add((SignalEventSubscriptionEntity) eventSubscriptionEntity); } return signalEventSubscriptionEntities; } protected List<MessageEventSubscriptionEntity> toMessageEventSubscriptionEntityList( List<EventSubscriptionEntity> result ) { List<MessageEventSubscriptionEntity> messageEventSubscriptionEntities = new ArrayList<
MessageEventSubscriptionEntity >(result.size()); for (EventSubscriptionEntity eventSubscriptionEntity : result) { messageEventSubscriptionEntities.add((MessageEventSubscriptionEntity) eventSubscriptionEntity); } return messageEventSubscriptionEntities; } public EventSubscriptionDataManager getEventSubscriptionDataManager() { return eventSubscriptionDataManager; } public void setEventSubscriptionDataManager(EventSubscriptionDataManager eventSubscriptionDataManager) { this.eventSubscriptionDataManager = eventSubscriptionDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventSubscriptionEntityManagerImpl.java
1
请完成以下Java代码
public CardSequenceNumberRange1 getSeqNbRg() { return seqNbRg; } /** * Sets the value of the seqNbRg property. * * @param value * allowed object is * {@link CardSequenceNumberRange1 } * */ public void setSeqNbRg(CardSequenceNumberRange1 value) { this.seqNbRg = value; } /** * Gets the value of the txDtRg property. * * @return * possible object is * {@link DateOrDateTimePeriodChoice }
* */ public DateOrDateTimePeriodChoice getTxDtRg() { return txDtRg; } /** * Sets the value of the txDtRg property. * * @param value * allowed object is * {@link DateOrDateTimePeriodChoice } * */ public void setTxDtRg(DateOrDateTimePeriodChoice value) { this.txDtRg = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardAggregated1.java
1
请完成以下Java代码
public void parseUserTask(Element userTaskElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseCallActivity(Element callActivityElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity); } public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { addListeners(activity); } public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) { addListeners(activity); } public void parseMultiInstanceLoopCharacteristics(Element activityElement, Element multiInstanceLoopCharacteristicsElement, ActivityImpl activity) { addListeners(activity); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\parser\MetricsBpmnParseListener.java
1
请在Spring Boot框架中完成以下Java代码
public Payer ikNumber(String ikNumber) { this.ikNumber = ikNumber; return this; } /** * Get ikNumber * @return ikNumber **/ @Schema(example = "108534160", description = "") public String getIkNumber() { return ikNumber; } public void setIkNumber(String ikNumber) { this.ikNumber = ikNumber; } public Payer timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Payer payer = (Payer) o; return Objects.equals(this._id, payer._id) && Objects.equals(this.name, payer.name) && Objects.equals(this.type, payer.type) && Objects.equals(this.ikNumber, payer.ikNumber) && Objects.equals(this.timestamp, payer.timestamp); }
@Override public int hashCode() { return Objects.hash(_id, name, type, ikNumber, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Payer {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" ikNumber: ").append(toIndentedString(ikNumber)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).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-patient-api\src\main\java\io\swagger\client\model\Payer.java
2
请完成以下Java代码
public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); }
@Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setQty_Reported (final @Nullable BigDecimal Qty_Reported) { set_Value (COLUMNNAME_Qty_Reported, Qty_Reported); } @Override public BigDecimal getQty_Reported() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry_Detail.java
1
请在Spring Boot框架中完成以下Java代码
ManagementErrorPageCustomizer managementErrorPageCustomizer(WebProperties webProperties) { return new ManagementErrorPageCustomizer(webProperties); } @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) DispatcherServlet dispatcherServlet() { DispatcherServlet dispatcherServlet = new DispatcherServlet(); // Ensure the parent configuration does not leak down to us dispatcherServlet.setDetectAllHandlerAdapters(false); dispatcherServlet.setDetectAllHandlerExceptionResolvers(false); dispatcherServlet.setDetectAllHandlerMappings(false); dispatcherServlet.setDetectAllViewResolvers(false); return dispatcherServlet; } @Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) { return new DispatcherServletRegistrationBean(dispatcherServlet, "/"); } @Bean(name = DispatcherServlet.HANDLER_MAPPING_BEAN_NAME) CompositeHandlerMapping compositeHandlerMapping() { return new CompositeHandlerMapping(); } @Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME) CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) { return new CompositeHandlerAdapter(beanFactory); } @Bean(name = DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME) CompositeHandlerExceptionResolver compositeHandlerExceptionResolver() { return new CompositeHandlerExceptionResolver(); }
@Bean @ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class }) RequestContextFilter requestContextFilter() { return new OrderedRequestContextFilter(); } /** * {@link WebServerFactoryCustomizer} to add an {@link ErrorPage} so that the * {@link ManagementErrorEndpoint} can be used. */ static class ManagementErrorPageCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered { private final WebProperties properties; ManagementErrorPageCustomizer(WebProperties properties) { this.properties = properties; } @Override public void customize(ConfigurableServletWebServerFactory factory) { factory.addErrorPages(new ErrorPage(this.properties.getError().getPath())); } @Override public int getOrder() { return 10; // Run after ManagementWebServerFactoryCustomizer } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\WebMvcEndpointChildContextConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class TaskVariableUtils { public static boolean isCaseRelated(ValueFields valueField) { return isCaseRelated(valueField.getScopeId(), valueField.getScopeType()); } public static boolean isCaseRelated(TaskInfo task) { return isCaseRelated(task.getScopeId(), task.getScopeType()); } private static boolean isCaseRelated(String scopeId, String scopeType) { return scopeId != null && ScopeTypes.CMMN.equals(scopeType); } public static boolean isProcessRelated(TaskInfo task) { return task.getProcessInstanceId() != null; }
public static boolean doesVariableBelongToTask(ValueFields valueFields, TaskInfo taskInfo) { if (taskInfo.getProcessInstanceId() != null) { return taskInfo.getProcessInstanceId() .equals(valueFields.getProcessInstanceId()); } if (taskInfo.getScopeType() != null && valueFields.getScopeId() != null) { return taskInfo.getScopeType() .equals(valueFields.getScopeType()) && valueFields.getScopeId() .equals(taskInfo.getScopeId()); } return false; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\util\TaskVariableUtils.java
2
请完成以下Java代码
public class ReadOnePage { public static void main(String[] args) { // Create a new document object Document document = new Document(); // Load document content from the specified file document.loadFromFile("/Users/liuhaihua/tmp/WordDocument.docx"); // Create a fixed layout document object FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document); // Get the first page FixedLayoutPage page = layoutDoc.getPages().get(0); // Get the section where the page is located Section section = page.getSection(); // Get the first paragraph of the page Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph(); int startIndex = 0; if (paragraphStart != null) { // Get the index of the paragraph in the section startIndex = section.getBody().getChildObjects().indexOf(paragraphStart); } // Get the last paragraph of the page Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph(); int endIndex = 0; if (paragraphEnd != null) { // Get the index of the paragraph in the section
endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd); } // Create a new document object Document newdoc = new Document(); // Add a new section Section newSection = newdoc.addSection(); // Clone the properties of the original section to the new section section.cloneSectionPropertiesTo(newSection); // Copy the content of the original document's page to the new document for (int i = startIndex; i <=endIndex; i++) { newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone()); } // Save the new document to the specified file newdoc.saveToFile("/Users/liuhaihua/tmp/Content of One Page.docx", FileFormat.Docx); // Close and release the new document newdoc.close(); newdoc.dispose(); // Close and release the original document document.close(); document.dispose(); } }
repos\springboot-demo-master\spire-doc\src\main\java\com\et\spire\doc\ReadOnePage.java
1
请完成以下Java代码
public void addAttribute(ExtensionAttribute attribute) { if (attribute != null && isNotEmpty(attribute.getName())) { attributes.computeIfAbsent(attribute.getName(), key -> new ArrayList<>()); attributes.get(attribute.getName()).add(attribute); } } @Override public void setAttributes(Map<String, List<ExtensionAttribute>> attributes) { this.attributes = attributes; } public void setValues(BaseElement otherElement) { setId(otherElement.getId()); if (otherElement.getExtensionElements() != null && !otherElement.getExtensionElements().isEmpty()) { Map<String, List<ExtensionElement>> validExtensionElements = otherElement .getExtensionElements() .entrySet() .stream() .filter(e -> hasElements(e.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); extensionElements.putAll(validExtensionElements); }
if (otherElement.getAttributes() != null && !otherElement.getAttributes().isEmpty()) { Map<String, List<ExtensionAttribute>> validAttributes = otherElement .getAttributes() .entrySet() .stream() .filter(e -> hasElements(e.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); attributes.putAll(validAttributes); } } private boolean hasElements(List<?> listOfElements) { return listOfElements != null && !listOfElements.isEmpty(); } public abstract BaseElement clone(); }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BaseElement.java
1
请完成以下Java代码
public String toGlobalQRCodeString() { return HUQRCodeJsonConverter.toGlobalQRCodeJsonString(this); } public ScannedCode toScannedCode() {return ScannedCode.ofString(toGlobalQRCodeString());} public String toDisplayableQRCode() { return id.getDisplayableSuffix(); } public PrintableQRCode toPrintableQRCode() { return PrintableQRCode.builder() .topText(extractPrintableTopText(this)) .bottomText(extractPrintableBottomText(this)) .qrCode(HUQRCodeJsonConverter.toGlobalQRCode(this).getAsString()) .build(); } public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode) { return HUQRCodeJsonConverter.isTypeMatching(globalQRCode); } private static String extractPrintableTopText(final HUQRCode qrCode) { final StringBuilder result = new StringBuilder(); final HUQRCodeProductInfo product = qrCode.getProduct().orElse(null); if (product != null) { result.append(product.getCode()); result.append(" - "); result.append(product.getName()); } for (final HUQRCodeAttribute attribute : qrCode.getAttributes()) { final String displayValue = StringUtils.trimBlankToNull(attribute.getValueRendered()); if (displayValue != null) { if (result.length() > 0) { result.append(", "); } result.append(displayValue); } } return result.toString(); } @Override public Optional<BigDecimal> getWeightInKg() { return getAttribute(Weightables.ATTR_WeightNet)
.map(HUQRCodeAttribute::getValueAsBigDecimal) .filter(weight -> weight.signum() > 0); } @Override public Optional<LocalDate> getBestBeforeDate() { return getAttribute(AttributeConstants.ATTR_BestBeforeDate).map(HUQRCodeAttribute::getValueAsLocalDate); } @Override public Optional<LocalDate> getProductionDate() { return getAttribute(AttributeConstants.ProductionDate).map(HUQRCodeAttribute::getValueAsLocalDate); } @Override public Optional<String> getLotNumber() { return getAttribute(AttributeConstants.ATTR_LotNumber).map(HUQRCodeAttribute::getValue); } private Optional<HUQRCodeAttribute> getAttribute(@NonNull final AttributeCode attributeCode) { return attributes.stream().filter(attribute -> AttributeCode.equals(attribute.getCode(), attributeCode)).findFirst(); } private static String extractPrintableBottomText(final HUQRCode qrCode) { return qrCode.getPackingInfo().getHuUnitType().getShortDisplayName() + " ..." + qrCode.toDisplayableQRCode(); } public Optional<HUQRCodeProductInfo> getProduct() {return Optional.ofNullable(product);} @JsonIgnore public Optional<ProductId> getProductId() {return getProduct().map(HUQRCodeProductInfo::getId);} @JsonIgnore public ProductId getProductIdNotNull() {return getProductId().orElseThrow(() -> new AdempiereException("QR Code does not contain product information: " + this));} public HuPackingInstructionsId getPackingInstructionsId() {return getPackingInfo().getPackingInstructionsId();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCode.java
1
请在Spring Boot框架中完成以下Java代码
public static class CalculateSOCreditStatusRequest { BPartnerStats stat; BigDecimal additionalAmt; Timestamp date; boolean forceCheckCreditStatus; @Builder private CalculateSOCreditStatusRequest( @NonNull BPartnerStats stat, @NonNull Timestamp date, BigDecimal additionalAmt, Boolean forceCheckCreditStatus) { this.stat = stat; this.date = date; this.additionalAmt = CoalesceUtil.coalesce(additionalAmt, ZERO); this.forceCheckCreditStatus = CoalesceUtil.coalesce(forceCheckCreditStatus, false); } } /** * Calculate the future/simulated SOCreditStatus for the given {@link BPartnerStats} object at a certain date * <br> * The computation can be forced with the flag <code>forceCheckCreditStatus</code><br> * If the status is <code>CreditStop</code>, the status can be recomputed only if flag <code>forceCheckCreditStatus</code> is on Y * <br> * <b>No updating</b> * * @param stat * @param additionalAmt
* @param date * @return */ String calculateProjectedSOCreditStatus(CalculateSOCreditStatusRequest request); /** * Logic to tell whether or not the given grandTotal makes the credit stop for the given BPartner stats. * To be used in document preparing: invoices, payments, etc * * @param stat * @param grandTotal * @param date * @return */ boolean isCreditStopSales(BPartnerStats stat, BigDecimal grandTotal, Timestamp date); /** * Get Credit Watch % from the bpartner group of the given statistics * * @param stats * @return */ BigDecimal getCreditWatchRatio(BPartnerStats stats); void resetCreditStatusFromBPGroup(I_C_BPartner bpartner); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\IBPartnerStatsBL.java
2
请在Spring Boot框架中完成以下Java代码
public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() {
return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java
2
请完成以下Java代码
public InputStream getInputStream() throws IOException { return new FilterInputStream(super.getInputStream()) { @Override public void close() throws IOException { closeThenDeleteFile(this.in); } }; } private void closeThenDeleteFile(Closeable closeable) throws IOException { try { closeable.close(); } finally { deleteFile(); } } private void deleteFile() { try { Files.delete(getFile().toPath()); }
catch (IOException ex) { TemporaryFileSystemResource.this.logger .warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex); } } @Override public boolean isFile() { // Prevent zero-copy so we can delete the file on close return false; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\HeapDumpWebEndpoint.java
1
请完成以下Java代码
protected JsScriptExecutionTask doInvokeFunction(UUID scriptId, Object[] args) { return new JsScriptExecutionTask(doInvokeFunction(scriptId, scriptInfoMap.get(scriptId), args)); } @Override protected ListenableFuture<UUID> doEvalScript(TenantId tenantId, ScriptType scriptType, String scriptBody, UUID scriptId, String[] argNames) { String scriptHash = hash(tenantId, scriptBody); String functionName = constructFunctionName(scriptId, scriptHash); String jsScript = generateJsScript(scriptType, functionName, scriptBody, argNames); return doEval(scriptId, new JsScriptInfo(scriptHash, functionName), jsScript); } @Override protected void doRelease(UUID scriptId) throws Exception { doRelease(scriptId, scriptInfoMap.remove(scriptId)); } @Override public String validate(TenantId tenantId, String scriptBody) { String errorMessage = super.validate(tenantId, scriptBody); if (errorMessage == null) { return JsValidator.validate(scriptBody); } return errorMessage; } protected abstract ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo jsInfo, String scriptBody); protected abstract ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo jsInfo, Object[] args); protected abstract void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws Exception; private String generateJsScript(ScriptType scriptType, String functionName, String scriptBody, String... argNames) { if (scriptType == ScriptType.RULE_NODE_SCRIPT) { return RuleNodeScriptFactory.generateRuleNodeScript(functionName, scriptBody, argNames); }
throw new RuntimeException("No script factory implemented for scriptType: " + scriptType); } protected String constructFunctionName(UUID scriptId, String scriptHash) { return "invokeInternal_" + scriptId.toString().replace('-', '_'); } protected String hash(TenantId tenantId, String scriptBody) { return Hashing.murmur3_128().newHasher() .putLong(tenantId.getId().getMostSignificantBits()) .putLong(tenantId.getId().getLeastSignificantBits()) .putUnencodedChars(scriptBody) .hash().toString(); } @Override protected StatsType getStatsType() { return StatsType.JS_INVOKE; } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\AbstractJsInvokeService.java
1
请完成以下Java代码
public void setPA_ReportLine_ID (int PA_ReportLine_ID) { if (PA_ReportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID)); } /** Get Report Line. @return Report Line */ public int getPA_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Report Source. @param PA_ReportSource_ID Restriction of what will be shown in Report Line */ public void setPA_ReportSource_ID (int PA_ReportSource_ID) { if (PA_ReportSource_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportSource_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportSource_ID, Integer.valueOf(PA_ReportSource_ID)); } /** Get Report Source. @return Restriction of what will be shown in Report Line */ public int getPA_ReportSource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportSource_ID); if (ii == null) return 0; return ii.intValue(); } /** Set User Element 1. @param UserElement1_ID User defined accounting Element */ public void setUserElement1_ID (int UserElement1_ID) { if (UserElement1_ID < 1) set_Value (COLUMNNAME_UserElement1_ID, null); else set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID)); } /** Get User Element 1. @return User defined accounting Element */
public int getUserElement1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID); if (ii == null) return 0; return ii.intValue(); } /** Set User Element 2. @param UserElement2_ID User defined accounting Element */ public void setUserElement2_ID (int UserElement2_ID) { if (UserElement2_ID < 1) set_Value (COLUMNNAME_UserElement2_ID, null); else set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID)); } /** Get User Element 2. @return User defined accounting Element */ public int getUserElement2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportSource.java
1
请完成以下Java代码
public @NonNull Iterator<Packageable> iterator() {return list.iterator();} public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds() { return list.stream().map(Packageable::getShipmentScheduleId).sorted().collect(ImmutableSet.toImmutableSet()); } public Optional<BPartnerId> getSingleCustomerId() {return getSingleValue(Packageable::getCustomerId);} public <T> Optional<T> getSingleValue(@NonNull final Function<Packageable, T> mapper) { if (list.isEmpty()) { return Optional.empty(); } final ImmutableList<T> values = list.stream() .map(mapper) .filter(Objects::nonNull) .distinct() .collect(ImmutableList.toImmutableList()); if (values.isEmpty()) { return Optional.empty();
} else if (values.size() == 1) { return Optional.of(values.get(0)); } else { //throw new AdempiereException("More than one value were extracted (" + values + ") from " + list); return Optional.empty(); } } public Stream<PackageableList> groupBy(Function<Packageable, ?> classifier) { return list.stream() .collect(Collectors.groupingBy(classifier, LinkedHashMap::new, PackageableList.collect())) .values() .stream(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\PackageableList.java
1
请完成以下Java代码
public static HuPackingInstructionsItemId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(final HuPackingInstructionsItemId id) { return id != null ? id.getRepoId() : -1; } public static final HuPackingInstructionsItemId TEMPLATE_MATERIAL_ITEM = new HuPackingInstructionsItemId(540004); private static final HuPackingInstructionsItemId TEMPLATE_PACKING_ITEM = new HuPackingInstructionsItemId(100); public static final HuPackingInstructionsItemId VIRTUAL = new HuPackingInstructionsItemId(101); int repoId; private HuPackingInstructionsItemId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Item_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(final HuPackingInstructionsItemId o1, final HuPackingInstructionsItemId o2) { return Objects.equals(o1, o2); } public boolean isTemplate() { return isTemplateRepoId(repoId); }
public static boolean isTemplateRepoId(final int repoId) { return repoId == TEMPLATE_MATERIAL_ITEM.repoId || repoId == TEMPLATE_PACKING_ITEM.repoId; } public boolean isVirtual() { return isVirtualRepoId(repoId); } public static boolean isVirtualRepoId(final int repoId) { return repoId == VIRTUAL.repoId; } public boolean isRealPackingInstructions() { return isRealPackingInstructionsRepoId(repoId); } public static boolean isRealPackingInstructionsRepoId(final int repoId) { return repoId > 0 && !isTemplateRepoId(repoId) && !isVirtualRepoId(repoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsItemId.java
1
请完成以下Java代码
public long getCreatedTime() { return super.getCreatedTime(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ComponentDescriptor that = (ComponentDescriptor) o; if (type != that.type) return false; if (scope != that.scope) return false; if (!Objects.equals(name, that.name)) return false; if (!Objects.equals(actions, that.actions)) return false; if (!Objects.equals(configurationDescriptor, that.configurationDescriptor)) return false; if (configurationVersion != that.configurationVersion) return false; if (clusteringMode != that.clusteringMode) return false; if (hasQueueName != that.isHasQueueName()) return false;
return Objects.equals(clazz, that.clazz); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (scope != null ? scope.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (clazz != null ? clazz.hashCode() : 0); result = 31 * result + (actions != null ? actions.hashCode() : 0); result = 31 * result + (clusteringMode != null ? clusteringMode.hashCode() : 0); result = 31 * result + (hasQueueName ? 1 : 0); return result; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\plugin\ComponentDescriptor.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Indication. @param M_Indication_ID Indication */ @Override public void setM_Indication_ID (int M_Indication_ID) { if (M_Indication_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Indication_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Indication_ID, Integer.valueOf(M_Indication_ID)); } /** Get Indication. @return Indication */ @Override public int getM_Indication_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_M_Indication_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_Indication.java
1
请完成以下Java代码
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Role name. @param RoleName Role name */ @Override public void setRoleName (java.lang.String RoleName) { set_Value (COLUMNNAME_RoleName, RoleName); } /** Get Role name. @return Role name */ @Override public java.lang.String getRoleName ()
{ return (java.lang.String)get_Value(COLUMNNAME_RoleName); } /** Set UserValue. @param UserValue UserValue */ @Override public void setUserValue (java.lang.String UserValue) { set_Value (COLUMNNAME_UserValue, UserValue); } /** Get UserValue. @return UserValue */ @Override public java.lang.String getUserValue () { return (java.lang.String)get_Value(COLUMNNAME_UserValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_User.java
1
请完成以下Java代码
public class PermissionCheck { /** the permission to check for */ protected Permission permission; protected int perms; /** the type of the resource to check permissions for */ protected Resource resource; protected int resourceType; /** the id of the resource to check permission for */ protected String resourceId; /** query parameter for resource Id. Is injected as RAW parameter into the query */ protected String resourceIdQueryParam; protected Long authorizationNotFoundReturnValue = null; public PermissionCheck() { } public Permission getPermission() { return permission; } public void setPermission(Permission permission) { this.permission = permission; if (permission != null) { perms = permission.getValue(); } } public int getPerms() { return perms; } public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; if (resource != null) { resourceType = resource.resourceType();
} } public int getResourceType() { return resourceType; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getResourceIdQueryParam() { return resourceIdQueryParam; } public void setResourceIdQueryParam(String resourceIdQueryParam) { this.resourceIdQueryParam = resourceIdQueryParam; } public Long getAuthorizationNotFoundReturnValue() { return authorizationNotFoundReturnValue; } public void setAuthorizationNotFoundReturnValue(Long authorizationNotFoundReturnValue) { this.authorizationNotFoundReturnValue = authorizationNotFoundReturnValue; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\PermissionCheck.java
1
请完成以下Java代码
public boolean hasMultiplyRate( @NonNull final CurrencyId fromCurrencyId, @NonNull final CurrencyId toCurrencyId) { return getMultiplyRateOrNull(fromCurrencyId, toCurrencyId) != null; } @Nullable private BigDecimal getMultiplyRateOrNull( @NonNull final CurrencyId fromCurrencyId, @NonNull final CurrencyId toCurrencyId) { final FixedConversionRate rate = rates.get(FixedConversionRateKey.builder() .fromCurrencyId(fromCurrencyId) .toCurrencyId(toCurrencyId) .build());
return rate != null ? rate.getMultiplyRate() : null; } @Value @Builder private static class FixedConversionRateKey { @NonNull CurrencyId fromCurrencyId; @NonNull CurrencyId toCurrencyId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\FixedConversionRateMap.java
1
请完成以下Java代码
public BPartnerContact newContact(@NonNull final IdentifierString contactIdentifier) { final BPartnerContact contact; final BPartnerContactBuilder contactBuilder = BPartnerContact.builder(); switch (contactIdentifier.getType()) { case METASFRESH_ID: if (bpartnerId != null) { final BPartnerContactId bpartnerContactId = BPartnerContactId.of(bpartnerId, contactIdentifier.asMetasfreshId(UserId::ofRepoId)); contact = contactBuilder.id(bpartnerContactId).build(); id2Contact.put(bpartnerContactId, contact); } else { contact = contactBuilder.build(); } break; case EXTERNAL_ID: contact = contactBuilder.externalId(contactIdentifier.asExternalId()).build(); externalId2Contact.put(contactIdentifier.asExternalId(), contact); break; case VALUE: contact = contactBuilder.value(contactIdentifier.asValue()).build(); value2Contact.put(contactIdentifier.asValue(), contact); break; default: throw new InvalidIdentifierException(contactIdentifier); } bpartnerComposite .getContacts() .add(contact); return contact; } public Collection<BPartnerContact> getUnusedContacts() { return id2UnusedContact.values();
} public void resetDefaultContactFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setDefaultContact(false); } } public void resetShipToDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setShipToDefault(false); } } public void resetPurchaseDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setPurchaseDefault(false); } } public void resetSalesDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setSalesDefault(false); } } public void resetBillToDefaultFlags() { for (final BPartnerContact bpartnerContact : getUnusedContacts()) { bpartnerContact.getContactType().setBillToDefault(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\jsonpersister\ShortTermContactIndex.java
1
请完成以下Java代码
public void setCRM_Occupation_Parent_ID (final int CRM_Occupation_Parent_ID) { if (CRM_Occupation_Parent_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_Parent_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_Parent_ID, CRM_Occupation_Parent_ID); } @Override public int getCRM_Occupation_Parent_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_Parent_ID); } /** * JobType AD_Reference_ID=541383 * Reference name: JobType */ public static final int JOBTYPE_AD_Reference_ID=541383; /** Job = B */ public static final String JOBTYPE_Job = "B"; /** Specialization = F */ public static final String JOBTYPE_Specialization = "F"; /** AdditionalSpecialization = Z */ public static final String JOBTYPE_AdditionalSpecialization = "Z"; @Override public void setJobType (final @Nullable java.lang.String JobType) { set_Value (COLUMNNAME_JobType, JobType); } @Override public java.lang.String getJobType() { return get_ValueAsString(COLUMNNAME_JobType); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
@Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CRM_Occupation.java
1
请完成以下Java代码
public void destroy() {} @Override public void deleteTopic(String topic) {} }); templateBuilder.requestTemplate(producerTemplate); templateBuilder.responseTemplate(consumerTemplate); templateBuilder.maxPendingRequests(transportApiSettings.getMaxPendingRequests()); templateBuilder.maxRequestTimeout(transportApiSettings.getMaxRequestsTimeout()); templateBuilder.pollInterval(transportApiSettings.getResponsePollInterval()); return templateBuilder.build(); } @Override public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> createRuleEngineMsgProducer() { return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(transportApiSettings.getRequestsTopic())); } @Override public TbQueueProducer<TbProtoQueueMsg<ToCoreMsg>> createTbCoreMsgProducer() { return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getTopic())); }
@Override public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> createTbCoreNotificationsMsgProducer() { return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getTopic())); } @Override public TbQueueConsumer<TbProtoQueueMsg<ToTransportMsg>> createTransportNotificationsConsumer() { return new InMemoryTbQueueConsumer<>(storage, topicService.buildTopicName(transportNotificationSettings.getNotificationsTopic() + "." + serviceInfoProvider.getServiceId())); } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToUsageStatsServiceMsg>> createToUsageStatsServiceMsgProducer() { return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getUsageStatsTopic())); } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToHousekeeperServiceMsg>> createHousekeeperMsgProducer() { return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getHousekeeperTopic())); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\InMemoryTbTransportQueueFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class PPOrderCandidateDeletedEventHandler extends PPOrderCandidateEventHandler implements MaterialEventHandler<PPOrderCandidateDeletedEvent> { public PPOrderCandidateDeletedEventHandler( @NonNull final CandidateChangeService candidateChangeService, @NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval) { super(candidateChangeService, candidateRepositoryRetrieval); } @Override public Collection<Class<? extends PPOrderCandidateDeletedEvent>> getHandledEventType() { return ImmutableList.of(PPOrderCandidateDeletedEvent.class); } @Override public void handleEvent(@NonNull final PPOrderCandidateDeletedEvent event) { final CandidatesQuery preExistingHeaderSupplyQuery = createPreExistingHeaderCandidateQuery(event); final Candidate existingCandidateOrNull = candidateRepositoryRetrieval.retrieveLatestMatchOrNull(preExistingHeaderSupplyQuery); if (existingCandidateOrNull != null)
{ deleteLineCandidates(event, existingCandidateOrNull); candidateChangeService.onCandidateDelete(existingCandidateOrNull); } } @NonNull private CandidatesQuery createPreExistingHeaderCandidateQuery(@NonNull final PPOrderCandidateDeletedEvent ppOrderCandidateDeletedEvent) { final PPOrderCandidate ppOrderCandidate = ppOrderCandidateDeletedEvent.getPpOrderCandidate(); return CandidatesQuery .builder() .productionDetailsQuery(ProductionDetailsQuery.builder() .ppOrderCandidateId(ppOrderCandidate.getPpOrderCandidateId()) .build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ppordercandidate\PPOrderCandidateDeletedEventHandler.java
2
请完成以下Java代码
public static TbMathArgumentValue constant(TbMathArgument arg) { return fromString(arg.getKey()); } private static TbMathArgumentValue defaultOrThrow(Double defaultValue, String error) { if (defaultValue != null) { return new TbMathArgumentValue(defaultValue); } throw new RuntimeException(error); } public static TbMathArgumentValue fromMessageBody(TbMathArgument arg, String argKey, Optional<ObjectNode> jsonNodeOpt) { Double defaultValue = arg.getDefaultValue(); if (jsonNodeOpt.isEmpty()) { return defaultOrThrow(defaultValue, "Message body is empty!"); } var json = jsonNodeOpt.get(); if (!json.has(argKey)) { return defaultOrThrow(defaultValue, "Message body has no '" + argKey + "'!"); } JsonNode valueNode = json.get(argKey); if (valueNode.isNull()) { return defaultOrThrow(defaultValue, "Message body has null '" + argKey + "'!"); } double value; if (valueNode.isNumber()) { value = valueNode.doubleValue(); } else if (valueNode.isTextual()) { var valueNodeText = valueNode.asText(); if (StringUtils.isNotBlank(valueNodeText)) { try { value = Double.parseDouble(valueNode.asText()); } catch (NumberFormatException ne) { throw new RuntimeException("Can't convert value '" + valueNode.asText() + "' to double!"); } } else {
return defaultOrThrow(defaultValue, "Message value is empty for '" + argKey + "'!"); } } else { throw new RuntimeException("Can't convert value '" + valueNode.toString() + "' to double!"); } return new TbMathArgumentValue(value); } public static TbMathArgumentValue fromMessageMetadata(TbMathArgument arg, String argKey, TbMsgMetaData metaData) { Double defaultValue = arg.getDefaultValue(); if (metaData == null) { return defaultOrThrow(defaultValue, "Message metadata is empty!"); } var value = metaData.getValue(argKey); if (StringUtils.isEmpty(value)) { return defaultOrThrow(defaultValue, "Message metadata has no '" + argKey + "'!"); } return fromString(value); } public static TbMathArgumentValue fromLong(long value) { return new TbMathArgumentValue(value); } public static TbMathArgumentValue fromDouble(double value) { return new TbMathArgumentValue(value); } public static TbMathArgumentValue fromString(String value) { try { return new TbMathArgumentValue(Double.parseDouble(value)); } catch (NumberFormatException ne) { throw new RuntimeException("Can't convert value '" + value + "' to double!"); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\math\TbMathArgumentValue.java
1
请完成以下Java代码
public class Customer extends Person { private final String loyaltyCardId; public Customer(String firstName, String lastName, int age, String loyaltyCardId) { this(firstName, null, lastName, age, loyaltyCardId); } public Customer(String firstName, String middleName, String lastName, int age, String loyaltyCardId) { super(firstName, middleName, lastName, age); this.loyaltyCardId = loyaltyCardId; } public String getLoyaltyCardId() { return loyaltyCardId; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Customer customer = (Customer) o; return Objects.equals(loyaltyCardId, customer.loyaltyCardId); } @Override public int hashCode() { return Objects.hash(super.hashCode(), loyaltyCardId); } }
repos\tutorials-master\core-java-modules\core-java-lang-4\src\main\java\com\baeldung\constructorchaining\Customer.java
1
请在Spring Boot框架中完成以下Java代码
private void changeProjectLine(final ChangeProjectLineRequest request, final ProjectLine projectLine) { if (request.getCommittedQtyToAdd() != null) { projectLine.addCommittedQty(request.getCommittedQtyToAdd()); } } public void linkToOrderLine( @NonNull final ProjectAndLineId projectLineId, @NonNull final OrderAndLineId orderLineId) { projectLineRepository.linkToOrderLine(projectLineId, orderLineId); } public boolean isClosed(@NonNull final ProjectId projectId) { final I_C_Project projectRecord = getById(projectId); return projectRecord.isProcessed(); } public void closeProject(@NonNull final ProjectId projectId) { final I_C_Project projectRecord = getById(projectId); if (projectRecord.isProcessed()) { throw new AdempiereException("Project already closed: " + projectId); } projectStatusListeners.onBeforeClose(projectRecord);
projectLineRepository.markLinesAsProcessed(projectId); projectRecord.setProcessed(true); InterfaceWrapperHelper.saveRecord(projectRecord); projectStatusListeners.onAfterClose(projectRecord); } public void uncloseProject(@NonNull final ProjectId projectId) { final I_C_Project projectRecord = getById(projectId); if (!projectRecord.isProcessed()) { throw new AdempiereException("Project not closed: " + projectId); } projectStatusListeners.onBeforeUnClose(projectRecord); projectLineRepository.markLinesAsNotProcessed(projectId); projectRecord.setProcessed(false); InterfaceWrapperHelper.saveRecord(projectRecord); projectStatusListeners.onAfterUnClose(projectRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\service\ProjectService.java
2
请完成以下Java代码
private OrderResponsePackage createOrderResponsePackage(final JpaOrderPackage jpaOrderPackage) { return OrderResponsePackage.builder() .id(Id.of(jpaOrderPackage.getDocumentNo())) .orderType(jpaOrderPackage.getOrderType()) .orderIdentification(jpaOrderPackage.getOrderIdentification()) .supportId(SupportIDType.of(jpaOrderPackage.getSupportId())) .packingMaterialId(jpaOrderPackage.getPackingMaterialId()) .items(jpaOrderPackage.getItems().stream() .map(this::createOrderResponsePackageItem) .collect(ImmutableList.toImmutableList())) .build(); } private OrderResponsePackageItem createOrderResponsePackageItem(final JpaOrderPackageItem jpaOrderPackageItem) { return OrderResponsePackageItem.builder() .requestId(OrderCreateRequestPackageItemId.of(jpaOrderPackageItem.getUuid())) .pzn(PZN.of(jpaOrderPackageItem.getPzn())) .qty(Quantity.of(jpaOrderPackageItem.getQty())) .deliverySpecifications(jpaOrderPackageItem.getDeliverySpecifications()) .build(); } public OrderStatusResponse getOrderStatus(@NonNull final Id orderId, @NonNull final BPartnerId bpartnerId) { final JpaOrder jpaOrder = getJpaOrder(orderId, bpartnerId); return createOrderStatusResponse(jpaOrder); } private JpaOrder getJpaOrder(@NonNull final Id orderId, @NonNull final BPartnerId bpartnerId)
{ final JpaOrder jpaOrder = jpaOrdersRepo.findByDocumentNoAndMfBpartnerId(orderId.getValueAsString(), bpartnerId.getBpartnerId()); if (jpaOrder == null) { throw new RuntimeException("No order found for id='" + orderId + "' and bpartnerId='" + bpartnerId + "'"); } return jpaOrder; } private OrderStatusResponse createOrderStatusResponse(final JpaOrder jpaOrder) { return OrderStatusResponse.builder() .orderId(Id.of(jpaOrder.getDocumentNo())) .supportId(SupportIDType.of(jpaOrder.getSupportId())) .orderStatus(jpaOrder.getOrderStatus()) .orderPackages(jpaOrder.getOrderPackages().stream() .map(this::createOrderResponsePackage) .collect(ImmutableList.toImmutableList())) .build(); } public List<OrderResponse> getOrders() { return jpaOrdersRepo.findAll() .stream() .map(this::createOrderResponse) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\order\OrderService.java
1
请完成以下Java代码
private boolean openSOWindow(final int bPartnerId, final int locationShipId, final int locationBillId, final int contactId, final int billContactId) { final AdWindowId SALES_ORDER_WINDOW_ID = AdWindowId.ofRepoId(143); final AWindow soFrame = new AWindow(); final MQuery query = new MQuery(Table_Name); query.addRestriction(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID + "=" + bPartnerId); final boolean success = soFrame .initWindow(SALES_ORDER_WINDOW_ID, query); if (!success) { return false; } soFrame.pack(); AEnv.addToWindowManager(soFrame); final GridTab tab = soFrame.getAPanel().getCurrentTab(); tab.dataNew(DataNewCopyMode.NoCopy); tab.setValue(I_C_Order.COLUMNNAME_C_BPartner_ID, bPartnerId);
tab.setValue(I_C_Order.COLUMNNAME_C_BPartner_Location_ID, locationShipId); tab.setValue(I_C_Order.COLUMNNAME_Bill_Location_ID, locationBillId); if (contactId > 0) { tab.setValue(I_C_Order.COLUMNNAME_AD_User_ID, contactId); } if (billContactId > 0) { tab.setValue(I_C_Order.COLUMNNAME_Bill_User_ID, billContactId); } AEnv.showCenterScreen(soFrame); return success; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\BPartnerCockpit.java
1
请在Spring Boot框架中完成以下Java代码
public class UsersService { @Autowired private UsersRepository usersRepository; @Autowired private JmsSender jmsSender; public UserRecord getUserById(String id) { return usersRepository.findById(id) .orElseThrow(() -> new UnknownUserException(id)); } @Transactional public void deleteUserById(String id) { var user = usersRepository.findById(id) .orElseThrow(() -> new UnknownUserException(id)); usersRepository.delete(user); jmsSender.sendDeleteUserMessage(id); }
@Transactional public UserRecord updateUser(String id, Optional<String> newName) { var user = usersRepository.findById(id) .orElseThrow(() -> new UnknownUserException(id)); newName.ifPresent(user::setName); return user; } public UserRecord createUser(String name) { var user = new UserRecord(UUID.randomUUID() .toString(), name); usersRepository.save(user); return user; } }
repos\tutorials-master\lightrun\lightrun-users-service\src\main\java\com\baeldung\usersservice\service\UsersService.java
2
请完成以下Java代码
public static Book unmarshalDates(InputStream inputFile) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Book.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); return (Book) jaxbUnmarshaller.unmarshal(inputFile); } public static BookDateAdapter unmarshalDatesUsingCustomXmlAdapter(InputStream inputFile) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(BookDateAdapter.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); return (BookDateAdapter) jaxbUnmarshaller.unmarshal(inputFile); } public static BookLocalDateTimeAdapter unmarshalDatesUsingJava8(InputStream inputFile) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(BookLocalDateTimeAdapter.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); return (BookLocalDateTimeAdapter) jaxbUnmarshaller.unmarshal(inputFile);
} public static InputStream getInputStream(String file) { ClassLoader classLoader = JaxbDateUnmarshalling.class.getClassLoader(); return classLoader.getResourceAsStream(file); } public static void main(String[] args) throws JAXBException { Book book = unmarshalDates(getInputStream(DEFAULT_DATE_UNMARSHALLING_FILE)); BookDateAdapter bookDateAdapter = unmarshalDatesUsingCustomXmlAdapter(getInputStream(CUSTOM_DATE_UNMARSHALLING_FILE)); BookLocalDateTimeAdapter bookLocalDateTimeAdapter = unmarshalDatesUsingJava8(getInputStream(CUSTOM_DATE_UNMARSHALLING_FILE)); System.out.println(book); System.out.println(bookDateAdapter); System.out.println(bookLocalDateTimeAdapter); } }
repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\dateunmarshalling\JaxbDateUnmarshalling.java
1
请在Spring Boot框架中完成以下Java代码
public void configure() throws Exception { errorHandler(defaultErrorHandler()); onException(Exception.class) .to(direct(MF_ERROR_ROUTE_ID)); from(direct(PRINTING_CLIENT_ROUTE_ID)) .routeId(PRINTING_CLIENT_ROUTE_ID) .streamCache("true") .process(this::prepareContext) .process(this::getPrintingData) .to(direct(MF_GET_PRINTING_DATA_ROUTE_ID)) .process(this::setPrintingResult) .to(direct(MF_SET_PRINTING_RESULT_ROUTE_ID)) .end(); } private void prepareContext(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final PrintingClientContext context = PrintingClientContext.builder() .printingQueueId(request.getParameters().get(ExternalSystemConstants.PARAM_PRINTING_QUEUE_ID)) .targetDirectory(request.getParameters().get(ExternalSystemConstants.PARAM_TARGET_DIRECTORY)) .build(); exchange.setProperty(PrintingClientConstants.PRINTING_CLIENT_CONTEXT, context); } private void getPrintingData(@NonNull final Exchange exchange){ final PrintingClientContext context = exchange.getProperty(PrintingClientConstants.PRINTING_CLIENT_CONTEXT, PrintingClientContext.class); exchange.getIn().removeHeaders("*"); exchange.getIn().setHeader(HEADER_PRINTING_QUEUE_ID, context.getPrintingQueueId()); exchange.getIn().setBody(null); }
private void setPrintingResult(@NonNull final Exchange exchange) { final Object printingDataCandidate = exchange.getIn().getBody(); if (!(printingDataCandidate instanceof JsonPrintingDataResponse)) { throw new RuntimeCamelException("API Request " + MF_PRINT_V2_BASE + "getPrintingData/" + "{" + HEADER_PRINTING_QUEUE_ID + "}" + "expected result to be instanceof JsonPrintingDataResponse." + " However, it is " + (printingDataCandidate == null ? "null" : printingDataCandidate.getClass().getName())); } final JsonPrintingDataResponse request = (JsonPrintingDataResponse) printingDataCandidate; final PrintingClientContext context = exchange.getProperty(PrintingClientConstants.PRINTING_CLIENT_CONTEXT, PrintingClientContext.class); try { printingClientPDFFileStorer.storeInFileSystem(request, context.getTargetDirectory()); } catch (final PrintingException e) { final JsonPrintingResultRequest response = JsonPrintingResultRequest.builder() .processed(false) .errorMsg("ERROR: " + e.getMessage()) .build(); exchange.getIn().setBody(response); return; } final JsonPrintingResultRequest response = JsonPrintingResultRequest.builder() .processed(true) .build(); exchange.getIn().setBody(response); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-printingclient\src\main\java\de\metas\camel\externalsystems\PrintingClientCamelRoute.java
2
请在Spring Boot框架中完成以下Java代码
public class CommissionFact { /** This fact's timestamp; note that we need chronology, but don't care for a particular timezone. */ Instant timestamp; CommissionState state; CommissionPoints points; @JsonCreator @Builder private CommissionFact( @JsonProperty("timestamp") @NonNull final Instant timestamp, @JsonProperty("state") @NonNull final CommissionState state, @JsonProperty("points") @NonNull final CommissionPoints points) { this.timestamp = timestamp; this.state = state; this.points = points; }
@NonNull public static Optional<CommissionFact> createFact( @NonNull final Instant timestamp, @NonNull final CommissionState state, @NonNull final CommissionPoints currentCommissionPoints, @NonNull final CommissionPoints previousCommissionPoints) { final CommissionPoints points = currentCommissionPoints.subtract(previousCommissionPoints); if (points.isZero()) { return Optional.empty(); // a zero-points fact would not change anything, so don't bother creating it } final CommissionFact fact = CommissionFact.builder() .state(state) .points(points) .timestamp(timestamp) .build(); return Optional.of(fact); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\CommissionFact.java
2
请完成以下Java代码
public class ProcessCreatedListenerDelegate implements ActivitiEventListener { private List<ProcessRuntimeEventListener<ProcessCreatedEvent>> listeners; private ToAPIProcessCreatedEventConverter entityCreatedEventConverter; public ProcessCreatedListenerDelegate( List<ProcessRuntimeEventListener<ProcessCreatedEvent>> listeners, ToAPIProcessCreatedEventConverter entityCreatedEventConverter ) { this.listeners = listeners; this.entityCreatedEventConverter = entityCreatedEventConverter; } @Override public void onEvent(ActivitiEvent event) {
if (event instanceof ActivitiEntityEvent) { entityCreatedEventConverter .from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (ProcessRuntimeEventListener<ProcessCreatedEvent> listener : listeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ProcessCreatedListenerDelegate.java
1
请完成以下Java代码
private final void fireDocValidate(final Object document, final int timing) { final Object model; if (document instanceof IDocument) { model = ((IDocument)document).getDocumentModel(); } else { model = document; } ModelValidationEngine.get().fireDocValidate(model, timing); } @Override public void onBeforePost(final Object document) {
fireDocValidate(document, ModelValidator.TIMING_BEFORE_POST); } @Override public void onAfterPost(final Object document) { fireDocValidate(document, ModelValidator.TIMING_AFTER_POST); } // @Override // public void onAfterUnpost(final Object document) // { // fireDocValidate(document, ModelValidator.TIMING_AFTER_UNPOST); // } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\FactAcctListenersService.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Rabatt %. @param Discount Abschlag in Prozent */ @Override public void setDiscount (java.math.BigDecimal Discount) { set_Value (COLUMNNAME_Discount, Discount); } /** Get Rabatt %. @return Abschlag in Prozent */ @Override public java.math.BigDecimal getDiscount () {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Discount); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Aufschlag auf Standardpreis. @param Std_AddAmt Amount added to a price as a surcharge */ @Override public void setStd_AddAmt (java.math.BigDecimal Std_AddAmt) { set_Value (COLUMNNAME_Std_AddAmt, Std_AddAmt); } /** Get Aufschlag auf Standardpreis. @return Amount added to a price as a surcharge */ @Override public java.math.BigDecimal getStd_AddAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_AddAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PriceLimit_Restriction.java
1
请完成以下Java代码
public class TransactionDeletedEvent extends AbstractTransactionEvent { public static final String TYPE = "TransactionDeletedEvent"; @JsonCreator @Builder public TransactionDeletedEvent( @JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor, @JsonProperty("materialDescriptor") final MaterialDescriptor materialDescriptor, @JsonProperty("minMaxDescriptor") @Nullable final MinMaxDescriptor minMaxDescriptor, @JsonProperty("receiptScheduleIdsQtys") @Singular final Map<Integer, BigDecimal> receiptScheduleIdsQtys, @JsonProperty("receiptId") final InOutAndLineId receiptId, @JsonProperty("shipmentId") final InOutAndLineId shipmentId, @JsonProperty("ppOrderId") final int ppOrderId, @JsonProperty("ppOrderLineId") final int ppOrderLineId, @JsonProperty("ddOrderId") final int ddOrderId, @JsonProperty("ddOrderLineId") final int ddOrderLineId, @JsonProperty("inventoryId") final int inventoryId, @JsonProperty("inventoryLineId") final int inventoryLineId, @JsonProperty("transactionId") final int transactionId, @JsonProperty("directMovementWarehouse") final boolean directMovementWarehouse, @JsonProperty("huOnHandQtyChangeDescriptor") final Collection<HUDescriptor> huOnHandQtyChangeDescriptors) { super(eventDescriptor, materialDescriptor, minMaxDescriptor, receiptScheduleIdsQtys, receiptId, shipmentId, ppOrderId, ppOrderLineId, ddOrderId, ddOrderLineId, inventoryId,
inventoryLineId, transactionId, directMovementWarehouse, huOnHandQtyChangeDescriptors); } /** * @return zero. */ @Override public BigDecimal getQuantity() { return BigDecimal.ZERO; } /** * @return our material descriptor's <b>negated</b> quantity, i.e. the negated {@code MovementQty} of the underlying {@code M_Transaction}. */ @Override public BigDecimal getQuantityDelta() { return getMaterialDescriptor().getQuantity().negate(); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\transactions\TransactionDeletedEvent.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { final SelectionSize selectionSize = context.getSelectionSize(); if (selectionSize.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (selectionSize.isAllSelected() || selectionSize.getSize() > 500) { // Checking is too expensive; just assume that some selected records have an email address return ProcessPreconditionsResolution.accept(); } final boolean atLeastOneRecordHasEmail = context .streamSelectedModels(I_C_Doc_Outbound_Log.class) .anyMatch(record -> !Check.isEmpty(record.getCurrentEMailAddress(), true)); if (!atLeastOneRecordHasEmail) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_EMPTY_MailTo)); } return ProcessPreconditionsResolution.accept(); } @Param(parameterName = PARA_OnlyNotSentMails, mandatory=true) private boolean p_OnlyNotSentMails = false; @Override protected final void prepare() { if (docOutboundService.retrieveLogs(getFilter(), true).isEmpty()) { throw new AdempiereException(MSG_No_DocOutboundLog_Selection); } }
protected IQueryFilter<I_C_Doc_Outbound_Log> getFilter() { final ProcessInfo pi = getProcessInfo(); return pi.getQueryFilterOrElse(ConstantQueryFilter.of(false)); } @Override @RunOutOfTrx protected final String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); final int counter = docOutboundService.sendMails( getFilter(), pinstanceId, p_OnlyNotSentMails); return msgBL.getMsg(Async_Constants.MSG_WORKPACKAGES_CREATED, ImmutableList.of(counter)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\mailrecipient\process\C_Doc_Outbound_Log_SendPDFMails.java
1
请完成以下Java代码
public class MybatisDeadLetterJobDataManager extends AbstractDataManager<DeadLetterJobEntity> implements DeadLetterJobDataManager { protected CachedEntityMatcher<DeadLetterJobEntity> deadLetterByExecutionIdMatcher = new DeadLetterJobsByExecutionIdMatcher(); public MybatisDeadLetterJobDataManager(ProcessEngineConfigurationImpl processEngineConfiguration) { super(processEngineConfiguration); } @Override public Class<? extends DeadLetterJobEntity> getManagedEntityClass() { return DeadLetterJobEntityImpl.class; } @Override public DeadLetterJobEntity create() { return new DeadLetterJobEntityImpl(); } @Override public void delete(DeadLetterJobEntity entity) { getDbSqlSession().delete(entity); } @Override @SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(DeadLetterJobQueryImpl jobQuery, Page page) { String query = "selectDeadLetterJobByQueryCriteria"; return getDbSqlSession().selectList(query, jobQuery, page); } @Override public long findJobCountByQueryCriteria(DeadLetterJobQueryImpl jobQuery) { return (Long) getDbSqlSession().selectOne("selectDeadLetterJobCountByQueryCriteria", jobQuery); } @Override public List<DeadLetterJobEntity> findJobsByExecutionId(String executionId) { return getList("selectDeadLetterJobsByExecutionId", executionId, deadLetterByExecutionIdMatcher, true); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().update("updateDeadLetterJobTenantIdForDeployment", params); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisDeadLetterJobDataManager.java
1
请在Spring Boot框架中完成以下Java代码
private IPricingResult calculateCommissionPointPriceFor( @NonNull final FlatrateTermId flatrateTermId, @NonNull final LocalDate requestedDate) { final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class); final IBPartnerDAO bPartnerDAO = Services.get(IBPartnerDAO.class); final IPricingBL pricingBL = Services.get(IPricingBL.class); final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class); final I_C_Flatrate_Term flatrateTerm = flatrateDAO.retrieveTerm(flatrateTermId); final BPartnerLocationAndCaptureId commissionToLocationId = ContractLocationHelper.extractBillToLocationId(flatrateTerm); final BPartnerId bPartnerId = BPartnerId.ofRepoId(flatrateTerm.getBill_BPartner_ID()); final PricingSystemId pricingSystemId = bPartnerDAO.retrievePricingSystemIdOrNull(bPartnerId, SOTrx.PURCHASE); final PriceListId priceListId = priceListDAO.retrievePriceListIdByPricingSyst(pricingSystemId, commissionToLocationId, SOTrx.PURCHASE);
final ProductId commissionProductId = ProductId.ofRepoId(flatrateTerm.getM_Product_ID()); final IEditablePricingContext pricingContext = pricingBL .createInitialContext( OrgId.ofRepoId(flatrateTerm.getAD_Org_ID()), commissionProductId, bPartnerId, Quantitys.of(ONE, commissionProductId), SOTrx.PURCHASE) .setPriceListId(priceListId) .setPriceDate(requestedDate); return pricingBL.calculatePrice(pricingContext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionPointsService.java
2
请完成以下Java代码
public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() { return rmtdAmt; } /** * Sets the value of the rmtdAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) { this.rmtdAmt = value; } /** * Gets the value of the fmlyMdclInsrncInd property. * * @return * possible object is * {@link Boolean } * */ public Boolean isFmlyMdclInsrncInd() { return fmlyMdclInsrncInd; } /** * Sets the value of the fmlyMdclInsrncInd property. * * @param value * allowed object is * {@link Boolean } * */ public void setFmlyMdclInsrncInd(Boolean value) { this.fmlyMdclInsrncInd = value; } /** * Gets the value of the mplyeeTermntnInd property. * * @return * possible object is
* {@link Boolean } * */ public Boolean isMplyeeTermntnInd() { return mplyeeTermntnInd; } /** * Sets the value of the mplyeeTermntnInd property. * * @param value * allowed object is * {@link Boolean } * */ public void setMplyeeTermntnInd(Boolean value) { this.mplyeeTermntnInd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\Garnishment1.java
1
请完成以下Java代码
public void train(String corpus) throws IOException { final List<List<String[]>> sequenceList = new LinkedList<List<String[]>>(); IOUtility.loadInstance(corpus, new InstanceHandler() { @Override public boolean process(Sentence sentence) { sequenceList.add(convertToSequence(sentence)); return false; } }); TagSet tagSet = getTagSet(); List<int[][]> sampleList = new ArrayList<int[][]>(sequenceList.size()); for (List<String[]> sequence : sequenceList) { int[][] sample = new int[2][sequence.size()]; int i = 0; for (String[] os : sequence)
{ sample[0][i] = vocabulary.idOf(os[0]); assert sample[0][i] != -1; sample[1][i] = tagSet.add(os[1]); assert sample[1][i] != -1; ++i; } sampleList.add(sample); } model.train(sampleList); vocabulary.mutable = false; } protected abstract List<String[]> convertToSequence(Sentence sentence); protected abstract TagSet getTagSet(); }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMTrainer.java
1
请完成以下Java代码
public void setOutboundHttpMethod (final String OutboundHttpMethod) { set_Value (COLUMNNAME_OutboundHttpMethod, OutboundHttpMethod); } @Override public String getOutboundHttpMethod() { return get_ValueAsString(COLUMNNAME_OutboundHttpMethod); } @Override public void setPassword (final @Nullable String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setSasSignature (final @Nullable String SasSignature) { set_Value (COLUMNNAME_SasSignature, SasSignature); } @Override public String getSasSignature() { return get_ValueAsString(COLUMNNAME_SasSignature); } /** * Type AD_Reference_ID=542016 * Reference name: ExternalSystem_Outbound_Endpoint_EndpointType */ public static final int TYPE_AD_Reference_ID=542016; /** HTTP = HTTP */ public static final String TYPE_HTTP = "HTTP"; /** SFTP = SFTP */ public static final String TYPE_SFTP = "SFTP"; /** FILE = FILE */ public static final String TYPE_FILE = "FILE"; /** EMAIL = EMAIL */ public static final String TYPE_EMAIL = "EMAIL"; /** TCP = TCP */ public static final String TYPE_TCP = "TCP"; @Override
public void setType (final String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public String getType() { return get_ValueAsString(COLUMNNAME_Type); } @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.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Outbound_Endpoint.java
1
请完成以下Java代码
public class DataFetchingEnvironmentMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { Class<?> type = parameter.getParameterType(); return (type.equals(DataFetchingEnvironment.class) || type.equals(GraphQLContext.class) || type.equals(DataFetchingFieldSelectionSet.class) || type.equals(GraphqlErrorBuilder.class) || type.equals(Locale.class) || isOptionalLocale(parameter)); } private static boolean isOptionalLocale(MethodParameter parameter) { return parameter.nestedIfOptional().getNestedParameterType().equals(Locale.class); } @Override public @Nullable Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) { Class<?> type = parameter.getParameterType(); if (type.equals(GraphQLContext.class)) { return environment.getGraphQlContext(); } else if (type.equals(DataFetchingFieldSelectionSet.class)) { return environment.getSelectionSet(); }
else if (type.equals(Locale.class)) { return environment.getLocale(); } else if (isOptionalLocale(parameter)) { return Optional.ofNullable(environment.getLocale()); } else if (type.equals(DataFetchingEnvironment.class)) { return environment; } else if (type.equals(GraphqlErrorBuilder.class)) { return GraphqlErrorBuilder.newError(environment); } else { throw new IllegalStateException("Unexpected method parameter type: " + parameter); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\DataFetchingEnvironmentMethodArgumentResolver.java
1
请完成以下Java代码
public ITrxListenerManager getTrxListenerManager() { return getTrxListenerManager(true); // create=true } @Override public final ITrxManager getTrxManager() { return trxManager; } private Map<String, Object> getPropertiesMap() { if (_properties == null) { synchronized (this) { if (_properties == null) { _properties = new ConcurrentHashMap<>(); } } } return _properties; } private Map<String, Object> getPropertiesMapOrNull() { synchronized (this) { return _properties; } } @Nullable @Override public final <T> T setProperty(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); // Handle null value case if (value == null) { final Map<String, Object> properties = getPropertiesMapOrNull(); if (properties == null) { return null; } @SuppressWarnings("unchecked") final T valueOld = (T)properties.remove(name); return valueOld; } else { @SuppressWarnings("unchecked") final T valueOld = (T)getPropertiesMap().put(name, value); return valueOld; } } @Override public final <T> T getProperty(final String name) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().get(name); return value; }
@Override public <T> T getProperty(final String name, final Supplier<T> valueInitializer) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.get()); return value; } @Override public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer) { @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.apply(this)); return value; } @Override public <T> T setAndGetProperty(@NonNull final String name, @NonNull final Function<T, T> valueRemappingFunction) { final BiFunction<? super String, ? super Object, ?> remappingFunction = (propertyName, oldValue) -> { @SuppressWarnings("unchecked") final T oldValueCasted = (T)oldValue; return valueRemappingFunction.apply(oldValueCasted); }; @SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().compute(name, remappingFunction); return value; } protected final void setDebugConnectionBackendId(final String debugConnectionBackendId) { this.debugConnectionBackendId = debugConnectionBackendId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrx.java
1
请完成以下Java代码
int size() { return _size; } /** * 清空缓存 */ void clear() { resize(0); _buf = null; _size = 0; _capacity = 0; } /** * 在末尾加一个值 * @param value 值 */ void add(byte value) { if (_size == _capacity) { resizeBuf(_size + 1); } _buf[_size++] = value; } /** * 将最后一个值去掉 */ void deleteLast() { --_size; } /** * 重设大小 * @param size 大小 */ void resize(int size) { if (size > _capacity) { resizeBuf(size); } _size = size; } /** * 重设大小,并且在末尾加一个值 * @param size 大小 * @param value 值 */ void resize(int size, byte value) { if (size > _capacity) { resizeBuf(size); } while (_size < size) { _buf[_size++] = value; } } /** * 增加容量 * @param size 容量 */ void reserve(int size) { if (size > _capacity) { resizeBuf(size); } }
/** * 设置缓冲区大小 * @param size 大小 */ private void resizeBuf(int size) { int capacity; if (size >= _capacity * 2) { capacity = size; } else { capacity = 1; while (capacity < size) { capacity <<= 1; } } byte[] buf = new byte[capacity]; if (_size > 0) { System.arraycopy(_buf, 0, buf, 0, _size); } _buf = buf; _capacity = capacity; } /** * 缓冲区 */ private byte[] _buf; /** * 大小 */ private int _size; /** * 容量 */ private int _capacity; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoBytePool.java
1
请在Spring Boot框架中完成以下Java代码
public class DeleteTimerJobCmd implements Command<Object>, Serializable { private static final Logger LOGGER = LoggerFactory.getLogger(DeleteTimerJobCmd.class); private static final long serialVersionUID = 1L; protected String timerJobId; protected JobServiceConfiguration jobServiceConfiguration; public DeleteTimerJobCmd(String timerJobId, JobServiceConfiguration jobServiceConfiguration) { this.timerJobId = timerJobId; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public Object execute(CommandContext commandContext) { TimerJobEntity jobToDelete = getJobToDelete(commandContext); sendCancelEvent(commandContext, jobToDelete); jobServiceConfiguration.getTimerJobEntityManager().delete(jobToDelete); return null; } protected void sendCancelEvent(CommandContext commandContext, TimerJobEntity jobToDelete) { FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete), jobServiceConfiguration.getEngineName()); } } protected TimerJobEntity getJobToDelete(CommandContext commandContext) { if (timerJobId == null) { throw new FlowableIllegalArgumentException("jobId is null");
} if (LOGGER.isDebugEnabled()) { LOGGER.debug("Deleting job {}", timerJobId); } TimerJobEntity job = jobServiceConfiguration.getTimerJobEntityManager().findById(timerJobId); if (job == null) { throw new FlowableObjectNotFoundException("No timer job found with id '" + timerJobId + "'", Job.class); } // We need to check if the job was locked, ie acquired by the job acquisition thread // This happens if the job was already acquired, but not yet executed. // In that case, we can't allow to delete the job. if (job.getLockOwner() != null) { throw new FlowableException("Cannot delete " + job + " when the job is being executed. Try again later."); } return job; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteTimerJobCmd.java
2
请在Spring Boot框架中完成以下Java代码
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() { DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient(); accessTokenResponseClient.setRequestEntityConverter(new CustomRequestEntityConverter()); OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); tokenResponseHttpMessageConverter.setTokenResponseConverter(new CustomTokenResponseConverter()); RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), tokenResponseHttpMessageConverter)); restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); accessTokenResponseClient.setRestOperations(restTemplate); return accessTokenResponseClient; } // additional configuration for non-Spring Boot projects private static List<String> clients = Arrays.asList("google", "facebook"); //@Bean public ClientRegistrationRepository clientRegistrationRepository() { List<ClientRegistration> registrations = clients.stream() .map(c -> getRegistration(c)) .filter(registration -> registration != null) .collect(Collectors.toList()); return new InMemoryClientRegistrationRepository(registrations); } private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration."; @Autowired private Environment env; private ClientRegistration getRegistration(String client) { String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
if (clientId == null) { return null; } String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret"); if (client.equals("google")) { return CommonOAuth2Provider.GOOGLE.getBuilder(client) .clientId(clientId) .clientSecret(clientSecret) .build(); } if (client.equals("facebook")) { return CommonOAuth2Provider.FACEBOOK.getBuilder(client) .clientId(clientId) .clientSecret(clientSecret) .build(); } return null; } }
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2\CustomRequestSecurityConfig.java
2
请完成以下Java代码
public void recreateGroup(@NonNull final Group group) {build().recreateGroup(group);} } public Group createGroup( @Nullable final Collection<OrderLineId> lineIdsToGroup, @Nullable final OrderId orderId, @Nullable final ConditionsId contractConditionsId) { final Group group = groupsRepo.retrieveOrCreateGroup( RetrieveOrCreateGroupRequest.builder() .orderId(orderId) .orderLineIds(lineIdsToGroup != null ? ImmutableSet.copyOf(lineIdsToGroup) : ImmutableSet.of()) .newGroupTemplate(groupTemplate) .newContractConditionsId(contractConditionsId) .qtyMultiplier(qty) .build()); recreateGroup(group);
return group; } public void recreateGroup(@NonNull final Group group) { group.removeAllGeneratedLines(); groupTemplate.getCompensationLines() .stream() .filter(compensationLineTemplate -> compensationLineTemplate.isMatching(group)) .map(templateLine -> compensationLineCreateRequestFactory.createGroupCompensationLineCreateRequest(templateLine, group)) .forEach(group::addNewCompensationLine); group.updateAllCompensationLines(); groupsRepo.saveGroup(group); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupCreator.java
1
请完成以下Java代码
public Incoterms getByValue(@NotNull final String value, @NotNull final OrgId orgId) { return getIncotermsMap().getByValue(value, orgId); } @NonNull private IncotermsMap getIncotermsMap() { return cache.getOrLoadNonNull(0, this::retrieveIncotermsMap); } @NotNull private IncotermsMap retrieveIncotermsMap() { final ImmutableList<Incoterms> incoterms = queryBL.createQueryBuilder(I_C_Incoterms.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(IncotermsRepository::ofRecord) .collect(ImmutableList.toImmutableList()); return new IncotermsRepository.IncotermsMap(incoterms); } private static Incoterms ofRecord(@NotNull final I_C_Incoterms record) { return Incoterms.builder() .id(IncotermsId.ofRepoId(record.getC_Incoterms_ID())) .name(record.getName()) .value(record.getValue()) .isDefault(record.isDefault()) .defaultLocation(record.getDefaultLocation()) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .build(); } private static final class IncotermsMap { private final ImmutableMap<IncotermsId, Incoterms> byId; private final ImmutableMap<OrgId, Incoterms> defaultByOrgId; private final ImmutableMap<ValueAndOrgId, Incoterms> byValueAndOrgId; IncotermsMap(final List<Incoterms> list) { this.byId = Maps.uniqueIndex(list, Incoterms::getId); this.defaultByOrgId = list.stream().filter(Incoterms::isDefault) .collect(ImmutableMap.toImmutableMap(Incoterms::getOrgId, incoterms->incoterms)); this.byValueAndOrgId = Maps.uniqueIndex(list, incoterm -> ValueAndOrgId.builder().value(incoterm.getValue()).orgId(incoterm.getOrgId()).build()); } @NonNull public Incoterms getById(@NonNull final IncotermsId id) { final Incoterms incoterms = byId.get(id); if (incoterms == null) {
throw new AdempiereException("Incoterms not found by ID: " + id); } return incoterms; } @Nullable public Incoterms getDefaultByOrgId(@NonNull final OrgId orgId) { return CoalesceUtil.coalesce(defaultByOrgId.get(orgId), defaultByOrgId.get(OrgId.ANY)); } @NonNull Incoterms getByValue(@NonNull final String value, @NonNull final OrgId orgId) { final Incoterms incoterms = CoalesceUtil.coalesce(byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(orgId).build()), byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(OrgId.ANY).build())); if (incoterms == null) { throw new AdempiereException("Incoterms not found by value: " + value + " and orgIds: " + orgId + " or " + OrgId.ANY); } return incoterms; } @Builder @Value private static class ValueAndOrgId { @NonNull String value; @NonNull OrgId orgId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getResourceSuffixes() { return resourceSuffixes; } public void setResourceSuffixes(List<String> resourceSuffixes) { this.resourceSuffixes = resourceSuffixes; } public boolean isDeployResources() { return deployResources; } public void setDeployResources(boolean deployResources) { this.deployResources = deployResources; } public boolean isEnableChangeDetection() { return enableChangeDetection; } public void setEnableChangeDetection(boolean enableChangeDetection) { this.enableChangeDetection = enableChangeDetection; } public Duration getChangeDetectionInitialDelay() { return changeDetectionInitialDelay; } public void setChangeDetectionInitialDelay(Duration changeDetectionInitialDelay) { this.changeDetectionInitialDelay = changeDetectionInitialDelay; } public Duration getChangeDetectionDelay() { return changeDetectionDelay;
} public void setChangeDetectionDelay(Duration changeDetectionDelay) { this.changeDetectionDelay = changeDetectionDelay; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public FlowableServlet getServlet() { return servlet; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\eventregistry\FlowableEventRegistryProperties.java
2
请完成以下Java代码
public class ClusterListener extends AbstractBehavior<ClusterEvent.ClusterDomainEvent> { public ClusterListener(ActorContext<ClusterEvent.ClusterDomainEvent> context) { super(context); Cluster cluster = Cluster.get(context.getSystem()); cluster.subscriptions().tell(Subscribe.create(getContext().getSelf(), ClusterEvent.ClusterDomainEvent.class)); } @Override public Receive<ClusterEvent.ClusterDomainEvent> createReceive() { return newReceiveBuilder() .onMessage(ClusterEvent.MemberUp.class, this::onMemberUp) .onMessage(ClusterEvent.MemberRemoved.class, this::onMemberRemoved) .onAnyMessage(event -> { System.out.println("Received cluster event: " + event); return this;
}) .build(); } private Behavior<ClusterEvent.ClusterDomainEvent> onMemberUp(ClusterEvent.MemberUp memberUp) { System.out.println("Member is Up: " + memberUp.member()); return this; } private Behavior<ClusterEvent.ClusterDomainEvent> onMemberRemoved(ClusterEvent.MemberRemoved memberRemoved) { System.out.println("Member is Removed: " + memberRemoved.member()); return this; } public static Behavior<ClusterEvent.ClusterDomainEvent> create() { return Behaviors.setup(ClusterListener::new); } }
repos\springboot-demo-master\akka\src\main\java\com\et\akka\cluster\ClusterListener.java
1
请完成以下Java代码
public static ImmutableTranslatableString ofMap( @Nullable final Map<String, String> trls, @Nullable final String defaultValue) { return new ImmutableTranslatableString(trls, defaultValue); } public static ImmutableTranslatableString ofDefaultValue(@Nullable final String defaultValue) { return ofMap(null, defaultValue); } private static ImmutableMap<String, String> normalizeTrlsMap(@Nullable final Map<String, String> trls) { if (trls == null || trls.isEmpty()) { return ImmutableMap.of(); } else if (trls.containsValue(null)) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); trls.forEach((adLanguage, trl) -> builder.put(adLanguage, trl != null ? trl : "")); return builder.build(); } else { return ImmutableMap.copyOf(trls); } } @Override @Deprecated public String toString() {
return defaultValue; } @Override public String translate(final String adLanguage) { return trlMap.getOrDefault(adLanguage, defaultValue); } @Override public String getDefaultValue() { return defaultValue; } @Override public Set<String> getAD_Languages() { return trlMap.keySet(); } @JsonIgnore // needed for snapshot testing public boolean isEmpty() { return defaultValue.isEmpty() && trlMap.values().stream().allMatch(String::isEmpty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ImmutableTranslatableString.java
1
请完成以下Java代码
public String getOneResult(String methodName) { return String.format("%s invoker success", methodName); } @Override public List<String> getMultiResult(String methodName) { List<String> list = new ArrayList<>(3); for (int i = 0; i < 3; i++) { list.add(String.format("%s invoker success, %d ", methodName, i + 1)); } return list; } @Override public User addUser(User user) { user.setId(1L); return user; } @Override
public List<User> findAllUser() { List<User> list = new ArrayList<>(); for (int i = 0; i < 3; i++) { int no = i + 1; list.add(new User((long) no, "USER_" + no, "PWD_" + no, 18 + no)); } return list; } @Override public User findUserById(Long id) { return new User(id, "USER_" + id, "PWD_" + id, 18); } }
repos\springboot-demo-master\webflux\src\main\java\com\et\webflux\DemoServiceImpl.java
1
请完成以下Java代码
public class CaseExecutionVariablesResource extends AbstractVariablesResource { public CaseExecutionVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) { super(engine, resourceId, objectMapper); } protected VariableMap getVariableEntities(boolean deserializeValues) { CaseService caseService = engine.getCaseService(); return caseService.getVariablesTyped(resourceId, deserializeValues); } protected void updateVariableEntities(VariableMap variables, List<String> deletions) { CaseService caseService = engine.getCaseService(); caseService .withCaseExecution(resourceId) .setVariables(variables) .removeVariables(deletions) .execute(); } protected void removeVariableEntity(String variableKey) { CaseService caseService = engine.getCaseService(); caseService
.withCaseExecution(resourceId) .removeVariable(variableKey) .execute(); } protected String getResourceTypeName() { return "case execution"; } protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { CaseService caseService = engine.getCaseService(); return caseService.getVariableTyped(resourceId, variableKey, deserializeValue); } protected void setVariableEntity(String variableKey, TypedValue variableValue) { CaseService caseService = engine.getCaseService(); caseService .withCaseExecution(resourceId) .setVariable(variableKey, variableValue) .execute(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\CaseExecutionVariablesResource.java
1
请完成以下Java代码
public Set<UserId> retrieveSystemUserIds() { return queryBL.createQueryBuilderOutOfTrx(I_AD_User.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_IsSystemUser, true) .orderByDescending(org.compiere.model.I_AD_User.COLUMNNAME_AD_User_ID) .create() .idsAsSet(UserId::ofRepoId); } @Override public boolean isSystemUser(@NonNull final UserId userId) { return queryBL .createQueryBuilder(I_AD_User.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_AD_User_ID, userId) .addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_IsSystemUser, true) .create() .anyMatch(); } @Override public BPartnerId getBPartnerIdByUserId(@NonNull final UserId userId) { final org.compiere.model.I_AD_User userRecord = getById(userId); return BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID()); } @Override public <T extends org.compiere.model.I_AD_User> T getByIdInTrx(final UserId userId, final Class<T> modelClass) { return load(userId, modelClass); } @Override @Nullable public UserId retrieveUserIdByLogin(@NonNull final String login) { return queryBL .createQueryBuilderOutOfTrx(I_AD_User.class) .addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_Login, login) .create() .firstId(UserId::ofRepoIdOrNull); } @Override public void save(@NonNull final org.compiere.model.I_AD_User user) {
InterfaceWrapperHelper.save(user); } @Override public Optional<I_AD_User> getCounterpartUser( @NonNull final UserId sourceUserId, @NonNull final OrgId targetOrgId) { final OrgMappingId orgMappingId = getOrgMappingId(sourceUserId).orElse(null); if (orgMappingId == null) { return Optional.empty(); } final UserId targetUserId = queryBL.createQueryBuilder(I_AD_User.class) .addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_Mapping_ID, orgMappingId) .addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_ID, targetOrgId) .orderByDescending(I_AD_User.COLUMNNAME_AD_User_ID) .create() .firstId(UserId::ofRepoIdOrNull); if (targetUserId == null) { return Optional.empty(); } return Optional.of(getById(targetUserId)); } @Override public ImmutableSet<UserId> retrieveUsersByJobId(@NonNull final JobId jobId) { return queryBL.createQueryBuilder(I_AD_User.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_User.COLUMNNAME_C_Job_ID, jobId) .create() .idsAsSet(UserId::ofRepoId); } private Optional<OrgMappingId> getOrgMappingId(@NonNull final UserId sourceUserId) { final I_AD_User sourceUserRecord = getById(sourceUserId); return OrgMappingId.optionalOfRepoId(sourceUserRecord.getAD_Org_Mapping_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserDAO.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getRemoveWaitingForRepetitionPlanItemDefinitionIds() { return removeWaitingForRepetitionPlanItemDefinitionIds; } @ApiModelProperty(value = "remove waiting for repetition to provided plan item definition ids") public void setRemoveWaitingForRepetitionPlanItemDefinitionIds(List<String> removeWaitingForRepetitionPlanItemDefinitionIds) { this.removeWaitingForRepetitionPlanItemDefinitionIds = removeWaitingForRepetitionPlanItemDefinitionIds; } public Map<String, String> getChangePlanItemIds() { return changePlanItemIds; } @ApiModelProperty(value = "map an existing plan item id to new plan item id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemIds(Map<String, String> changePlanItemIds) { this.changePlanItemIds = changePlanItemIds; } public Map<String, String> getChangePlanItemIdsWithDefinitionId() { return changePlanItemIdsWithDefinitionId; }
@ApiModelProperty(value = "map an existing plan item id to new plan item id with the plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemIdsWithDefinitionId(Map<String, String> changePlanItemIdsWithDefinitionId) { this.changePlanItemIdsWithDefinitionId = changePlanItemIdsWithDefinitionId; } public List<PlanItemDefinitionWithTargetIdsRequest> getChangePlanItemDefinitionsWithNewTargetIds() { return changePlanItemDefinitionsWithNewTargetIds; } @ApiModelProperty(value = "map an existing plan item id to a new plan item id and plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemDefinitionsWithNewTargetIds(List<PlanItemDefinitionWithTargetIdsRequest> changePlanItemDefinitionsWithNewTargetIds) { this.changePlanItemDefinitionsWithNewTargetIds = changePlanItemDefinitionsWithNewTargetIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\ChangePlanItemStateRequest.java
2
请在Spring Boot框架中完成以下Java代码
private AggregatedPricingRule createPricingRules() { final IPricingDAO pricingRulesRepo = Services.get(IPricingDAO.class); final ImmutableList<IPricingRule> rules = pricingRulesRepo.getPricingRules() .stream() .map(this::createPricingRuleNoFail) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); return AggregatedPricingRule.of(rules); } @Nullable private IPricingRule createPricingRuleNoFail(final PricingRuleDescriptor ruleDef) { try { return ruleDef.getPricingRuleClass().getReferencedClass().newInstance(); } catch (final Exception ex) { logger.warn("Cannot load rule for {}", ruleDef, ex); return null; } } private CurrencyPrecision getPricePrecision(@NonNull final PriceListId priceListId) { return Services.get(IPriceListBL.class).getPricePrecision(priceListId);
} @Override public void registerPriceLimitRule(@NonNull final IPriceLimitRule rule) { priceLimitRules.addEnforcer(rule); } @Override public PriceLimitRuleResult computePriceLimit(@NonNull final PriceLimitRuleContext context) { return priceLimitRules.compute(context); } @Override public Set<CountryId> getPriceLimitCountryIds() { return priceLimitRules.getPriceCountryIds(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingBL.java
2
请在Spring Boot框架中完成以下Java代码
protected ProcessEngine getProcessEngineService(ServiceName processEngineServiceName) { try { ServiceController<ProcessEngine> serviceController = getProcessEngineServiceController(processEngineServiceName); return serviceController.getValue(); } catch (ServiceNotFoundException e) { return null; } } @SuppressWarnings("unchecked") protected ServiceController<ProcessEngine> getProcessEngineServiceController(ServiceName processEngineServiceName) { ServiceController<ProcessEngine> serviceController = (ServiceController<ProcessEngine>) serviceContainer.getRequiredService(processEngineServiceName); return serviceController; } protected void startTrackingServices() { processEngineServiceTracker = new ServiceTracker<>(ServiceNames.forManagedProcessEngines(), processEngines); serviceContainer.addListener(processEngineServiceTracker); processApplicationServiceTracker = new ServiceTracker<>(ServiceNames.forManagedProcessApplications(), processApplications); serviceContainer.addListener(processApplicationServiceTracker); } protected void stopTrackingServices() { serviceContainer.removeListener(processEngineServiceTracker); serviceContainer.removeListener(processApplicationServiceTracker); } /** * <p>invoked by the {@link MscManagedProcessEngine} and {@link MscManagedProcessEngineController} * when a process engine is started</p> */ public void processEngineStarted(ProcessEngine processEngine) { processEngines.add(processEngine);
} /** * <p>invoked by the {@link MscManagedProcessEngine} and {@link MscManagedProcessEngineController} * when a process engine is stopped</p> */ public void processEngineStopped(ProcessEngine processEngine) { processEngines.remove(processEngine); } @SuppressWarnings("unchecked") protected MscManagedProcessApplication getManagedProcessApplication(String name) { ServiceController<MscManagedProcessApplication> serviceController = (ServiceController<MscManagedProcessApplication>) serviceContainer .getService(ServiceNames.forManagedProcessApplication(name)); if (serviceController != null) { return serviceController.getValue(); } else { return null; } } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscRuntimeContainerDelegate.java
2
请完成以下Java代码
public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getDocStatus().isCompleted() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.getWfActivity().getWfActivityType().assertExpected(HANDLED_ACTIVITY_TYPE); return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJobRestService::complete ); } private String getQuestion(@NonNull final WFProcess wfProcess, @NonNull final String language) {
final PickingJob pickingJob = wfProcess.getDocumentAs(PickingJob.class); if (pickingJob.getProgress().isDone()) { return msgBL.getMsg(language, ARE_YOU_SURE); } final PickingJobOptions options = pickingJobRestService.getPickingJobOptions(pickingJob.getCustomerId()); if (!options.isAllowCompletingPartialPickingJob()) { return msgBL.getMsg(language, ARE_YOU_SURE); } return msgBL.getMsg(language, NOT_ALL_LINES_ARE_COMPLETED_WARNING); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\CompletePickingWFActivityHandler.java
1
请完成以下Java代码
public static ProcessEngine getProcessEngine(String processEngineName) { return getProcessEngine(processEngineName, true); } /** obtain a process engine by name. * @param processEngineName is the name of the process engine or null for the default process engine. */ public static ProcessEngine getProcessEngine(String processEngineName, boolean forceCreate) { if (!isInitialized) { init(forceCreate); } return processEngines.get(processEngineName); } /** retries to initialize a process engine that previously failed. */ public static ProcessEngineInfo retry(String resourceUrl) { try { return initProcessEngineFromResource(new URL(resourceUrl)); } catch (MalformedURLException e) { throw new ProcessEngineException("invalid url: "+resourceUrl, e); } } /** provides access to process engine to application clients in a * managed server environment. */ public static Map<String, ProcessEngine> getProcessEngines() { return processEngines;
} /** closes all process engines. This method should be called when the server shuts down. */ public synchronized static void destroy() { if (isInitialized) { Map<String, ProcessEngine> engines = new HashMap<String, ProcessEngine>(processEngines); processEngines = new HashMap<String, ProcessEngine>(); for (String processEngineName: engines.keySet()) { ProcessEngine processEngine = engines.get(processEngineName); try { processEngine.close(); } catch (Exception e) { LOG.exceptionWhileClosingProcessEngine(processEngineName==null ? "the default process engine" : "process engine "+processEngineName, e); } } processEngineInfosByName.clear(); processEngineInfosByResourceUrl.clear(); processEngineInfos.clear(); isInitialized = false; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\ProcessEngines.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ @Override protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } @Override public String toString() { StringBuffer sb = new StringBuffer ("X_C_DirectDebitLine[") .append(get_ID()).append("]"); return sb.toString(); } @Override public I_C_DirectDebit getC_DirectDebit() throws Exception { return get_ValueAsPO(COLUMNNAME_C_DirectDebit_ID, org.compiere.model.I_C_DirectDebit.class); } /** Set C_DirectDebit_ID. @param C_DirectDebit_ID C_DirectDebit_ID */ @Override public void setC_DirectDebit_ID (int C_DirectDebit_ID) { if (C_DirectDebit_ID < 1) throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory."); set_Value (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID)); } /** Get C_DirectDebit_ID. @return C_DirectDebit_ID */ @Override public int getC_DirectDebit_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID); if (ii == null) return 0; return ii.intValue(); } /** Set C_DirectDebitLine_ID. @param C_DirectDebitLine_ID C_DirectDebitLine_ID */ @Override public void setC_DirectDebitLine_ID (int C_DirectDebitLine_ID) { if (C_DirectDebitLine_ID < 1) throw new IllegalArgumentException ("C_DirectDebitLine_ID is mandatory."); set_ValueNoCheck (COLUMNNAME_C_DirectDebitLine_ID, Integer.valueOf(C_DirectDebitLine_ID)); } /** Get C_DirectDebitLine_ID.
@return C_DirectDebitLine_ID */ @Override public int getC_DirectDebitLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebitLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override public I_C_Invoice getC_Invoice() throws Exception { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); } /** Set Invoice. @param C_Invoice_ID Invoice Identifier */ @Override public void setC_Invoice_ID (int C_Invoice_ID) { if (C_Invoice_ID < 1) throw new IllegalArgumentException ("C_Invoice_ID is mandatory."); set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID)); } /** Get Invoice. @return Invoice Identifier */ @Override public int getC_Invoice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebitLine.java
1
请完成以下Java代码
public DmnElement getElement() { return element; } public void setElement(DmnElement element) { this.element = element; } public int getXmlRowNumber() { return xmlRowNumber; } public void setXmlRowNumber(int xmlRowNumber) { this.xmlRowNumber = xmlRowNumber; } public int getXmlColumnNumber() { return xmlColumnNumber; } public void setXmlColumnNumber(int xmlColumnNumber) { this.xmlColumnNumber = xmlColumnNumber; } public boolean equals(GraphicInfo ginfo) { if (this.getX() != ginfo.getX()) { return false; } if (this.getY() != ginfo.getY()) { return false; } if (this.getHeight() != ginfo.getHeight()) { return false; } if (this.getWidth() != ginfo.getWidth()) {
return false; } // check for zero value in case we are comparing model value to BPMN DI value // model values do not have xml location information if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) { return false; } if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) { return false; } // only check for elements that support this value if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) { return false; } return true; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\GraphicInfo.java
1
请完成以下Java代码
public void addFlowGraphicInfoListByDiagramId(String diagramId, String key, List<GraphicInfo> graphicInfoList) { flowLocationByDiagramIdMap.computeIfAbsent(diagramId, k -> new LinkedHashMap<>()); flowLocationByDiagramIdMap.get(diagramId).put(key, graphicInfoList); flowLocationMap.put(key, graphicInfoList); } public Map<String, Map<String, GraphicInfo>> getLabelLocationByDiagramIdMap() { return labelLocationByDiagramIdMap; } public Map<String, GraphicInfo> getLabelLocationByDiagramId(String diagramId) { return labelLocationByDiagramIdMap.get(diagramId); } public void addLabelGraphicInfo(String key, GraphicInfo graphicInfo) { labelLocationMap.put(key, graphicInfo); } public void addLabelGraphicInfoByDiagramId(String diagramId, String key, GraphicInfo graphicInfo) { labelLocationByDiagramIdMap.computeIfAbsent(diagramId, k -> new LinkedHashMap<>()); labelLocationByDiagramIdMap.get(diagramId).put(key, graphicInfo); labelLocationMap.put(key, graphicInfo); } public void removeLabelGraphicInfo(String key) { flowLocationMap.remove(key); } public Map<String, Map<String, List<GraphicInfo>>> getDecisionServiceDividerLocationByDiagramIdMap() { return decisionServiceDividerLocationByDiagramIdMap; } public Map<String, List<GraphicInfo>> getDecisionServiceDividerLocationMapByDiagramId(String diagramId) { return decisionServiceDividerLocationByDiagramIdMap.get(diagramId); } public Map<String, List<GraphicInfo>> getDecisionServiceDividerLocationMap() { return decisionServiceDividerLocationMap; } public List<GraphicInfo> getDecisionServiceDividerGraphicInfo(String key) { return decisionServiceDividerLocationMap.get(key); } public void addDecisionServiceDividerGraphicInfoList(String key, List<GraphicInfo> graphicInfoList) { decisionServiceDividerLocationMap.put(key, graphicInfoList); } public void addDecisionServiceDividerGraphicInfoListByDiagramId(String diagramId, String key, List<GraphicInfo> graphicInfoList) { decisionServiceDividerLocationByDiagramIdMap.computeIfAbsent(diagramId, k -> new LinkedHashMap<>());
decisionServiceDividerLocationByDiagramIdMap.get(diagramId).put(key, graphicInfoList); decisionServiceDividerLocationMap.put(key, graphicInfoList); } public String getExporter() { return exporter; } public void setExporter(String exporter) { this.exporter = exporter; } public String getExporterVersion() { return exporterVersion; } public void setExporterVersion(String exporterVersion) { this.exporterVersion = exporterVersion; } public Map<String, String> getNamespaces() { return namespaceMap; } public void addNamespace(String prefix, String uri) { namespaceMap.put(prefix, uri); } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnDefinition.java
1
请完成以下Java代码
private static void updateAllocationRecord( @NonNull final I_M_InOutLine_To_C_Customs_Invoice_Line record, @NonNull final CustomsInvoiceLineAlloc alloc, @NonNull final CustomsInvoiceLineId customsInvoiceLineId, @NonNull final ProductId productId) { record.setM_InOut_ID(alloc.getInoutAndLineId().getInOutId().getRepoId()); record.setM_InOutLine_ID(alloc.getInoutAndLineId().getInOutLineId().getRepoId()); record.setC_Customs_Invoice_ID(customsInvoiceLineId.getCustomsInvoiceId().getRepoId()); record.setC_Customs_Invoice_Line_ID(customsInvoiceLineId.getRepoId()); record.setM_Product_ID(productId.getRepoId()); record.setC_UOM_ID(alloc.getQuantityInPriceUOM().getUomId().getRepoId()); record.setMovementQty(alloc.getQuantityInPriceUOM().toBigDecimal()); record.setPriceActual(alloc.getPrice().toBigDecimal()); record.setC_Currency_ID(alloc.getPrice().getCurrencyId().getRepoId()); saveRecord(record); } private List<I_M_InOutLine_To_C_Customs_Invoice_Line> retrieveAllocationRecords(final CustomsInvoiceLineId customsInvoiceLineId) { return queryBL.createQueryBuilder(I_M_InOutLine_To_C_Customs_Invoice_Line.class) .addEqualsFilter(I_M_InOutLine_To_C_Customs_Invoice_Line.COLUMN_C_Customs_Invoice_Line_ID, customsInvoiceLineId) .orderBy(I_M_InOutLine_To_C_Customs_Invoice_Line.COLUMN_M_InOutLine_To_C_Customs_Invoice_Line_ID) .create() .list(); } private static InOutAndLineId extractInOutAndLineId(final I_M_InOutLine_To_C_Customs_Invoice_Line record) {
return InOutAndLineId.ofRepoId(record.getM_InOut_ID(), record.getM_InOutLine_ID()); } private ImmutableListMultimap<CustomsInvoiceLineId, CustomsInvoiceLineAlloc> retrieveAllocations(final CustomsInvoiceId customsInvoiceId) { return queryBL.createQueryBuilder(I_M_InOutLine_To_C_Customs_Invoice_Line.class) .addEqualsFilter(I_M_InOutLine_To_C_Customs_Invoice_Line.COLUMN_C_Customs_Invoice_ID, customsInvoiceId) .orderBy(I_M_InOutLine_To_C_Customs_Invoice_Line.COLUMN_M_InOutLine_To_C_Customs_Invoice_Line_ID) .create() .stream() .collect(ImmutableListMultimap.toImmutableListMultimap( record -> extractCustomsInvoiceLineId(record), record -> toCustomsInvoiceLineAlloc(record))); } private CustomsInvoiceLineAlloc toCustomsInvoiceLineAlloc(final I_M_InOutLine_To_C_Customs_Invoice_Line record) { return CustomsInvoiceLineAlloc.builder() .inoutAndLineId(extractInOutAndLineId(record)) .price(Money.of(record.getPriceActual(), CurrencyId.ofRepoId(record.getC_Currency_ID()))) .quantityInPriceUOM(Quantity.of(record.getMovementQty(), uomDAO.getById(record.getC_UOM_ID()))) .build(); } private static CustomsInvoiceLineId extractCustomsInvoiceLineId(final I_M_InOutLine_To_C_Customs_Invoice_Line record) { return CustomsInvoiceLineId.ofRepoId(record.getC_Customs_Invoice_ID(), record.getC_Customs_Invoice_Line_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\CustomsInvoiceRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class ProducerService { private static final Logger logger = LoggerFactory.getLogger(ProducerService.class); @Autowired private ALiMqConfig aLiMqConfig; @Autowired private ProducerBean producer; /** * 调用此方法 发送消息,o 为自定义的消息体 */ public void sendMessage(Object o) { Message message = new Message(aLiMqConfig.getStockTopic(), "test", JSON.toJSON(o).toString().getBytes(StandardCharsets.UTF_8)); //向mq发送消息 sendAsync(ProducerBean::isStarted, producer, message); } /** * 向阿里云rocket mq发送消息。 * * @param predicate 断言 * @param bean 发送消息bean * @param message 需要发送的消息 */ private static void sendAsync(Predicate<ProducerBean> predicate, ProducerBean bean, Message message) { if (predicate.test(bean)) { bean.sendAsync(message, new SendCallback() {
@Override public void onSuccess(SendResult sendResult) { logger.info("向mq推送库存消息成功,消息是:{}", sendResult.toString()); } @Override public void onException(OnExceptionContext e) { logger.error("向mq推送库存消息失败,消息id 为 {} 错误是:{}", e.getMessageId(), e.getException().getMessage()); } }); } else { logger.error("mq库存生产端启动失败!!!消息是:{}", message.toString()); } } }
repos\springBoot-master\springboot-rocketmq-ali\src\main\java\cn\abel\queue\service\ProducerService.java
2
请完成以下Java代码
public class X_M_Product_PrintFormat extends org.compiere.model.PO implements I_M_Product_PrintFormat, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1870500207L; /** Standard Constructor */ public X_M_Product_PrintFormat (final Properties ctx, final int M_Product_PrintFormat_ID, @Nullable final String trxName) { super (ctx, M_Product_PrintFormat_ID, trxName); } /** Load Constructor */ public X_M_Product_PrintFormat (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_PrintFormat getAD_PrintFormat() { return get_ValueAsPO(COLUMNNAME_AD_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class); } @Override public void setAD_PrintFormat(final org.compiere.model.I_AD_PrintFormat AD_PrintFormat) { set_ValueFromPO(COLUMNNAME_AD_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class, AD_PrintFormat); } @Override public void setAD_PrintFormat_ID (final int AD_PrintFormat_ID) { if (AD_PrintFormat_ID < 1) set_Value (COLUMNNAME_AD_PrintFormat_ID, null); else set_Value (COLUMNNAME_AD_PrintFormat_ID, AD_PrintFormat_ID); } @Override public int getAD_PrintFormat_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrintFormat_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null);
else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Product_PrintFormat_ID (final int M_Product_PrintFormat_ID) { if (M_Product_PrintFormat_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_PrintFormat_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_PrintFormat_ID, M_Product_PrintFormat_ID); } @Override public int getM_Product_PrintFormat_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_PrintFormat_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PrintFormat.java
1
请完成以下Java代码
public Boolean getActive() { return active; } public void setActive(final Boolean active) { this.active = active; } public void setPassword(final String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? authorities : Collections.emptyList(); } @Override public void setAuthorities(final Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; }
@Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return Boolean.TRUE.equals(active); } @InstanceName @DependsOnProperties({"firstName", "lastName", "username"}) public String getDisplayName() { return String.format("%s %s [%s]", (firstName != null ? firstName : ""), (lastName != null ? lastName : ""), username).trim(); } @Override public String getTimeZoneId() { return timeZoneId; } public void setTimeZoneId(final String timeZoneId) { this.timeZoneId = timeZoneId; } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\entity\User.java
1
请完成以下Java代码
public class VersionResult { /** * 是否发现新版本 */ @ApiModelProperty(value = "是否发现新版本(true:发现新版本,false:没有发现新版本)", name = "findNew", example = "true", required = true) private boolean findNew; /** * APP名称 */ @ApiModelProperty(value = "APP名称", name = "appName", example = "行政收费") private String appName; /** * 新版本号 */ @ApiModelProperty(value = "新版本号", name = "version", example = "v1.3.8") private String version; /** * 新版本说明 */ @ApiModelProperty(value = "新版本说明", name = "tips", example = "增加人脸识别功能") private String tips; /** * 新版本发布时间 */ @ApiModelProperty(value = "新版本发布时间", name = "publishtime", example = "2017-12-24 12:32:19") private Date publishtime; /** * 新版本下载地址 */ @ApiModelProperty(value = "新版本下载地址", name = "downloadUrl", example = "http://xncoding.net/files/行政收费_1.3.0.apk") private String downloadUrl; public boolean isFindNew() { return findNew; } public void setFindNew(boolean findNew) { this.findNew = findNew; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; }
public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getTips() { return tips; } public void setTips(String tips) { this.tips = tips; } public Date getPublishtime() { return publishtime; } public void setPublishtime(Date publishtime) { this.publishtime = publishtime; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\VersionResult.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; } Hospital hospital = (Hospital) o; return Objects.equals(this._id, hospital._id) && Objects.equals(this.company, hospital.company) && Objects.equals(this.name, hospital.name) && Objects.equals(this.companyName, hospital.companyName) && Objects.equals(this.additionalCompanyName, hospital.additionalCompanyName) && Objects.equals(this.address, hospital.address) && Objects.equals(this.postalCode, hospital.postalCode) && Objects.equals(this.city, hospital.city) && Objects.equals(this.phone, hospital.phone) && Objects.equals(this.fax, hospital.fax) && Objects.equals(this.email, hospital.email) && Objects.equals(this.website, hospital.website) && Objects.equals(this.timestamp, hospital.timestamp); } @Override public int hashCode() { return Objects.hash(_id, company, name, companyName, additionalCompanyName, address, postalCode, city, phone, fax, email, website, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Hospital {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" company: ").append(toIndentedString(company)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" companyName: ").append(toIndentedString(companyName)).append("\n"); sb.append(" additionalCompanyName: ").append(toIndentedString(additionalCompanyName)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" website: ").append(toIndentedString(website)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).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-patient-api\src\main\java\io\swagger\client\model\Hospital.java
2
请完成以下Java代码
public String getArea() { return area; } } public class AuthoredArticle { private UUID id; private String title; private String content; private Date createdAt; private Area area; private Author author; public Area getArea() { return area; } public void setArea(Area area) { this.area = area; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public UUID getId() {
return id; } public void setId(UUID id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonschemageneration\recursive\AuthoredArticle.java
1
请在Spring Boot框架中完成以下Java代码
public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // For examples using Spring 4.1.0 if ((env.getProperty("resource.handler.conf")).equals("4.1.0")) { registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(3600).resourceChain(true).addResolver(new EncodedResourceResolver()).addResolver(new PathResourceResolver()); registry.addResourceHandler("/resources/**").addResourceLocations("/resources/", "classpath:/other-resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); registry.addResourceHandler("/other-files/**").addResourceLocations("file:/Users/Elena/").setCachePeriod(3600).resourceChain(true).addResolver(new EncodedResourceResolver()); } // For examples using Spring 4.0.7 else if ((env.getProperty("resource.handler.conf")).equals("4.0.7")) { registry.addResourceHandler("/resources/**").addResourceLocations("/", "/resources/", "classpath:/other-resources/"); registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/Elena/"); } } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); registry.addInterceptor(localeChangeInterceptor); } @Bean public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { ResourceUrlEncodingFilter filter = new ResourceUrlEncodingFilter(); return filter; }
@Bean public LocaleResolver localeResolver() { CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); return cookieLocaleResolver; } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setUseCodeAsDefaultMessage(true); messageSource.setDefaultEncoding("UTF-8"); messageSource.setCacheSeconds(0); return messageSource; } }
repos\tutorials-master\spring-web-modules\spring-static-resources\src\main\java\com\baeldung\spring\MvcConfig.java
2
请完成以下Java代码
private final I_AD_Image retrieveLogoADImage() { final Properties ctx = Env.newTemporaryCtx(); final I_AD_Client client = retriveAD_Client(ctx); if (client == null) { return null; } final I_AD_ClientInfo clientInfo = Services.get(IClientDAO.class).retrieveClientInfo(ctx, client.getAD_Client_ID()); if (clientInfo == null) { return null; } I_AD_Image logo = clientInfo.getLogoWeb(); if (logo == null) { logo = clientInfo.getLogo(); } return logo; } private final I_AD_Client retriveAD_Client(final Properties ctx) { final List<I_AD_Client> clients = Services.get(IClientDAO.class).retrieveAllClients(ctx); for (final I_AD_Client client : clients) { if (client.getAD_Client_ID() > 0) { return client; } } return null; } private BufferedImage loadProductLogoImage() { final Image logo = Adempiere.getProductLogoLarge(); if (logo == null) { return null; } return toBufferedImage(logo); } /** * Converts a given Image into a BufferedImage * * @param image The Image to be converted * @return The converted BufferedImage */ public static BufferedImage toBufferedImage(final Image image) { if (image instanceof BufferedImage) { return (BufferedImage)image; } // Create a buffered image with transparency final BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image final Graphics2D bGr = bufferedImage.createGraphics(); bGr.drawImage(image, 0, 0, null); bGr.dispose(); // Return the buffered image return bufferedImage; } private static byte[] toPngData(final BufferedImage image, final int width) { if (image == null) { return null; } BufferedImage imageScaled; final int widthOrig = image.getWidth(); final int heightOrig = image.getHeight(); if (width > 0 && widthOrig > 0) { final double scale = (double)width / (double)widthOrig; final int height = (int)(heightOrig * scale); imageScaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final AffineTransform at = new AffineTransform(); at.scale(scale, scale); final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); imageScaled = scaleOp.filter(image, imageScaled); } else { imageScaled = image; } final ByteArrayOutputStream pngBuf = new ByteArrayOutputStream(); try { ImageIO.write(imageScaled, "png", pngBuf); } catch (final Exception e) { e.printStackTrace(); return null; } return pngBuf.toByteArray(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ImagesServlet.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } if (!streamSelectedHUIds(Select.ONLY_TOPLEVEL).findAny().isPresent()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU)); } if (!securPharmService.hasConfig()) { return ProcessPreconditionsResolution.rejectWithInternalReason("No securpharm config"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt()
{ final DataMatrixCode dataMatrix = getDataMatrix(); final SecurPharmHUAttributesScanner scanner = securPharmService.newHUScanner(); streamSelectedHUs(Select.ONLY_TOPLEVEL) .forEach(hu -> scanner.scanAndUpdateHUAttributes(dataMatrix, hu)); return super.doIt(); } protected final DataMatrixCode getDataMatrix() { return DataMatrixCode.ofString(dataMatrixCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnFromCustomer_Pharma.java
1
请完成以下Java代码
public class RestartProcessInstancesBatchCmd extends AbstractRestartProcessInstanceCmd<Batch> { private final CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER; public RestartProcessInstancesBatchCmd(CommandExecutor commandExecutor, RestartProcessInstanceBuilderImpl builder) { super(commandExecutor, builder); } @Override public Batch execute(CommandContext commandContext) { Collection<String> collectedInstanceIds = collectProcessInstanceIds(); List<AbstractProcessInstanceModificationCommand> instructions = builder.getInstructions(); ensureNotEmpty(BadUserRequestException.class, "Restart instructions cannot be empty", "instructions", instructions); ensureNotEmpty(BadUserRequestException.class, "Process instance ids cannot be empty", "processInstanceIds", collectedInstanceIds); ensureNotContainsNull(BadUserRequestException.class, "Process instance ids cannot be null", "processInstanceIds", collectedInstanceIds); String processDefinitionId = builder.getProcessDefinitionId(); ProcessDefinitionEntity processDefinition = getProcessDefinition(commandContext, processDefinitionId); ensureNotNull(BadUserRequestException.class, "Process definition cannot be null", processDefinition); ensureTenantAuthorized(commandContext, processDefinition); String tenantId = processDefinition.getTenantId(); return new BatchBuilder(commandContext) .type(Batch.TYPE_PROCESS_INSTANCE_RESTART) .config(getConfiguration(collectedInstanceIds, processDefinition.getDeploymentId())) .permission(BatchPermissions.CREATE_BATCH_RESTART_PROCESS_INSTANCES)
.tenantId(tenantId) .operationLogHandler((ctx, instanceCount) -> writeUserOperationLog(ctx, processDefinition, instanceCount, true)) .build(); } protected void ensureTenantAuthorized(CommandContext commandContext, ProcessDefinitionEntity processDefinition) { if (!commandContext.getTenantManager().isAuthenticatedTenant(processDefinition.getTenantId())) { throw LOG.exceptionCommandWithUnauthorizedTenant("restart process instances of process definition '" + processDefinition.getId() + "'"); } } public BatchConfiguration getConfiguration(Collection<String> instanceIds, String deploymentId) { return new RestartProcessInstancesBatchConfiguration( new ArrayList<>(instanceIds), DeploymentMappings.of(new DeploymentMapping(deploymentId, instanceIds.size())), builder.getInstructions(), builder.getProcessDefinitionId(), builder.isInitialVariables(), builder.isSkipCustomListeners(), builder.isSkipIoMappings(), builder.isWithoutBusinessKey()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\RestartProcessInstancesBatchCmd.java
1
请完成以下Java代码
public void setAuthoritiesClaimDelimiter(String authoritiesClaimDelimiter) { Assert.notNull(authoritiesClaimDelimiter, "authoritiesClaimDelimiter cannot be null"); this.authoritiesClaimDelimiter = authoritiesClaimDelimiter; } /** * Sets the name of token claim to use for mapping {@link GrantedAuthority * authorities} by this converter. Defaults to * {@link JwtGrantedAuthoritiesConverter#WELL_KNOWN_AUTHORITIES_CLAIM_NAMES}. * @param authoritiesClaimName The token claim name to map authorities * @since 5.2 */ public void setAuthoritiesClaimName(String authoritiesClaimName) { Assert.hasText(authoritiesClaimName, "authoritiesClaimName cannot be empty"); this.authoritiesClaimNames = Collections.singletonList(authoritiesClaimName); } private String getAuthoritiesClaimName(Jwt jwt) { for (String claimName : this.authoritiesClaimNames) { if (jwt.hasClaim(claimName)) { return claimName; } } return null; } private Collection<String> getAuthorities(Jwt jwt) { String claimName = getAuthoritiesClaimName(jwt); if (claimName == null) { this.logger.trace("Returning no authorities since could not find any claims that might contain scopes"); return Collections.emptyList(); } if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Looking for scopes in claim %s", claimName));
} Object authorities = jwt.getClaim(claimName); if (authorities instanceof String) { if (StringUtils.hasText((String) authorities)) { return Arrays.asList(((String) authorities).split(this.authoritiesClaimDelimiter)); } return Collections.emptyList(); } if (authorities instanceof Collection) { return castAuthoritiesToCollection(authorities); } return Collections.emptyList(); } @SuppressWarnings("unchecked") private Collection<String> castAuthoritiesToCollection(Object authorities) { return (Collection<String>) authorities; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtGrantedAuthoritiesConverter.java
1
请完成以下Java代码
public PlanItemInstanceLifecycleListener createClassDelegateLifeCycleListener(FlowableListener listener) { return classDelegateFactory.create(listener.getImplementation(), listener.getFieldExtensions()); } @Override public PlanItemInstanceLifecycleListener createExpressionLifeCycleListener(FlowableListener listener) { return new ExpressionPlanItemLifecycleListener(listener.getSourceState(), listener.getTargetState(), expressionManager.createExpression(listener.getImplementation())); } @Override public PlanItemInstanceLifecycleListener createDelegateExpressionLifeCycleListener(FlowableListener listener) { return new DelegateExpressionPlanItemLifecycleListener(listener.getSourceState(), listener.getTargetState(), expressionManager.createExpression(listener.getImplementation()), listener.getFieldExtensions()); } @Override
public CaseInstanceLifecycleListener createClassDelegateCaseLifeCycleListener(FlowableListener listener) { return classDelegateFactory.create(listener.getImplementation(), listener.getFieldExtensions()); } @Override public CaseInstanceLifecycleListener createExpressionCaseLifeCycleListener(FlowableListener listener) { return new ExpressionCaseLifecycleListener(listener.getSourceState(), listener.getTargetState(), expressionManager.createExpression(listener.getImplementation())); } @Override public CaseInstanceLifecycleListener createDelegateExpressionCaseLifeCycleListener(FlowableListener listener) { return new DelegateExpressionCaseLifecycleListener(listener.getSourceState(), listener.getTargetState(), expressionManager.createExpression(listener.getImplementation()), listener.getFieldExtensions()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\listener\DefaultCmmnListenerFactory.java
1
请完成以下Java代码
public class MImpExConnector extends X_ImpEx_Connector { /** * */ private static final long serialVersionUID = -4915263677859779046L; public MImpExConnector(Properties ctx, int C_ImpExConnector_ID, String trxName) { super(ctx, C_ImpExConnector_ID, trxName); } public MImpExConnector(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } private IConnector getConnector() { final String className = getImpEx_ConnectorType().getClassname(); final IConnector connector = Util.getInstance(IConnector.class, className); return connector; } public IConnector useConnector() { final IConnector connector = getConnector(); final List<MImpexConnectorParam> mParams = MImpexConnectorParam.retrieve(this); final List<Parameter> connectorParams = new ArrayList<Parameter>(mParams.size()); for (final MImpexConnectorParam mParam : mParams) { final Parameter connectorParam = new Parameter( mParam.getName(), mParam.getParamName(), mParam.getDescription(), mParam .getAD_Reference_ID(), mParam.getSeqNo()); connectorParam.setValue(mParam.getParamValue()); connectorParams.add(connectorParam); } connector.open(connectorParams); return connector; } public void createParameters() { deleteParameters(); for (final Parameter param : getConnector().getParameters()) { final MImpexConnectorParam mParam = new MImpexConnectorParam( getCtx(), 0, get_TrxName()); mParam.setParamName(param.displayName); mParam.setDescription(param.description);
mParam.setAD_Reference_ID(param.displayType); mParam.setName(param.name); mParam.setSeqNo(param.seqNo); mParam.setImpEx_Connector_ID(this.get_ID()); mParam.saveEx(); } } private void deleteParameters() { for (final MImpexConnectorParam mParam : MImpexConnectorParam.retrieve(this)) { mParam.deleteEx(false); } } @Override protected boolean beforeDelete() { deleteParameters(); return true; } @Override protected boolean afterSave(boolean newRecord, boolean success) { if (success && (newRecord || is_ValueChanged(COLUMNNAME_ImpEx_ConnectorType_ID))) { createParameters(); } return success; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\model\MImpExConnector.java
1
请在Spring Boot框架中完成以下Java代码
RSocketServerBootstrap rSocketServerBootstrap(RSocketServerFactory rSocketServerFactory, RSocketMessageHandler rSocketMessageHandler) { return new RSocketServerBootstrap(rSocketServerFactory, rSocketMessageHandler.responder()); } @Bean RSocketServerCustomizer frameDecoderRSocketServerCustomizer(RSocketMessageHandler rSocketMessageHandler) { return (server) -> { if (rSocketMessageHandler.getRSocketStrategies() .dataBufferFactory() instanceof NettyDataBufferFactory) { server.payloadDecoder(PayloadDecoder.ZERO_COPY); } }; } } static class OnRSocketWebServerCondition extends AllNestedConditions { OnRSocketWebServerCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnWebApplication(type = Type.REACTIVE) static class IsReactiveWebApplication {
} @ConditionalOnProperty(name = "spring.rsocket.server.port", matchIfMissing = true) static class HasNoPortConfigured { } @ConditionalOnProperty("spring.rsocket.server.mapping-path") static class HasMappingPathConfigured { } @ConditionalOnProperty(name = "spring.rsocket.server.transport", havingValue = "websocket") static class HasWebsocketTransportConfigured { } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketServerAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void fetchAuthorByGenreAsDtoClassQueryBuilderMechanism() { List<AuthorDto> authors = authorRepository.findBy(); authors.forEach(a -> System.out.println("Author{id=" + a.getId() + ", name=" + a.getName() + ", genre=" + a.getGenre() + ", age=" + a.getAge() + "}")); briefOverviewOfPersistentContextContent(); } private void briefOverviewOfPersistentContextContent() { org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext(); int managedEntities = persistenceContext.getNumberOfManagedEntities(); System.out.println("\n-----------------------------------"); System.out.println("Total number of managed entities: " + managedEntities); // getEntitiesByKey() will be removed and probably replaced with #iterateEntities() Map<EntityKey, Object> entitiesByKey = persistenceContext.getEntitiesByKey(); entitiesByKey.forEach((key, value) -> System.out.println(key + ": " + value));
for (Object entry : entitiesByKey.values()) { EntityEntry ee = persistenceContext.getEntry(entry); System.out.println( "Entity name: " + ee.getEntityName() + " | Status: " + ee.getStatus() + " | State: " + Arrays.toString(ee.getLoadedState())); }; System.out.println("\n-----------------------------------\n"); } private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() { SharedSessionContractImplementor sharedSession = entityManager.unwrap( SharedSessionContractImplementor.class ); return sharedSession.getPersistenceContext(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinDtoAllFields\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
private boolean isCreditMemoInvoice() { return isCreditMemoInvoice; } /** * Updates dimensions and UOM of given FactLine from invoice line */ private void updateFromInvoiceLine(@Nullable final FactLine fl) { if (fl == null) { return; } final I_C_InvoiceLine invoiceLine = getInvoiceLine(); //fl.setC_UOM_ID(firstGreaterThanZero(invoiceLine.getPrice_UOM_ID(), invoiceLine.getC_UOM_ID())); final Dimension invoiceLineDimension = services.extractDimensionFromModel(invoiceLine); fl.setFromDimension(invoiceLineDimension); } private CostAmountDetailed getCreateCostDetails(final AcctSchema as) { Check.assume(!isSOTrx(), "Cannot create cost details for sales match invoice"); final I_M_InOut receipt = getReceipt(); final Quantity qtyMatched = getQty(); final MatchInvType type = matchInv.getType(); final Money amtMatched; final CostElement costElement; if (type.isMaterial()) { amtMatched = getInvoiceLineMatchedAmt(); costElement = null; } else if (type.isCost()) { final MatchInvCostPart costPart = matchInv.getCostPartNotNull(); amtMatched = costPart.getCostAmountInvoiced(); costElement = services.getCostElementById(costPart.getCostElementId()); } else { throw new AdempiereException("Unhandled type: " + type); } return services.createCostDetail(
CostDetailCreateRequest.builder() .acctSchemaId(as.getId()) .clientId(matchInv.getClientId()) .orgId(matchInv.getOrgId()) .productId(matchInv.getProductId()) .attributeSetInstanceId(matchInv.getAsiId()) .documentRef(CostingDocumentRef.ofMatchInvoiceId(matchInv.getId())) .costElement(costElement) .qty(qtyMatched) .amt(CostAmount.ofMoney(amtMatched)) .currencyConversionContext(inOutBL.getCurrencyConversionContext(receipt)) .date(getDateAcctAsInstant()) .description(getDescription()) .build()) .getTotalAmountToPost(as); } @Nullable private CostElementId getCostElementId() { final MatchInvType type = matchInv.getType(); if (type.isMaterial()) { return null; } else if (type.isCost()) { return matchInv.getCostPartNotNull().getCostElementId(); } else { throw new AdempiereException("Unhandled type: " + type); } } } // Doc_MatchInv
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_MatchInv.java
1
请完成以下Java代码
public ProcessEngineService getProcessEngineService() { return this; } @Override public ProcessApplicationService getProcessApplicationService() { return this; } @Override public ExecutorService getExecutorService() { return serviceContainer.getServiceValue(ServiceTypes.BPM_PLATFORM, SERVICE_NAME_EXECUTOR); } // ProcessEngineServiceDelegate ////////////////////////////////////////////// @Override public ProcessEngine getDefaultProcessEngine() { return serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, "default"); } @Override public ProcessEngine getProcessEngine(String name) { return serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, name); } @Override public List<ProcessEngine> getProcessEngines() { return serviceContainer.getServiceValuesByType(ServiceTypes.PROCESS_ENGINE); } @Override public Set<String> getProcessEngineNames() { Set<String> processEngineNames = new HashSet<String>(); List<ProcessEngine> processEngines = getProcessEngines(); for (ProcessEngine processEngine : processEngines) { processEngineNames.add(processEngine.getName()); } return processEngineNames; } // process application service implementation ///////////////////////////////// @Override public Set<String> getProcessApplicationNames() { List<JmxManagedProcessApplication> processApplications = serviceContainer.getServiceValuesByType(ServiceTypes.PROCESS_APPLICATION); Set<String> processApplicationNames = new HashSet<String>(); for (JmxManagedProcessApplication jmxManagedProcessApplication : processApplications) { processApplicationNames.add(jmxManagedProcessApplication.getProcessApplicationName()); } return processApplicationNames; }
@Override public ProcessApplicationInfo getProcessApplicationInfo(String processApplicationName) { JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName); if (processApplicationService == null) { return null; } else { return processApplicationService.getProcessApplicationInfo(); } } @Override public ProcessApplicationReference getDeployedProcessApplication(String processApplicationName) { JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName); if (processApplicationService == null) { return null; } else { return processApplicationService.getProcessApplicationReference(); } } // Getter / Setter //////////////////////////////////////////////////////////// public PlatformServiceContainer getServiceContainer() { return serviceContainer; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\RuntimeContainerDelegateImpl.java
1
请完成以下Java代码
public class MForm extends X_AD_Form { /** * */ private static final long serialVersionUID = -2013533837940046638L; /** * Default Constructor * @param ctx context * @param AD_Form_ID id * @param trxName transaction */ public MForm (Properties ctx, int AD_Form_ID, String trxName)
{ super (ctx, AD_Form_ID, trxName); } // MForm /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MForm (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MForm } // MForm
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MForm.java
1
请完成以下Java代码
public void setDeployers(List<Deployer> deployers) { this.deployers = deployers; } public void deploy(final DeploymentEntity deployment) { Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() { public Void call() throws Exception { for (Deployer deployer : deployers) { deployer.deploy(deployment); } return null; } }); } public void deployOnlyGivenResourcesOfDeployment(final DeploymentEntity deployment, String... resourceNames) { initDeployment(deployment, resourceNames); Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() { public Void call() throws Exception { for (Deployer deployer : deployers) { deployer.deploy(deployment);
} return null; } }); deployment.setResources(null); } protected void initDeployment(final DeploymentEntity deployment, String... resourceNames) { deployment.clearResources(); for (String resourceName : resourceNames) { if (resourceName != null) { // with the given resource we prevent the deployment of querying // the database which means using all resources that were utilized during the deployment ResourceEntity resource = Context.getCommandContext().getResourceManager().findResourceByDeploymentIdAndResourceName(deployment.getId(), resourceName); deployment.addResource(resource); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CacheDeployer.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Preis Präzision. @param PricePrecision Precision (number of decimals) for the Price */ @Override public void setPricePrecision (int PricePrecision)
{ set_Value (COLUMNNAME_PricePrecision, Integer.valueOf(PricePrecision)); } /** Get Preis Präzision. @return Precision (number of decimals) for the Price */ @Override public int getPricePrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision); 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_PriceList.java
1
请完成以下Java代码
public class HistoricExternalTaskLogResourceImpl implements HistoricExternalTaskLogResource { protected String id; protected ProcessEngine engine; public HistoricExternalTaskLogResourceImpl(String id, ProcessEngine engine) { this.id = id; this.engine = engine; } @Override public HistoricExternalTaskLogDto getHistoricExternalTaskLog() { HistoryService historyService = engine.getHistoryService(); HistoricExternalTaskLog historicExternalTaskLog = historyService .createHistoricExternalTaskLogQuery() .logId(id) .singleResult(); if (historicExternalTaskLog == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Historic external task log with id " + id + " does not exist"); }
return HistoricExternalTaskLogDto.fromHistoricExternalTaskLog(historicExternalTaskLog); } @Override public String getErrorDetails() { try { HistoryService historyService = engine.getHistoryService(); return historyService.getHistoricExternalTaskLogErrorDetails(id); } catch (AuthorizationException e) { throw e; } catch (ProcessEngineException e) { throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\history\impl\HistoricExternalTaskLogResourceImpl.java
1