instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setUpdateQty (final @Nullable java.lang.String UpdateQty) { set_Value (COLUMNNAME_UpdateQty, UpdateQty); } @Override public java.lang.String getUpdateQty() { return get_ValueAsString(COLUMNNAME_UpdateQty); } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() {
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Inventory.java
1
请完成以下Java代码
public class PlanFragmentXmlConverter extends TaskXmlConverter { @Override public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_PLAN_FRAGMENT; } @Override protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { /* * A plan fragment does NOT have a runtime state, even though it has an associated plan item. * * From the CMMN spec: "Unlike other PlanItemDefinitions, a PlanFragment does not have a representation in run-time, * i.e., there is no notion of lifecycle tracking of a PlanFragment (not being a Stage) in the context of a Case instance. * Just the PlanItems that are contained in it are instantiated and have their lifecyles that are tracked. * * Do note that a Stage is a subclass of a PlanFragment (but this is only for plan item / sentry containment). */ PlanFragment planFragment = new PlanFragment(); planFragment.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));
planFragment.setCase(conversionHelper.getCurrentCase()); planFragment.setParent(conversionHelper.getCurrentPlanFragment()); conversionHelper.setCurrentPlanFragment(planFragment); conversionHelper.addPlanFragment(planFragment); return planFragment; } @Override protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) { super.elementEnd(xtr, conversionHelper); conversionHelper.removeCurrentPlanFragment(); } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\PlanFragmentXmlConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class HttpBearerAuth implements Authentication { private final String scheme; private String bearerToken; public HttpBearerAuth(String scheme) { this.scheme = scheme; } /** * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. * * @return The bearer token */ public String getBearerToken() { return bearerToken; } /** * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. * * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { this.bearerToken = bearerToken; }
@Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) { if (bearerToken == null) { return; } headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); } private static String upperCaseBearer(String scheme) { return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\invoker\auth\HttpBearerAuth.java
2
请完成以下Java代码
public int getLotNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_LotNo_Sequence_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintName (final java.lang.String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } @Override public java.lang.String getPrintName() { return get_ValueAsString(COLUMNNAME_PrintName); } @Override
public org.compiere.model.I_R_RequestType getR_RequestType() { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(final org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType); } @Override public void setR_RequestType_ID (final int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, R_RequestType_ID); } @Override public int getR_RequestType_ID() { return get_ValueAsInt(COLUMNNAME_R_RequestType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType.java
1
请在Spring Boot框架中完成以下Java代码
public DirectExchange effortControlExchange() { return new DirectExchange(EXCHANGE_NAME_PREFIX); } @Bean public Binding effortControlBinding() { return BindingBuilder.bind(effortControlQueue()) .to(effortControlExchange()).with(EXCHANGE_NAME_PREFIX); } @Override public String getQueueName() {
return effortControlQueue().getName(); } @Override public Optional<String> getTopicName() { return Optional.of(EVENTBUS_TOPIC.getName()); } @Override public String getExchangeName() { return effortControlExchange().getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\effort_control\EffortControlQueueConfiguration.java
2
请完成以下Java代码
private ApiRequestAuditLog createLogEntry(@NonNull final String msg, final Object... msgParameters) { final LoggableWithThrowableUtil.FormattedMsgWithAdIssueId msgAndAdIssueId = LoggableWithThrowableUtil.extractMsgAndAdIssue(msg, msgParameters); return ApiRequestAuditLog.builder() .message(msgAndAdIssueId.getFormattedMessage()) .adIssueId(msgAndAdIssueId.getAdIsueId().orElse(null)) .timestamp(SystemTime.asInstant()) .apiRequestAuditId(apiRequestAuditId) .adClientId(clientId) .userId(userId) .build(); } private ApiRequestAuditLog createLogEntry(final @NonNull ITableRecordReference recordRef, final @NonNull String type, final @Nullable String trxName) { return ApiRequestAuditLog.builder() .timestamp(SystemTime.asInstant()) .apiRequestAuditId(apiRequestAuditId) .adClientId(clientId) .userId(userId)
.recordReference(recordRef) .type(StateType.ofCode(type)) .trxName(trxName) .build(); } private void addToBuffer(final ApiRequestAuditLog logEntry) { List<ApiRequestAuditLog> buffer = this.buffer; if (buffer == null) { buffer = this.buffer = new ArrayList<>(bufferSize); } buffer.add(logEntry); if (buffer.size() >= bufferSize) { flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\ApiAuditLoggable.java
1
请完成以下Java代码
public BigDecimal getQty() { // TODO: shall we use QtyToOrder instead... but that could affect our price (if we have some prices defined on breaks) return candidate.getQtyPromised(); } @Override public void setM_PricingSystem_ID(int M_PricingSystem_ID) { candidate.setM_PricingSystem_ID(M_PricingSystem_ID); } @Override public void setM_PriceList_ID(int M_PriceList_ID) {
candidate.setM_PriceList_ID(M_PriceList_ID); } @Override public void setCurrencyId(final CurrencyId currencyId) { candidate.setC_Currency_ID(CurrencyId.toRepoId(currencyId)); } @Override public void setPrice(BigDecimal priceStd) { candidate.setPrice(priceStd); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_PurchaseCandidate.java
1
请完成以下Java代码
protected void createCamelActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createCamelActivityBehavior(serviceTask)); } protected void createShellActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createShellActivityBehavior(serviceTask)); } protected void createActivityBehaviorForCustomServiceTaskType(BpmnParse bpmnParse, ServiceTask serviceTask) { logger.warn( "Invalid service task type: '" + serviceTask.getType() + "' " + " for service task " + serviceTask.getId() ); } protected void createClassDelegateServiceTask(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createClassDelegateServiceTask(serviceTask)); } protected void createServiceTaskDelegateExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior( bpmnParse.getActivityBehaviorFactory().createServiceTaskDelegateExpressionActivityBehavior(serviceTask) );
} protected void createServiceTaskExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior( bpmnParse.getActivityBehaviorFactory().createServiceTaskExpressionActivityBehavior(serviceTask) ); } protected void createWebServiceActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createWebServiceActivityBehavior(serviceTask)); } protected void createDefaultServiceTaskActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createDefaultServiceTaskBehavior(serviceTask)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\ServiceTaskParseHandler.java
1
请完成以下Java代码
public AddResult onRecordAdded( final ITableRecordReference r, final AddResult preliminaryResult) { final PlainContextAware ctx = PlainContextAware.newWithThreadInheritedTrx(Env.getCtx()); final Object model = r.getModel(ctx); final String tableName = r.getTableName(); if (tableName.startsWith("M_HU") && !tableName.startsWith("M_HU_Assign")) { lastHUReference = r; lastHUReferenceSeen = de.metas.common.util.time.SystemTime.asDate(); } else { setSalesOrPurchaseReference(r, model); } if (getNotNullReferenceCount() > 1) { Loggables.withLogger(logger, Level.WARN).addLog("Records which do not fit together are added to the same result.\n" + "Signaling the crawler to stop! The records are:\n" + "IsSOTrx=true, seen at {}: {}\n" + "IsSOTrx=false, seen at {}: {}\n" + "HU-record, seen at {}: {}\n", lastSalesReferenceSeen, lastSalesReference, lastPurchaseReferenceSeen, lastPurchaseReference, lastHUReferenceSeen, lastHUReference); return AddResult.STOP; } return preliminaryResult; } private int getNotNullReferenceCount() { int result = 0; if (lastHUReference != null) { result++; } if (lastSalesReference != null) { result++; } if (lastPurchaseReference != null) { result++; } return result; } /** * If the given model has {@code IsSOTrx} or {@code SOTrx}, then this method set the respective members within this class. * * @param r * @param model */ private void setSalesOrPurchaseReference( final ITableRecordReference r,
final Object model) { final String soTrxColName1 = "IsSOTrx"; final String soTrxColName2 = "SOTrx"; if (!InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName1) && !InterfaceWrapperHelper.hasModelColumnName(model, soTrxColName2)) { return; } final Boolean soTrx = CoalesceUtil.coalesceSuppliers( () -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName1), () -> InterfaceWrapperHelper.getValueOrNull(model, soTrxColName2)); if (soTrx == null) { return; } if (soTrx) { lastSalesReference = r; lastSalesReferenceSeen = de.metas.common.util.time.SystemTime.asDate(); } else { lastPurchaseReference = r; lastPurchaseReferenceSeen = SystemTime.asDate(); } } @Override public String toString() { return "SalesPurchaseWatchDog [lastSalesReference=" + lastSalesReference + ", lastPurchaseReference=" + lastPurchaseReference + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\SalesPurchaseWatchDog.java
1
请在Spring Boot框架中完成以下Java代码
public C withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) { addObjectPostProcessor(objectPostProcessor); return (C) this; } /** * Allows specifying the {@link PasswordEncoder} to use with the * {@link DaoAuthenticationProvider}. The default is to use plain text. * @param passwordEncoder The {@link PasswordEncoder} to use. * @return the {@link AbstractDaoAuthenticationConfigurer} for further customizations */ @SuppressWarnings("unchecked") public C passwordEncoder(PasswordEncoder passwordEncoder) { this.provider.setPasswordEncoder(passwordEncoder); return (C) this; } public C userDetailsPasswordManager(UserDetailsPasswordService passwordManager) { this.provider.setUserDetailsPasswordService(passwordManager); return (C) this; } @Override public void configure(B builder) {
this.provider = postProcess(this.provider); builder.authenticationProvider(this.provider); } /** * Gets the {@link UserDetailsService} that is used with the * {@link DaoAuthenticationProvider} * @return the {@link UserDetailsService} that is used with the * {@link DaoAuthenticationProvider} */ @Override public U getUserDetailsService() { return this.userDetailsService; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\userdetails\AbstractDaoAuthenticationConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public DeviceToCreateMaintenances nextServiceDate(String nextServiceDate) { this.nextServiceDate = nextServiceDate; return this; } /** * Nächste Prüfung * @return nextServiceDate **/ @Schema(example = "01.12.2020", description = "Nächste Prüfung") public String getNextServiceDate() { return nextServiceDate; } public void setNextServiceDate(String nextServiceDate) { this.nextServiceDate = nextServiceDate; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeviceToCreateMaintenances deviceToCreateMaintenances = (DeviceToCreateMaintenances) o; return Objects.equals(this.maintenanceCode, deviceToCreateMaintenances.maintenanceCode) && Objects.equals(this.maintenanceInterval, deviceToCreateMaintenances.maintenanceInterval) && Objects.equals(this.lastServiceDate, deviceToCreateMaintenances.lastServiceDate) && Objects.equals(this.nextServiceDate, deviceToCreateMaintenances.nextServiceDate); } @Override public int hashCode() { return Objects.hash(maintenanceCode, maintenanceInterval, lastServiceDate, nextServiceDate); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeviceToCreateMaintenances {\n"); sb.append(" maintenanceCode: ").append(toIndentedString(maintenanceCode)).append("\n"); sb.append(" maintenanceInterval: ").append(toIndentedString(maintenanceInterval)).append("\n"); sb.append(" lastServiceDate: ").append(toIndentedString(lastServiceDate)).append("\n"); sb.append(" nextServiceDate: ").append(toIndentedString(nextServiceDate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceToCreateMaintenances.java
2
请完成以下Java代码
private void fillProcessDefinitionData(HistoryEvent event, UserOperationLogContextEntry userOperationLogContextEntry) { String processDefinitionId = userOperationLogContextEntry.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(userOperationLogContextEntry.getProcessDefinitionId()); event.setProcessDefinitionKey(userOperationLogContextEntry.getProcessDefinitionKey()); } } private void fillProcessDefinitionData(HistoryEvent event, String processDefinitionId) { ProcessDefinitionEntity entity = this.getProcessDefinitionEntity(processDefinitionId); if (entity != null) { event.setProcessDefinitionId(entity.getId()); event.setProcessDefinitionKey(entity.getKey());
event.setProcessDefinitionVersion(entity.getVersion()); event.setProcessDefinitionName(entity.getName()); } } protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) { DbEntityManager dbEntityManager = (Context.getCommandContext() != null) ? Context.getCommandContext().getDbEntityManager() : null; if (dbEntityManager != null) { return dbEntityManager .selectById(ProcessDefinitionEntity.class, processDefinitionId); } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultHistoryEventProducer.java
1
请完成以下Java代码
public String getName() { return this.name; } /** * Return the listener ids of the containers in this group. * @return the listener ids. */ public Collection<String> getListenerIds() { return this.containers.stream() .map(container -> container.getListenerId()) .map(id -> { Assert.state(id != null, "Containers must have listener ids to be used here"); return id; }) .collect(Collectors.toList()); } /** * Return true if the provided container is in this group. * @param container the container. * @return true if it is in this group. */ public boolean contains(MessageListenerContainer container) { return this.containers.contains(container); } /** * Return true if all containers in this group are stopped. * @return true if all are stopped. */ public boolean allStopped() { return this.containers.stream() .allMatch(container -> !container.isRunning()); } /** * Add one or more containers to the group. * @param theContainers the container(s). */ public void addContainers(MessageListenerContainer... theContainers) { for (MessageListenerContainer container : theContainers) { this.containers.add(container); } } /** * Remove a container from the group. * @param container the container. * @return true if the container was removed. */ public boolean removeContainer(MessageListenerContainer container) { return this.containers.remove(container); }
@Override public synchronized void start() { if (!this.running) { this.containers.forEach(container -> { LOGGER.debug(() -> "Starting: " + container); container.start(); }); this.running = true; } } @Override public synchronized void stop() { if (this.running) { this.containers.forEach(container -> container.stop()); this.running = false; } } @Override public synchronized boolean isRunning() { return this.running; } @Override public String toString() { return "ContainerGroup [name=" + this.name + ", containers=" + this.containers + "]"; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ContainerGroup.java
1
请完成以下Java代码
public void setRemunerationType (String RemunerationType) { set_Value (COLUMNNAME_RemunerationType, RemunerationType); } /** Get Remuneration Type. @return Type of Remuneration */ public String getRemunerationType () { return (String)get_Value(COLUMNNAME_RemunerationType); } /** Set Standard Hours. @param StandardHours Standard Work Hours based on Remuneration Type */ public void setStandardHours (int StandardHours)
{ set_Value (COLUMNNAME_StandardHours, Integer.valueOf(StandardHours)); } /** Get Standard Hours. @return Standard Work Hours based on Remuneration Type */ public int getStandardHours () { Integer ii = (Integer)get_Value(COLUMNNAME_StandardHours); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Remuneration.java
1
请完成以下Java代码
private IAllocationRequest createSplitAllocationRequest(final IHUContext huContext) { final ProductId productId = getProductId(); final I_C_UOM uom = productBL.getStockUOM(productId); return AllocationUtils.builder() .setHUContext(huContext) .setProduct(productId) .setQuantity(getQtyCUsPerTU(), uom) .setDate(SystemTime.asZonedDateTime()) .setFromReferencedModel(null) // N/A .setForceQtyAllocation(false) .create(); }
private void autoProcessPicking(final HuId splitCUId) { final ShipmentScheduleId shipmentScheduleId = null; pickingCandidateService.processForHUIds(ImmutableSet.of(splitCUId), shipmentScheduleId); } private HuId retrieveHUIdToSplit() { return retrieveEligibleHUEditorRows() .map(HUEditorRow::getHuId) .collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("Only one HU shall be selected"))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\process\WEBUI_HUsToPick_PickCU.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSelectType() { return selectType; } public void setSelectType(Integer selectType) { this.selectType = selectType; } public Integer getInputType() { return inputType; } public void setInputType(Integer inputType) { this.inputType = inputType; } public String getInputList() { return inputList; } public void setInputList(String inputList) { this.inputList = inputList; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public Integer getFilterType() { return filterType; } public void setFilterType(Integer filterType) { this.filterType = filterType; } public Integer getSearchType() { return searchType; } public void setSearchType(Integer searchType) { this.searchType = searchType; } public Integer getRelatedStatus() { return relatedStatus; } public void setRelatedStatus(Integer relatedStatus) { this.relatedStatus = relatedStatus; } public Integer getHandAddStatus() { return handAddStatus; } public void setHandAddStatus(Integer handAddStatus) { this.handAddStatus = handAddStatus; }
public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } @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(", productAttributeCategoryId=").append(productAttributeCategoryId); sb.append(", name=").append(name); sb.append(", selectType=").append(selectType); sb.append(", inputType=").append(inputType); sb.append(", inputList=").append(inputList); sb.append(", sort=").append(sort); sb.append(", filterType=").append(filterType); sb.append(", searchType=").append(searchType); sb.append(", relatedStatus=").append(relatedStatus); sb.append(", handAddStatus=").append(handAddStatus); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttribute.java
1
请完成以下Java代码
public final class StandardClaimNames { /** * {@code sub} - the Subject identifier */ public static final String SUB = "sub"; /** * {@code name} - the user's full name */ public static final String NAME = "name"; /** * {@code given_name} - the user's given name(s) or first name(s) */ public static final String GIVEN_NAME = "given_name"; /** * {@code family_name} - the user's surname(s) or last name(s) */ public static final String FAMILY_NAME = "family_name"; /** * {@code middle_name} - the user's middle name(s) */ public static final String MIDDLE_NAME = "middle_name"; /** * {@code nickname} - the user's nick name that may or may not be the same as the * {@code given_name} */ public static final String NICKNAME = "nickname"; /** * {@code preferred_username} - the preferred username that the user wishes to be * referred to */ public static final String PREFERRED_USERNAME = "preferred_username"; /** * {@code profile} - the URL of the user's profile page */ public static final String PROFILE = "profile"; /** * {@code picture} - the URL of the user's profile picture */ public static final String PICTURE = "picture"; /** * {@code website} - the URL of the user's web page or blog */ public static final String WEBSITE = "website"; /** * {@code email} - the user's preferred e-mail address */ public static final String EMAIL = "email"; /** * {@code email_verified} - {@code true} if the user's e-mail address has been * verified, otherwise {@code false} */ public static final String EMAIL_VERIFIED = "email_verified"; /** * {@code gender} - the user's gender */ public static final String GENDER = "gender"; /** * {@code birthdate} - the user's birth date */ public static final String BIRTHDATE = "birthdate"; /** * {@code zoneinfo} - the user's time zone
*/ public static final String ZONEINFO = "zoneinfo"; /** * {@code locale} - the user's locale */ public static final String LOCALE = "locale"; /** * {@code phone_number} - the user's preferred phone number */ public static final String PHONE_NUMBER = "phone_number"; /** * {@code phone_number_verified} - {@code true} if the user's phone number has been * verified, otherwise {@code false} */ public static final String PHONE_NUMBER_VERIFIED = "phone_number_verified"; /** * {@code address} - the user's preferred postal address */ public static final String ADDRESS = "address"; /** * {@code updated_at} - the time the user's information was last updated */ public static final String UPDATED_AT = "updated_at"; private StandardClaimNames() { } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimNames.java
1
请完成以下Java代码
public Builder setOrderId(final @Nullable OrderId orderId) { this.orderId = orderId; return this; } public Builder setIsSOTrx(final boolean isSOTrx) { this.isSOTrx = isSOTrx; return this; } public boolean isSOTrx() { return isSOTrx; } public BPartnerId getBPartnerId() { return bpartnerId; } public Builder setBPartnerId(final BPartnerId bpartnerId) { this.bpartnerId = bpartnerId; return this; } public @Nullable BankAccountId getBPartnerBankAccountId() { return bpBankAccountId; } public Builder setBPartnerBankAccountId(final @Nullable BankAccountId bpBankAccountId) { this.bpBankAccountId = bpBankAccountId; return this; } public BigDecimal getOpenAmt() { return CoalesceUtil.coalesceNotNull(_openAmt, BigDecimal.ZERO); } public Builder setOpenAmt(final BigDecimal openAmt) { this._openAmt = openAmt; return this; } public BigDecimal getPayAmt() { final BigDecimal openAmt = getOpenAmt();
final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(discountAmt); } public BigDecimal getDiscountAmt() { return CoalesceUtil.coalesceNotNull(_discountAmt, BigDecimal.ZERO); } public Builder setDiscountAmt(final BigDecimal discountAmt) { this._discountAmt = discountAmt; return this; } public BigDecimal getDifferenceAmt() { final BigDecimal openAmt = getOpenAmt(); final BigDecimal payAmt = getPayAmt(); final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(payAmt).subtract(discountAmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionLineCandidate.java
1
请完成以下Java代码
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { HumanTask task = new HumanTask(); convertCommonTaskAttributes(xtr, task); task.setAssignee(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_ASSIGNEE)); task.setOwner(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_OWNER)); task.setPriority(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_PRIORITY)); task.setFormKey(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_FORM_KEY)); String sameDeploymentAttribute = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_SAME_DEPLOYMENT); if ("false".equalsIgnoreCase(sameDeploymentAttribute)) { task.setSameDeployment(false); } task.setValidateFormFields(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_FORM_FIELD_VALIDATION)); task.setDueDate(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_DUE_DATE)); task.setCategory(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_CATEGORY));
task.setTaskIdVariableName(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_TASK_ID_VARIABLE_NAME)); task.setTaskCompleterVariableName(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_TASK_COMPLETER_VARIABLE_NAME)); String candidateUsersString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_CANDIDATE_USERS); if (StringUtils.isNotEmpty(candidateUsersString)) { task.getCandidateUsers().addAll(CmmnXmlUtil.parseDelimitedList(candidateUsersString)); } String candidateGroupsString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_CANDIDATE_GROUPS); if (StringUtils.isNotEmpty(candidateGroupsString)) { task.getCandidateGroups().addAll(CmmnXmlUtil.parseDelimitedList(candidateGroupsString)); } return task; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\HumanTaskXmlConverter.java
1
请完成以下Java代码
public void cancelFutureSchedulerTasks() { scheduledTasks.forEach((k, v) -> { if (k instanceof SpringBatchScheduler) { v.cancel(false); } }); } @Bean public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder("job", jobRepository) .start(readBooks(jobRepository, transactionManager)) .build(); } @Bean protected Step readBooks(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("readBooks", jobRepository) .<Book, Book> chunk(2, transactionManager) .reader(reader()) .writer(writer()) .build(); } @Bean public FlatFileItemReader<Book> reader() { return new FlatFileItemReaderBuilder<Book>().name("bookItemReader") .resource(new ClassPathResource("books.csv")) .delimited()
.names(new String[] { "id", "name" }) .fieldSetMapper(new BeanWrapperFieldSetMapper<>() { { setTargetType(Book.class); } }) .build(); } @Bean public ItemWriter<Book> writer() { return items -> { logger.debug("writer..." + items.size()); for (Book item : items) { logger.debug(item.toString()); } }; } public AtomicInteger getBatchRunCounter() { return batchRunCounter; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchscheduler\SpringBatchScheduler.java
1
请在Spring Boot框架中完成以下Java代码
public String getBuyerGTINTU() { return buyerGTINTU; } /** * Sets the value of the buyerGTINTU property. * * @param value * allowed object is * {@link String } * */ public void setBuyerGTINTU(String value) { this.buyerGTINTU = value; } /** * Gets the value of the buyerGTINCU property. * * @return * possible object is * {@link String } * */ public String getBuyerGTINCU() { return buyerGTINCU; } /** * Sets the value of the buyerGTINCU property. * * @param value * allowed object is * {@link String } * */ public void setBuyerGTINCU(String value) { this.buyerGTINCU = value; } /** * Gets the value of the buyerEANCU property. * * @return * possible object is * {@link String } * */ public String getBuyerEANCU() { return buyerEANCU; } /** * Sets the value of the buyerEANCU property. * * @param value * allowed object is * {@link String }
* */ public void setBuyerEANCU(String value) { this.buyerEANCU = value; } /** * Gets the value of the supplierGTINCU property. * * @return * possible object is * {@link String } * */ public String getSupplierGTINCU() { return supplierGTINCU; } /** * Sets the value of the supplierGTINCU property. * * @param value * allowed object is * {@link String } * */ public void setSupplierGTINCU(String value) { this.supplierGTINCU = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev2\de\metas\edi\esb\jaxb\metasfreshinhousev2\EDICctopInvoic500VType.java
2
请完成以下Java代码
private final static String format(int intval) { String formatted = Integer.toHexString(intval); StringBuilder buf = new StringBuilder("00000000"); buf.replace(8 - formatted.length(), 8, formatted); return buf.toString(); } private final static String format(short shortval) { String formatted = Integer.toHexString(shortval); StringBuilder buf = new StringBuilder("0000"); buf.replace(4 - formatted.length(), 4, formatted); return buf.toString(); } private final static int getJvm() { return JVM; } private final static short getCount() { synchronized (UUIDGenerator.class) { if (counter < 0) { counter = 0; } return counter++; } } /** * Unique in a local network */ private final static int getIp() { return IP; } /** * Unique down to millisecond
*/ private final static short getHiTime() { return (short) (System.currentTimeMillis() >>> 32); } private final static int getLoTime() { return (int) System.currentTimeMillis(); } private final static int toInt(byte[] bytes) { int result = 0; int length = 4; for (int i = 0; i < length; i++) { result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i]; } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\UUIDGenerator.java
1
请完成以下Java代码
public static IModelCopyHelper copy() { return new ModelCopyHelper(); } public static boolean isOldValues(@NonNull final Object model) { if (POWrapper.isHandled(model)) { return POWrapper.isOldValues(model); } else if (GridTabWrapper.isHandled(model)) { return GridTabWrapper.isOldValues(model); } else if (POJOWrapper.isHandled(model)) { return POJOWrapper.isOldValues(model); } else { throw new AdempiereException("Model wrapping is not supported for " + model + "\n Class: " + model.getClass()); } } public static void assertNotOldValues(@NonNull final Object model) { if (isOldValues(model)) { throw new AdempiereException("Model was expected to not use old values: " + model + " (" + model.getClass() + ")"); } } /** * If the given <code>model</code> is not null and has all the columns which are defined inside the given <code>clazz</code>'s {@link IModelClassInfo},<br> * then return an instance using {@link #create(Object, Class)}.<br> * Otherwise, return <code>null</code> . */ public static <T> T asColumnReferenceAwareOrNull(final Object model, final Class<T> clazz) { if (model == null) { return null; } if (clazz.isAssignableFrom(model.getClass())) { return clazz.cast(model); } final IModelClassInfo clazzInfo = ModelClassIntrospector .getInstance() .getModelClassInfo(clazz); for (final String columnName : clazzInfo.getDefinedColumnNames()) { if (!hasModelColumnName(model, columnName))
{ // not all columns of clazz are also in model => we can't do it. return null; } } return InterfaceWrapperHelper.create(model, clazz); } /** * Disables the read only (i.e. not updateable) columns enforcement. * So basically, after you are calling this method you will be able to change the values for any not updateable column. * <p> * WARNING: please make sure you know what are you doing before calling this method. If you are not sure, please don't use it. */ public static void disableReadOnlyColumnCheck(final Object model) { Check.assumeNotNull(model, "model not null"); ATTR_ReadOnlyColumnCheckDisabled.setValue(model, Boolean.TRUE); } public static final ModelDynAttributeAccessor<Object, Boolean> ATTR_ReadOnlyColumnCheckDisabled = new ModelDynAttributeAccessor<>(InterfaceWrapperHelper.class.getName(), "ReadOnlyColumnCheckDisabled", Boolean.class); public static int getFirstValidIdByColumnName(final String columnName) { return POWrapper.getFirstValidIdByColumnName(columnName); } // NOTE: public until we move everything to "org.adempiere.ad.model.util" package. public static Object checkZeroIdValue(final String columnName, final Object value) { return POWrapper.checkZeroIdValue(columnName, value); } public static boolean isCopy(final Object model) { return helpers.isCopy(model); } public static boolean isCopying(final Object model) { return helpers.isCopying(model); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\InterfaceWrapperHelper.java
1
请完成以下Java代码
public QueueBuilder singleActiveConsumer() { return withArgument("x-single-active-consumer", true); } /** * Set the queue argument to declare a queue of type 'quorum' instead of 'classic'. * @return the builder. * @since 2.2.2 */ public QueueBuilder quorum() { return withArgument("x-queue-type", "quorum"); } /** * Set the queue argument to declare a queue of type 'stream' instead of 'classic'. * @return the builder. * @since 2.4 */ public QueueBuilder stream() { return withArgument("x-queue-type", "stream"); } /** * Set the delivery limit; only applies to quorum queues. * @param limit the limit. * @return the builder. * @since 2.2.2 * @see #quorum() */ public QueueBuilder deliveryLimit(int limit) { return withArgument("x-delivery-limit", limit); } /** * Builds a final queue. * @return the Queue instance. */ public Queue build() { return new Queue(this.name, this.durable, this.exclusive, this.autoDelete, getArguments()); } /** * Overflow argument values. */ public enum Overflow { /** * Drop the oldest message. */ dropHead("drop-head"), /** * Reject the new message. */ rejectPublish("reject-publish"); private final String value; Overflow(String value) { this.value = value; } /** * Return the value.
* @return the value. */ public String getValue() { return this.value; } } /** * Locate the queue leader. * * @since 2.3.7 * */ public enum LeaderLocator { /** * Deploy on the node with the fewest queue leaders. */ minLeaders("min-masters"), /** * Deploy on the node we are connected to. */ clientLocal("client-local"), /** * Deploy on a random node. */ random("random"); private final String value; LeaderLocator(String value) { this.value = value; } /** * Return the value. * @return the value. */ public String getValue() { return this.value; } } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\QueueBuilder.java
1
请完成以下Java代码
public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = (OAuth2TokenRevocationAuthenticationToken) authentication; OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils .getAuthenticatedClientElseThrowInvalidClient(tokenRevocationAuthentication); RegisteredClient registeredClient = clientPrincipal.getRegisteredClient(); OAuth2Authorization authorization = this.authorizationService .findByToken(tokenRevocationAuthentication.getToken(), null); if (authorization == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Did not authenticate token revocation request since token was not found"); } // Return the authentication request when token not found return tokenRevocationAuthentication; } if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT); }
OAuth2Authorization.Token<OAuth2Token> token = authorization.getToken(tokenRevocationAuthentication.getToken()); authorization = OAuth2Authorization.from(authorization).invalidate(token.getToken()).build(); this.authorizationService.save(authorization); if (this.logger.isTraceEnabled()) { this.logger.trace("Saved authorization with revoked token"); // This log is kept separate for consistency with other providers this.logger.trace("Authenticated token revocation request"); } return new OAuth2TokenRevocationAuthenticationToken(token.getToken(), clientPrincipal); } @Override public boolean supports(Class<?> authentication) { return OAuth2TokenRevocationAuthenticationToken.class.isAssignableFrom(authentication); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2TokenRevocationAuthenticationProvider.java
1
请完成以下Java代码
public void processBatchEvent(@RequestBody final MSV3UserChangedBatchEvent batchEvent) { authService.handleEvent(batchEvent); } // TODO: remove this endpoint, it's only for testing/debugging @PostMapping("/toRabbitMQ") public void forwardEventToRabbitMQ(@RequestBody final MSV3UserChangedEvent event) { msv3ServerPeerService.publishUserChangedEvent(event); } @GetMapping public List<MSV3UserChangedEvent> getAllUsers() { return authService.getAllUsers()
.stream() .map(this::toMSV3UserChangedEvent) .collect(ImmutableList.toImmutableList()); } private MSV3UserChangedEvent toMSV3UserChangedEvent(final MSV3User user) { return MSV3UserChangedEvent.prepareCreatedOrUpdatedEvent(user.getMetasfreshMSV3UserId()) .username(user.getUsername()) .password("N/A") .bpartnerId(user.getBpartnerId().getBpartnerId()) .bpartnerLocationId(user.getBpartnerId().getBpartnerLocationId()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\security\sync\UserSyncRestEndpoint.java
1
请完成以下Java代码
public String getVia() { return via; } /** * Sets the value of the via property. * * @param value * allowed object is * {@link String } * */ public void setVia(String value) { this.via = value; } /** * Gets the value of the sequenceId property. * */
public int getSequenceId() { return sequenceId; } /** * Sets the value of the sequenceId property. * */ public void setSequenceId(int value) { this.sequenceId = value; } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TransportType.java
1
请完成以下Java代码
public boolean isMandatory() { return false; } @Override public int getDisplaySeqNo() { return 0; } @Override public NamePair getNullAttributeValue() { return null; }
/** * @return true; we consider Null attributes as always generated */ @Override public boolean isNew() { return true; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java
1
请在Spring Boot框架中完成以下Java代码
CommandLineRunner customMybatisMapper(final ManagementService managementService) { return new CommandLineRunner() { @Override public void run(String... args) throws Exception { String processDefinitionId = managementService.executeCustomSql(new AbstractCustomSqlExecution<CustomMybatisMapper, String>(CustomMybatisMapper.class) { @Override public String execute(CustomMybatisMapper customMybatisMapper) { return customMybatisMapper.loadProcessDefinitionIdByKey("waiter"); } }); LOGGER.info("Process definition id = {}", processDefinitionId); } }; } @Bean CommandLineRunner customMybatisXmlMapper(final ManagementService managementService) { return new CommandLineRunner() { @Override public void run(String... args) throws Exception { String processDefinitionDeploymentId = managementService.executeCommand(new Command<String>() { @Override public String execute(CommandContext commandContext) {
return (String) CommandContextUtil.getDbSqlSession() .selectOne("selectProcessDefinitionDeploymentIdByKey", "waiter"); } }); LOGGER.info("Process definition deployment id = {}", processDefinitionDeploymentId); } }; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-custom-mybatis-mapper\src\main\java\flowable\Application.java
2
请完成以下Java代码
private void changeFlatrateTermQty(@NonNull final I_C_Flatrate_Term term, @NonNull final BigDecimal qty) { term.setPlannedQtyPerUnit(qty); InterfaceWrapperHelper.save(term); invalidateInvoiceCandidatesOfFlatrateTerm(term); } private void invalidateInvoiceCandidatesOfFlatrateTerm(@NonNull final I_C_Flatrate_Term term) { Services.get(IInvoiceCandidateHandlerBL.class).invalidateCandidatesFor(term); } private void changeQtyInSubscriptionProgressOfFlatrateTerm(@NonNull final I_C_Flatrate_Term term, @NonNull final BigDecimal qty) { final ISubscriptionDAO subscriptionPA = Services.get(ISubscriptionDAO.class);
final List<I_C_SubscriptionProgress> deliveries = subscriptionPA.retrieveSubscriptionProgresses(SubscriptionProgressQuery.builder() .term(term) .excludedStatus(X_C_SubscriptionProgress.STATUS_Done) .excludedStatus(X_C_SubscriptionProgress.STATUS_Delivered) .excludedStatus(X_C_SubscriptionProgress.STATUS_InPicking) .build()); deliveries.forEach(delivery -> { delivery.setQty(qty); InterfaceWrapperHelper.save(delivery); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractChangePriceQtyService.java
1
请完成以下Java代码
private boolean isOperand(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); } private char associativity(char ch) { if (ch == '^') return 'R'; return 'L'; } public String infixToPostfix(String infix) { StringBuilder result = new StringBuilder(); Stack<Character> stack = new Stack<>(); for (int i = 0; i < infix.length(); i++) { char ch = infix.charAt(i); if (isOperand(ch)) { result.append(ch); } else if (ch == '(') { stack.push(ch); } else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') { result.append(stack.pop()); } stack.pop(); } else { while (!stack.isEmpty() && (operatorPrecedenceCondition(infix, i, stack))) { result.append(stack.pop()); } stack.push(ch); } } while (!stack.isEmpty()) { result.append(stack.pop()); } return result.toString(); } private boolean operatorPrecedenceCondition(String infix, int i, Stack<Character> stack) { return getPrecedenceScore(infix.charAt(i)) < getPrecedenceScore(stack.peek()) || getPrecedenceScore(infix.charAt(i)) == getPrecedenceScore(stack.peek()) && associativity(infix.charAt(i)) == 'L'; } }
repos\tutorials-master\core-java-modules\core-java-lang-operators-3\src\main\java\com\baeldung\infixpostfix\InfixToPostFixExpressionConversion.java
1
请完成以下Java代码
public Builder setAllowedWriteOffTypes(final Set<InvoiceWriteOffAmountType> allowedWriteOffTypes) { this.allowedWriteOffTypes.clear(); if (allowedWriteOffTypes != null) { this.allowedWriteOffTypes.addAll(allowedWriteOffTypes); } return this; } public Builder addAllowedWriteOffType(final InvoiceWriteOffAmountType allowedWriteOffType) { Check.assumeNotNull(allowedWriteOffType, "allowedWriteOffType not null"); allowedWriteOffTypes.add(allowedWriteOffType); return this; } public Builder setWarningsConsumer(final IProcessor<Exception> warningsConsumer) { this.warningsConsumer = warningsConsumer; return this; } public Builder setDocumentIdsToIncludeWhenQuering(final Multimap<AllocableDocType, Integer> documentIds) { this.documentIds = documentIds; return this; } public Builder setFilter_Payment_ID(int filter_Payment_ID) { this.filterPaymentId = filter_Payment_ID; return this;
} public Builder setFilter_POReference(String filterPOReference) { this.filterPOReference = filterPOReference; return this; } public Builder allowPurchaseSalesInvoiceCompensation(final boolean allowPurchaseSalesInvoiceCompensation) { this.allowPurchaseSalesInvoiceCompensation = allowPurchaseSalesInvoiceCompensation; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationContext.java
1
请完成以下Java代码
private Iterator<I_C_ValidCombination> retriveAccounts() { final IQueryBuilder<I_C_ValidCombination> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_C_ValidCombination.class, getCtx(), ITrx.TRXNAME_None) .addOnlyContextClient() .addOnlyActiveRecordsFilter(); queryBuilder.orderBy() .addColumn(I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID); final Iterator<I_C_ValidCombination> accounts = queryBuilder.create() .iterate(I_C_ValidCombination.class); return accounts; } /** * * @param account * @return true if updated; false if got errors (which will be logged) */ private boolean updateValueDescription(I_C_ValidCombination account) { DB.saveConstraints(); try { DB.getConstraints().addAllowedTrxNamePrefix(ITrx.TRXNAME_PREFIX_LOCAL); accountBL.setValueDescription(account); InterfaceWrapperHelper.save(account);
return true; } catch (Exception e) { addLog(account.getCombination() + ": " + e.getLocalizedMessage()); log.warn(e.getLocalizedMessage(), e); } finally { DB.restoreConstraints(); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\C_ValidCombination_UpdateDescriptionForAll.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id private int id; private String login; private String password; private Role role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() {
return password; } public void setPassword(String password) { this.password = password; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\exception\User.java
2
请完成以下Java代码
public PageData<AuditLog> findAuditLogsByTenantIdAndCustomerId(UUID tenantId, CustomerId customerId, List<ActionType> actionTypes, TimePageLink pageLink) { return DaoUtil.toPageData( auditLogRepository .findAuditLogsByTenantIdAndCustomerId( tenantId, customerId.getId(), pageLink.getTextSearch(), pageLink.getStartTime(), pageLink.getEndTime(), actionTypes, DaoUtil.toPageable(pageLink))); } @Override public PageData<AuditLog> findAuditLogsByTenantIdAndUserId(UUID tenantId, UserId userId, List<ActionType> actionTypes, TimePageLink pageLink) { return DaoUtil.toPageData( auditLogRepository .findAuditLogsByTenantIdAndUserId( tenantId, userId.getId(), pageLink.getTextSearch(), pageLink.getStartTime(), pageLink.getEndTime(), actionTypes, DaoUtil.toPageable(pageLink))); } @Override public PageData<AuditLog> findAuditLogsByTenantId(UUID tenantId, List<ActionType> actionTypes, TimePageLink pageLink) { return DaoUtil.toPageData( auditLogRepository.findByTenantId( tenantId, pageLink.getTextSearch(), pageLink.getStartTime(), pageLink.getEndTime(), actionTypes, DaoUtil.toPageable(pageLink))); } @Override public void cleanUpAuditLogs(long expTime) { partitioningRepository.dropPartitionsBefore(AUDIT_LOG_TABLE_NAME, expTime, TimeUnit.HOURS.toMillis(partitionSizeInHours));
} @Override public void createPartition(AuditLogEntity entity) { partitioningRepository.createPartitionIfNotExists(AUDIT_LOG_TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours)); } @Override protected Class<AuditLogEntity> getEntityClass() { return AuditLogEntity.class; } @Override protected JpaRepository<AuditLogEntity, UUID> getRepository() { return auditLogRepository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\audit\JpaAuditLogDao.java
1
请完成以下Java代码
public ActivityInstance[] getActivityInstances(String activityId) { EnsureUtil.ensureNotNull("activityId", activityId); List<ActivityInstance> instances = new ArrayList<ActivityInstance>(); collectActivityInstances(activityId, instances); return instances.toArray(new ActivityInstance[instances.size()]); } protected void collectActivityInstances(String activityId, List<ActivityInstance> instances) { if (this.activityId.equals(activityId)) { instances.add(this); } else { for (ActivityInstance childInstance : childActivityInstances) { ((ActivityInstanceImpl) childInstance).collectActivityInstances(activityId, instances); } } } public TransitionInstance[] getTransitionInstances(String activityId) { EnsureUtil.ensureNotNull("activityId", activityId); List<TransitionInstance> instances = new ArrayList<TransitionInstance>(); collectTransitionInstances(activityId, instances); return instances.toArray(new TransitionInstance[instances.size()]); } protected void collectTransitionInstances(String activityId, List<TransitionInstance> instances) { boolean instanceFound = false;
for (TransitionInstance childTransitionInstance : childTransitionInstances) { if (activityId.equals(childTransitionInstance.getActivityId())) { instances.add(childTransitionInstance); instanceFound = true; } } if (!instanceFound) { for (ActivityInstance childActivityInstance : childActivityInstances) { ((ActivityInstanceImpl) childActivityInstance).collectTransitionInstances(activityId, instances); } } } public void setSubProcessInstanceId(String id) { subProcessInstanceId = id; } public String getSubProcessInstanceId() { return subProcessInstanceId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ActivityInstanceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public PublicKeyCredentialUserEntity findById(Bytes id) { log.info("findById: id={}", id.toBase64UrlString()); var externalId = id.toBase64UrlString(); return userRepository.findByExternalId(externalId) .map(DbPublicKeyCredentialUserEntityRepository::mapToUserEntity) .orElse(null); } @Override public PublicKeyCredentialUserEntity findByUsername(String username) { log.info("findByUsername: username={}", username); return userRepository.findByName(username) .map(DbPublicKeyCredentialUserEntityRepository::mapToUserEntity) .orElse(null); } @Override public void save(PublicKeyCredentialUserEntity userEntity) { log.info("save: username={}, externalId={}", userEntity.getName(),userEntity.getId().toBase64UrlString()); var entity = userRepository.findByExternalId(userEntity.getId().toBase64UrlString()) .orElse(new PasskeyUser()); entity.setExternalId(userEntity.getId().toBase64UrlString());
entity.setName(userEntity.getName()); entity.setDisplayName(userEntity.getDisplayName()); userRepository.save(entity); } @Override public void delete(Bytes id) { log.info("delete: id={}", id.toBase64UrlString()); userRepository.findByExternalId(id.toBase64UrlString()) .ifPresent(userRepository::delete); } private static PublicKeyCredentialUserEntity mapToUserEntity(PasskeyUser user) { return ImmutablePublicKeyCredentialUserEntity.builder() .id(Bytes.fromBase64(user.getExternalId())) .name(user.getName()) .displayName(user.getDisplayName()) .build(); } }
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\repository\DbPublicKeyCredentialUserEntityRepository.java
2
请完成以下Java代码
public static HistoricIncidentDto fromHistoricIncident(HistoricIncident historicIncident) { HistoricIncidentDto dto = new HistoricIncidentDto(); dto.id = historicIncident.getId(); dto.processDefinitionKey = historicIncident.getProcessDefinitionKey(); dto.processDefinitionId = historicIncident.getProcessDefinitionId(); dto.processInstanceId = historicIncident.getProcessInstanceId(); dto.executionId = historicIncident.getExecutionId(); dto.createTime = historicIncident.getCreateTime(); dto.endTime = historicIncident.getEndTime(); dto.incidentType = historicIncident.getIncidentType(); dto.failedActivityId = historicIncident.getFailedActivityId(); dto.activityId = historicIncident.getActivityId(); dto.causeIncidentId = historicIncident.getCauseIncidentId(); dto.rootCauseIncidentId = historicIncident.getRootCauseIncidentId();
dto.configuration = historicIncident.getConfiguration(); dto.historyConfiguration = historicIncident.getHistoryConfiguration(); dto.incidentMessage = historicIncident.getIncidentMessage(); dto.open = historicIncident.isOpen(); dto.deleted = historicIncident.isDeleted(); dto.resolved = historicIncident.isResolved(); dto.tenantId = historicIncident.getTenantId(); dto.jobDefinitionId = historicIncident.getJobDefinitionId(); dto.removalTime = historicIncident.getRemovalTime(); dto.rootProcessInstanceId = historicIncident.getRootProcessInstanceId(); dto.annotation = historicIncident.getAnnotation(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIncidentDto.java
1
请完成以下Java代码
public class DLM_Partition_Migrate extends JavaProcess { @Param(mandatory = true, parameterName = "IsTest") private boolean testMigrate; private final IMigratorService migratorService = Services.get(IMigratorService.class); private final IDLMService dlmService = Services.get(IDLMService.class); @RunOutOfTrx @Override protected String doIt() throws Exception { final IQueryBL queryBL = Services.get(IQueryBL.class); final ITrxItemProcessorExecutorService trxItemProcessorExecutorService = Services.get(ITrxItemProcessorExecutorService.class); // gh #1955: prevent an OutOfMemoryError final IQueryFilter<I_DLM_Partition> processFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final Iterator<I_DLM_Partition> partitionsToMigrate = queryBL.createQueryBuilder(I_DLM_Partition.class, this) .addOnlyActiveRecordsFilter() .addNotEqualsFilter(I_DLM_Partition.COLUMN_Target_DLM_Level, null) .addNotEqualsFilter(I_DLM_Partition.COLUMN_Target_DLM_Level, IMigratorService.DLM_Level_NOT_SET) .addNotEqualsFilter(I_DLM_Partition.COLUMN_Target_DLM_Level, ModelColumnNameValue.forColumn(I_DLM_Partition.COLUMN_Current_DLM_Level)) .filter(processFilter) .orderBy().addColumn(I_DLM_Partition.COLUMNNAME_DLM_Partition_ID).endOrderBy() .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .setOption(IQuery.OPTION_IteratorBufferSize, 500) .iterate(I_DLM_Partition.class); trxItemProcessorExecutorService.<I_DLM_Partition, Void> createExecutor() .setContext(getCtx(), getTrxName()) .setProcessor(new TrxItemProcessorAdapter<I_DLM_Partition, Void>() { @Override
public void process(final I_DLM_Partition partitionDB) throws Exception { process0(partitionDB); } }) .setExceptionHandler(LoggableTrxItemExceptionHandler.instance) .process(partitionsToMigrate); return MSG_OK; } private void process0(final I_DLM_Partition partitionDB) { final Partition partition = dlmService.loadPartition(partitionDB); if (testMigrate) { migratorService.testMigratePartition(partition); return; } final Partition migratedPartition = migratorService.migratePartition(partition); addLog("Migrated partition={} with result={}", partition, migratedPartition); dlmService.storePartition(migratedPartition, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\migrator\process\DLM_Partition_Migrate.java
1
请完成以下Java代码
public Optional<TemplateDefinition> findCandidateTemplateForTask(String taskUUID) { return templates.findCandidateTemplateForTask(taskUUID); } public VariableDefinition getProperty(String propertyUUID) { return properties != null ? properties.get(propertyUUID) : null; } public VariableDefinition getPropertyByName(String name) { if (properties != null) { for (Map.Entry<String, VariableDefinition> variableDefinition : properties.entrySet()) { if (variableDefinition.getValue() != null) { if (Objects.equals(variableDefinition.getValue().getName(), name)) { return variableDefinition.getValue(); } } } } return null; } public boolean hasMapping(String taskId) { return mappings.get(taskId) != null; } public boolean shouldMapAllInputs(String elementId) { ProcessVariablesMapping processVariablesMapping = mappings.get(elementId); return ( processVariablesMapping.getMappingType() != null && (processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_INPUTS) || processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL)) ); }
public boolean shouldMapAllOutputs(String elementId) { ProcessVariablesMapping processVariablesMapping = mappings.get(elementId); return ( processVariablesMapping.getMappingType() != null && (processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_OUTPUTS) || processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL)) ); } public TemplatesDefinition getTemplates() { return templates; } public void setTemplates(TemplatesDefinition templates) { this.templates = templates; } public Map<String, AssignmentDefinition> getAssignments() { return assignments; } public void setAssignments(Map<String, AssignmentDefinition> assignments) { this.assignments = assignments; } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\Extension.java
1
请完成以下Java代码
public void setAD_UI_Section(org.compiere.model.I_AD_UI_Section AD_UI_Section) { set_ValueFromPO(COLUMNNAME_AD_UI_Section_ID, org.compiere.model.I_AD_UI_Section.class, AD_UI_Section); } /** Set UI Section. @param AD_UI_Section_ID UI Section */ @Override public void setAD_UI_Section_ID (int AD_UI_Section_ID) { if (AD_UI_Section_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, Integer.valueOf(AD_UI_Section_ID)); } /** Get UI Section. @return UI Section */ @Override public int getAD_UI_Section_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Section_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Column.java
1
请完成以下Java代码
public abstract class AbstractResourceProvider<T extends Query<?, U>, U, DTO> { protected String id; protected ProcessEngine engine; public AbstractResourceProvider(String detailId, ProcessEngine engine) { this.id = detailId; this.engine = engine; } @GET @Produces(MediaType.APPLICATION_JSON) public DTO getResource(@QueryParam(VariableResource.DESERIALIZE_VALUE_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValue) { U variableInstance = baseQueryForVariable(deserializeObjectValue).singleResult(); if (variableInstance != null) { return transformToDto(variableInstance); } else { throw new InvalidRequestException(Status.NOT_FOUND, getResourceNameForErrorMessage() + " with Id '" + id + "' does not exist."); } } @GET @Path("/data") public Response getResourceBinary() { U queryResult = baseQueryForBinaryVariable().singleResult(); if (queryResult != null) { TypedValue variableInstance = transformQueryResultIntoTypedValue(queryResult); return new VariableResponseProvider().getResponseForTypedVariable(variableInstance, id); } else { throw new InvalidRequestException(Status.NOT_FOUND, getResourceNameForErrorMessage() + " with Id '" + id + "' does not exist."); } } protected String getId() { return id; }
protected ProcessEngine getEngine() { return engine; } /** * Create the query we need for fetching the desired result. Setting * properties in the query like disableCustomObjectDeserialization() or * disableBinaryFetching() should be done in this method. */ protected abstract Query<T, U> baseQueryForBinaryVariable(); /** * TODO change comment Create the query we need for fetching the desired * result. Setting properties in the query like * disableCustomObjectDeserialization() or disableBinaryFetching() should be * done in this method. * * @param deserializeObjectValue */ protected abstract Query<T, U> baseQueryForVariable(boolean deserializeObjectValue); protected abstract TypedValue transformQueryResultIntoTypedValue(U queryResult); protected abstract DTO transformToDto(U queryResult); protected abstract String getResourceNameForErrorMessage(); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\AbstractResourceProvider.java
1
请在Spring Boot框架中完成以下Java代码
public AnonymousConfigurer<H> authorities(String... authorities) { return authorities(AuthorityUtils.createAuthorityList(authorities)); } /** * Sets the {@link AuthenticationProvider} used to validate an anonymous user. If this * is set, no attributes on the {@link AnonymousConfigurer} will be set on the * {@link AuthenticationProvider}. * @param authenticationProvider the {@link AuthenticationProvider} used to validate * an anonymous user. Default is {@link AnonymousAuthenticationProvider} * @return the {@link AnonymousConfigurer} for further customization of anonymous * authentication */ public AnonymousConfigurer<H> authenticationProvider(AuthenticationProvider authenticationProvider) { this.authenticationProvider = authenticationProvider; return this; } /** * Sets the {@link AnonymousAuthenticationFilter} used to populate an anonymous user. * If this is set, no attributes on the {@link AnonymousConfigurer} will be set on the * {@link AnonymousAuthenticationFilter}. * @param authenticationFilter the {@link AnonymousAuthenticationFilter} used to * populate an anonymous user. * @return the {@link AnonymousConfigurer} for further customization of anonymous * authentication */ public AnonymousConfigurer<H> authenticationFilter(AnonymousAuthenticationFilter authenticationFilter) { this.authenticationFilter = authenticationFilter; return this; }
@Override public void init(H http) { if (this.authenticationProvider == null) { this.authenticationProvider = new AnonymousAuthenticationProvider(getKey()); } this.authenticationProvider = postProcess(this.authenticationProvider); http.authenticationProvider(this.authenticationProvider); } @Override public void configure(H http) { if (this.authenticationFilter == null) { this.authenticationFilter = new AnonymousAuthenticationFilter(getKey(), this.principal, this.authorities); } this.authenticationFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); this.authenticationFilter.afterPropertiesSet(); http.addFilter(this.authenticationFilter); } private String getKey() { if (this.computedKey != null) { return this.computedKey; } if (this.key == null) { this.computedKey = UUID.randomUUID().toString(); } else { this.computedKey = this.key; } return this.computedKey; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AnonymousConfigurer.java
2
请完成以下Java代码
public List<String> extractSuffix(int length, int size, boolean extend) { TFDictionary suffixTreeSet = new TFDictionary(); for (String key : tfDictionary.keySet()) { if (key.length() > length) { suffixTreeSet.add(key.substring(key.length() - length, key.length())); if (extend) { for (int l = 1; l < length; ++l) { suffixTreeSet.add(key.substring(key.length() - l, key.length())); } } } } if (extend) { size *= length; } return extract(suffixTreeSet, size); } private static List<String> extract(TFDictionary suffixTreeSet, int size) { List<String> suffixList = new ArrayList<String>(size); for (TermFrequency termFrequency : suffixTreeSet.values()) { if (suffixList.size() >= size) break; suffixList.add(termFrequency.getKey()); } return suffixList; } /** * 此方法认为后缀一定是整个的词语,所以length是以词语为单位的 * @param length * @param size * @param extend * @return */ public List<String> extractSuffixByWords(int length, int size, boolean extend) { TFDictionary suffixTreeSet = new TFDictionary(); for (String key : tfDictionary.keySet()) { List<Term> termList = StandardTokenizer.segment(key); if (termList.size() > length) {
suffixTreeSet.add(combine(termList.subList(termList.size() - length, termList.size()))); if (extend) { for (int l = 1; l < length; ++l) { suffixTreeSet.add(combine(termList.subList(termList.size() - l, termList.size()))); } } } } return extract(suffixTreeSet, size); } private static String combine(List<Term> termList) { StringBuilder sbResult = new StringBuilder(); for (Term term : termList) { sbResult.append(term.word); } return sbResult.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\CommonSuffixExtractor.java
1
请完成以下Java代码
private StorageType getStorageType(final ClientId adClientId) { final I_AD_Client client = clientDAO.getById(adClientId); if (client.isStoreArchiveOnFileSystem()) { return StorageType.Filesystem; } else { return StorageType.Database; } } private StorageType getStorageType(final I_AD_Archive archive) { if (archive.isFileSystem()) { return StorageType.Filesystem; } else { return StorageType.Database; } } private AccessMode getAccessMode() { if (Ini.isSwingClient()) { return AccessMode.CLIENT; } else { return AccessMode.SERVER; } } @Override public IArchiveStorage getArchiveStorage(final Properties ctx) { final ClientId adClientId = Env.getClientId(ctx); final StorageType storageType = getStorageType(adClientId); final AccessMode accessMode = getAccessMode(); return getArchiveStorage(adClientId, storageType, accessMode); } @Override public IArchiveStorage getArchiveStorage(final I_AD_Archive archive) { final ClientId adClientId = ClientId.ofRepoId(archive.getAD_Client_ID()); final StorageType storageType = getStorageType(archive); final AccessMode accessMode = getAccessMode(); return getArchiveStorage(adClientId, storageType, accessMode); } private IArchiveStorage getArchiveStorage( final ClientId adClientId, final StorageType storageType, final AccessMode accessMode) { final ArchiveStorageKey key = ArchiveStorageKey.of(adClientId, storageType, accessMode); return archiveStorages.getOrLoad(key, this::createArchiveStorage); }
private IArchiveStorage createArchiveStorage(@NonNull final ArchiveStorageKey key) { final Class<? extends IArchiveStorage> storageClass = getArchiveStorageClass(key.getStorageType(), key.getAccessMode()); try { final IArchiveStorage storage = storageClass.newInstance(); storage.init(key.getClientId()); return storage; } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e) .appendParametersToMessage() .setParameter("storageClass", storageClass); } } @Override public IArchiveStorage getArchiveStorage(final Properties ctx, final StorageType storageType) { final ClientId adClientId = Env.getClientId(ctx); final AccessMode accessMode = getAccessMode(); return getArchiveStorage(adClientId, storageType, accessMode); } @Override public IArchiveStorage getArchiveStorage(final Properties ctx, final StorageType storageType, final AccessMode accessMode) { final ClientId adClientId = Env.getClientId(ctx); return getArchiveStorage(adClientId, storageType, accessMode); } /** * Remove all registered {@link IArchiveStorage} classes. * <p> * NOTE: to be used only in testing */ public void removeAllArchiveStorages() { storageClasses.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveStorageFactory.java
1
请在Spring Boot框架中完成以下Java代码
protected void validateDataImpl(TenantId tenantId, OtaPackage otaPackage) { validateImpl(otaPackage); if (!otaPackage.hasUrl()) { if (StringUtils.isEmpty(otaPackage.getFileName())) { throw new DataValidationException("OtaPackage file name should be specified!"); } if (StringUtils.isEmpty(otaPackage.getContentType())) { throw new DataValidationException("OtaPackage content type should be specified!"); } if (otaPackage.getChecksumAlgorithm() == null) { throw new DataValidationException("OtaPackage checksum algorithm should be specified!"); } if (StringUtils.isEmpty(otaPackage.getChecksum())) { throw new DataValidationException("OtaPackage checksum should be specified!"); } String currentChecksum; currentChecksum = otaPackageService.generateChecksum(otaPackage.getChecksumAlgorithm(), otaPackage.getData()); if (!currentChecksum.equals(otaPackage.getChecksum())) { throw new DataValidationException("Wrong otaPackage file!"); } } else { if (otaPackage.getData() != null) { throw new DataValidationException("File can't be saved if URL present!");
} } } @Override protected OtaPackage validateUpdate(TenantId tenantId, OtaPackage otaPackage) { OtaPackage otaPackageOld = otaPackageDao.findById(tenantId, otaPackage.getUuidId()); validateUpdate(otaPackage, otaPackageOld); if (otaPackageOld.getData() != null && !otaPackageOld.getData().equals(otaPackage.getData())) { throw new DataValidationException("Updating otaPackage data is prohibited!"); } if (otaPackageOld.getData() == null && otaPackage.getData() != null) { DefaultTenantProfileConfiguration profileConfiguration = (DefaultTenantProfileConfiguration) tenantProfileCache.get(tenantId).getProfileData().getConfiguration(); long maxOtaPackagesInBytes = profileConfiguration.getMaxOtaPackagesInBytes(); validateMaxSumDataSizePerTenant(tenantId, otaPackageDao, maxOtaPackagesInBytes, otaPackage.getDataSize(), OTA_PACKAGE); } return otaPackageOld; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\OtaPackageDataValidator.java
2
请在Spring Boot框架中完成以下Java代码
public class EdgeBulkImportService extends AbstractBulkImportService<Edge> { private final EdgeService edgeService; private final TbEdgeService tbEdgeService; private final RuleChainService ruleChainService; @Override protected void setEntityFields(Edge entity, Map<BulkImportColumnType, String> fields) { ObjectNode additionalInfo = getOrCreateAdditionalInfoObj(entity); fields.forEach((columnType, value) -> { switch (columnType) { case NAME: entity.setName(value); break; case TYPE: entity.setType(value); break; case LABEL: entity.setLabel(value); break; case DESCRIPTION: additionalInfo.set("description", new TextNode(value)); break; case ROUTING_KEY: entity.setRoutingKey(value); break; case SECRET: entity.setSecret(value); break; } });
entity.setAdditionalInfo(additionalInfo); } @SneakyThrows @Override protected Edge saveEntity(SecurityUser user, Edge entity, Map<BulkImportColumnType, String> fields) { RuleChain edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(user.getTenantId()); return tbEdgeService.save(entity, edgeTemplateRootRuleChain, user); } @Override protected Edge findOrCreateEntity(TenantId tenantId, String name) { return Optional.ofNullable(edgeService.findEdgeByTenantIdAndName(tenantId, name)) .orElseGet(Edge::new); } @Override protected void setOwners(Edge entity, SecurityUser user) { entity.setTenantId(user.getTenantId()); entity.setCustomerId(user.getCustomerId()); } @Override protected EntityType getEntityType() { return EntityType.EDGE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\EdgeBulkImportService.java
2
请完成以下Java代码
public void setR_IssueRecommendation_ID (int R_IssueRecommendation_ID) { if (R_IssueRecommendation_ID < 1) set_Value (COLUMNNAME_R_IssueRecommendation_ID, null); else set_Value (COLUMNNAME_R_IssueRecommendation_ID, Integer.valueOf(R_IssueRecommendation_ID)); } /** Get Issue Recommendation. @return Recommendations how to fix an Issue */ public int getR_IssueRecommendation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueRecommendation_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_IssueStatus getR_IssueStatus() throws RuntimeException { return (I_R_IssueStatus)MTable.get(getCtx(), I_R_IssueStatus.Table_Name) .getPO(getR_IssueStatus_ID(), get_TrxName()); } /** Set Issue Status. @param R_IssueStatus_ID Status of an Issue */ public void setR_IssueStatus_ID (int R_IssueStatus_ID) { if (R_IssueStatus_ID < 1) set_Value (COLUMNNAME_R_IssueStatus_ID, null); else set_Value (COLUMNNAME_R_IssueStatus_ID, Integer.valueOf(R_IssueStatus_ID)); } /** Get Issue Status. @return Status of an Issue */ public int getR_IssueStatus_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueStatus_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_Request getR_Request() throws RuntimeException { return (I_R_Request)MTable.get(getCtx(), I_R_Request.Table_Name) .getPO(getR_Request_ID(), get_TrxName()); } /** Set Request. @param R_Request_ID Request from a Business Partner or Prospect */ public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); }
/** Get Request. @return Request from a Business Partner or Prospect */ public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Source Class. @param SourceClassName Source Class Name */ public void setSourceClassName (String SourceClassName) { set_Value (COLUMNNAME_SourceClassName, SourceClassName); } /** Get Source Class. @return Source Class Name */ public String getSourceClassName () { return (String)get_Value(COLUMNNAME_SourceClassName); } /** Set Source Method. @param SourceMethodName Source Method Name */ public void setSourceMethodName (String SourceMethodName) { set_Value (COLUMNNAME_SourceMethodName, SourceMethodName); } /** Get Source Method. @return Source Method Name */ public String getSourceMethodName () { return (String)get_Value(COLUMNNAME_SourceMethodName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueKnown.java
1
请完成以下Java代码
public Map<String, String> getEnvironment() { return this.environment; } public Set<Integer> getPorts() { return this.ports; } public String getCommand() { return this.command; } public Map<String, String> getLabels() { return this.labels; } /** * Builder for {@link ComposeService}. */ public static class Builder { private final String name; private String image; private String imageTag = "latest"; private String imageWebsite; private final Map<String, String> environment = new TreeMap<>(); private final Set<Integer> ports = new TreeSet<>(); private String command; private final Map<String, String> labels = new TreeMap<>(); protected Builder(String name) { this.name = name; } public Builder imageAndTag(String imageAndTag) { String[] split = imageAndTag.split(":", 2); String tag = (split.length == 1) ? "latest" : split[1]; return image(split[0]).imageTag(tag); } public Builder image(String image) { this.image = image; return this; } public Builder imageTag(String imageTag) { this.imageTag = imageTag; return this; } public Builder imageWebsite(String imageWebsite) { this.imageWebsite = imageWebsite; return this; }
public Builder environment(String key, String value) { this.environment.put(key, value); return this; } public Builder environment(Map<String, String> environment) { this.environment.putAll(environment); return this; } public Builder ports(Collection<Integer> ports) { this.ports.addAll(ports); return this; } public Builder ports(int... ports) { return ports(Arrays.stream(ports).boxed().toList()); } public Builder command(String command) { this.command = command; return this; } public Builder label(String key, String value) { this.labels.put(key, value); return this; } public Builder labels(Map<String, String> label) { this.labels.putAll(label); return this; } /** * Builds the {@link ComposeService} instance. * @return the built instance */ public ComposeService build() { return new ComposeService(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeService.java
1
请完成以下Java代码
public class DuplicateCheckController { @Autowired ISysDictService sysDictService; /** * 校验数据是否在系统中是否存在 * * @return */ @RequestMapping(value = "/check", method = RequestMethod.GET) @Operation(summary="重复校验接口") public Result<String> doDuplicateCheck(DuplicateCheckVo duplicateCheckVo, HttpServletRequest request) { log.debug("----duplicate check------:"+ duplicateCheckVo.toString()); // 1.填值为空,直接返回 if(StringUtils.isEmpty(duplicateCheckVo.getFieldVal())){ Result rs = new Result(); rs.setCode(500); rs.setSuccess(true); rs.setMessage("数据为空,不作处理!");
return rs; } // 2.返回结果 if (sysDictService.duplicateCheckData(duplicateCheckVo)) { // 该值可用 return Result.ok("该值可用!"); } else { // 该值不可用 log.info("该值不可用,系统中已存在!"); return Result.error("该值不可用,系统中已存在!"); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\DuplicateCheckController.java
1
请在Spring Boot框架中完成以下Java代码
class Metadata { @NonNull Type type; @NonNull String className; @NonNull String functionName; @Nullable String windowNameAndId; boolean isGroupingPlaceholder; @Singular Map<String, String> labels; public String getFunctionNameFQ() {return className + " - " + functionName;} } enum Type { MODEL_INTERCEPTOR("modelInterceptor"), DOC_ACTION("docAction"), ASYNC_WORKPACKAGE("asyncWorkPackage"), SCHEDULER("scheduler"), EVENTBUS_REMOTE_ENDPOINT("eventbus-remote-endpoint"), REST_CONTROLLER("rest-controller"),
REST_CONTROLLER_WITH_WINDOW_ID("rest-controller-with-windowId"), PO("po"), DB("db"); Type(final String code) { this.code = code; } public boolean isAnyRestControllerType() { return this == Type.REST_CONTROLLER || this == Type.REST_CONTROLLER_WITH_WINDOW_ID; } @Getter private final String code; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\PerformanceMonitoringService.java
2
请在Spring Boot框架中完成以下Java代码
public class UnitType { @XmlValue protected BigDecimal value; @XmlAttribute(name = "Unit", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact") protected String unit; /** * Gets the value of the value property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; }
/** * The type of unit. ERPEL recommends the use of code list UN/ECE recommendation 20. Note, that ERPEL supports both representations for piece: PCE and C62. A list of valid codes may be found under https://docs.ecosio.com/files/Measure_Unit_Qualifiers_6411.pdf * * @return * possible object is * {@link String } * */ public String getUnit() { return unit; } /** * Sets the value of the unit property. * * @param value * allowed object is * {@link String } * */ public void setUnit(String value) { this.unit = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\UnitType.java
2
请完成以下Java代码
public String customers(Principal principal, Model model) { addCustomers(); Iterable<Customer> customers = customerDAO.findAll(); model.addAttribute("customers", customers); model.addAttribute("username", principal.getName()); return "customers"; } // add customers for demonstration public void addCustomers() { Customer customer1 = new Customer(); customer1.setAddress("1111 foo blvd"); customer1.setName("Foo Industries"); customer1.setServiceRendered("Important services");
customerDAO.save(customer1); Customer customer2 = new Customer(); customer2.setAddress("2222 bar street"); customer2.setName("Bar LLP"); customer2.setServiceRendered("Important services"); customerDAO.save(customer2); Customer customer3 = new Customer(); customer3.setAddress("33 main street"); customer3.setName("Big LLC"); customer3.setServiceRendered("Important services"); customerDAO.save(customer3); } }
repos\tutorials-master\spring-boot-modules\spring-boot-keycloak-adapters\src\main\java\com\baeldung\keycloak\WebController.java
1
请在Spring Boot框架中完成以下Java代码
public class PersonModule extends AbstractModule { @Provides PersonController personController(PersonService personService) { return new PersonController(personService); } @Provides PersonService personService(PersonRepository personRepository) { return new PersonService(personRepository); } @Provides PersonRepository personRepository(DataSource dataSource) { return new PersonRepository(dataSource); } @Provides DataSource dataSource() { return new DataSource() { @Override public Connection getConnection() throws SQLException { return null; } @Override public Connection getConnection(String username, String password) throws SQLException { return null; } @Override public PrintWriter getLogWriter() throws SQLException { return null;
} @Override public void setLogWriter(PrintWriter out) throws SQLException { } @Override public void setLoginTimeout(int seconds) throws SQLException { } @Override public int getLoginTimeout() throws SQLException { return 0; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }; } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\activej\config\PersonModule.java
2
请完成以下Java代码
public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; }
public static void main(String[] args) { String content = "test"; String password = "12345678"; // 加密 System.out.println("加密前:" + content); byte[] encryptResult = encrypt(content, password); String encryptResultStr = parseByte2HexStr(encryptResult); System.out.println("加密后:" + encryptResultStr); // 解密 byte[] decryptFrom = parseHexStr2Byte(encryptResultStr); byte[] decryptResult = decrypt(decryptFrom, password); System.out.println("解密后:" + new String(decryptResult)); String enStr = encryptString("123", "@#&^%-$#@Coupon#$%^&@*"); System.out.println(enStr); System.out.println(decrypt("2DA4A4EEA4777CB2CC342815FC84B539", "@#&^%-$#@Coupon#$%^&@*")); } }
repos\spring-boot-student-master\spring-boot-student-encode\src\main\java\com\xiaolyuh\utils\AESUtil.java
1
请完成以下Java代码
public void setName(String name) { this.name = name; } public void setVersion(Integer version) { this.version = version; } public void setProjectReleaseVersion(String projectReleaseVersion) { this.projectReleaseVersion = projectReleaseVersion; } @Override public String getName() { return name; } @Override public Integer getVersion() {
return version; } @Override public String getProjectReleaseVersion() { return projectReleaseVersion; } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\DeploymentImpl.java
1
请完成以下Java代码
private void cuToExistingCU(@NonNull final I_M_HU sourceCuHU, @NonNull final I_M_HU targetHU) { trxManager.runInThreadInheritedTrx(() -> cuToExistingCU_InTrx(sourceCuHU, targetHU)); } private void cuToExistingCU_InTrx( @NonNull final I_M_HU sourceCuHU, @NonNull final I_M_HU targetHU) { final IMutableHUContext huContextWithOrgId = huContextFactory.createMutableHUContext(InterfaceWrapperHelper.getContextAware(targetHU)); final List<IHUProductStorage> productStorages = huContext.getHUStorageFactory() .getStorage(targetHU) .getProductStorages(); if (productStorages.size() > 1) { throw new AdempiereException("CUs with more than one product are not supported!"); } final IAllocationSource source = HUListAllocationSourceDestination .of(sourceCuHU, AllocationStrategyType.UNIFORM) .setDestroyEmptyHUs(true); final IAllocationDestination destination = HUListAllocationSourceDestination.of(targetHU, AllocationStrategyType.UNIFORM); final IHUProductStorage sourceProductStorage = getSingleProductStorage(sourceCuHU); final ProductId targetHUProductId = productStorages.isEmpty() ? sourceProductStorage.getProductId()
: productStorages.get(0).getProductId(); Check.assume(sourceProductStorage.getProductId().equals(targetHUProductId), "Source and Target HU productId must match!"); HULoader.of(source, destination) .load(AllocationUtils.builder() .setHUContext(huContextWithOrgId) .setDateAsToday() .setProduct(sourceProductStorage.getProductId()) .setQuantity(sourceProductStorage.getQtyInStockingUOM()) .setFromReferencedModel(sourceCuHU) .setForceQtyAllocation(true) .create()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\HUTransformService.java
1
请完成以下Java代码
public IRfQResponseProducer newRfQResponsesProducerFor(final I_C_RfQ rfq) { Check.assumeNotNull(rfq, "rfq not null"); final IRfQResponseProducer producer = rfqResponsesProducerFactory.newRfQResponsesProducerFor(rfq); if (producer != null) { return producer; } // Fallback to default producer return new DefaultRfQResponseProducer(); } @Override public IRfQConfiguration addRfQResponsesProducerFactory(final IRfQResponseProducerFactory factory) { rfqResponsesProducerFactory.addRfQResponsesProducerFactory(factory); return this; }
@Override public IRfQResponseRankingStrategy newRfQResponseRankingStrategyFor(final I_C_RfQ rfq) { // TODO: implement custom providers return new DefaultRfQResponseRankingStrategy(); } @Override public IRfQResponsePublisher getRfQResponsePublisher() { return rfqResponsePublisher; } @Override public IRfQConfiguration addRfQResponsePublisher(final IRfQResponsePublisher publisher) { rfqResponsePublisher.addRfQResponsePublisher(publisher); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfQConfiguration.java
1
请完成以下Java代码
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 setProductId(Long productId) { this.productId = productId; } public Long getMemberLevelId() { return memberLevelId; } public void setMemberLevelId(Long memberLevelId) { this.memberLevelId = memberLevelId; } public BigDecimal getMemberPrice() { return memberPrice; } public void setMemberPrice(BigDecimal memberPrice) { this.memberPrice = memberPrice; } public String getMemberLevelName() { return memberLevelName; } public void setMemberLevelName(String memberLevelName) { this.memberLevelName = memberLevelName; } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", memberLevelId=").append(memberLevelId); sb.append(", memberPrice=").append(memberPrice); sb.append(", memberLevelName=").append(memberLevelName); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsMemberPrice.java
1
请完成以下Java代码
protected String doIt() throws Exception { final IShipmentSchedulePA shipmentSchedulePA = Services.get(IShipmentSchedulePA.class); final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class); final IQueryFilter<I_M_ShipmentSchedule> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); IQueryBuilder<I_M_ShipmentSchedule> queryBuilderForShipmentScheduleSelection = shipmentSchedulePA.createQueryForShipmentScheduleSelection(getCtx(), userSelectionFilter); // TODO: filter for picking candidates! final Iterator<I_M_ShipmentSchedule> schedulesToUpdateIterator = queryBuilderForShipmentScheduleSelection .addEqualsFilter(I_M_ShipmentSchedule.COLUMNNAME_QtyPickList, BigDecimal.ZERO) .create() .iterate(I_M_ShipmentSchedule.class);
if (!schedulesToUpdateIterator.hasNext()) { throw new AdempiereException("@NoSelection@"); } while (schedulesToUpdateIterator.hasNext()) { final I_M_ShipmentSchedule schedule = schedulesToUpdateIterator.next(); shipmentScheduleBL.closeShipmentSchedule(schedule); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_CloseShipmentSchedules.java
1
请完成以下Java代码
public static class PlanItemInstanceByStageInstanceIdAndPlanItemIdCachedEntityMatcher extends CachedEntityMatcherAdapter<PlanItemInstanceEntity> { @Override public boolean isRetained(PlanItemInstanceEntity entity, Object param) { Map<String, Object> map = (Map<String, Object>) param; String stageInstanceId = (String) map.get("stageInstanceId"); String planItemId = (String) map.get("planItemId"); return stageInstanceId.equals(entity.getStageInstanceId()) && entity.getPlanItem() != null && planItemId.equals(entity.getPlanItem().getId()); } } public static class PlanItemInstanceByStagePlanItemInstanceIdCachedEntityMatcher extends CachedEntityMatcherAdapter<PlanItemInstanceEntity> { @Override public boolean isRetained(PlanItemInstanceEntity entity, Object param) { String stagePlanItemInstanceId = (String) param; return stagePlanItemInstanceId.equals(entity.getStageInstanceId()); } } public static class PlanItemInstanceByCaseInstanceIdAndTypeAndStateCachedEntityMatcher extends CachedEntityMatcherAdapter<PlanItemInstanceEntity> { @Override @SuppressWarnings("unchecked") public boolean isRetained(PlanItemInstanceEntity entity, Object param) { Map<String, Object> map = (Map<String, Object>) param; String caseInstanceId = (String) map.get("caseInstanceId"); List<String> planItemDefinitionTypes = (List<String>) map.get("planItemDefinitionTypes"); List<String> states = (List<String>) map.get("states"); boolean ended = (boolean) map.get("ended"); return caseInstanceId.equals(entity.getCaseInstanceId()) && (planItemDefinitionTypes == null || planItemDefinitionTypes.contains(entity.getPlanItemDefinitionType())) && (states == null || states.contains(entity.getState()))
&& (ended ? entity.getEndedTime() != null : entity.getEndedTime() == null); } } protected void setSafeInValueLists(PlanItemInstanceQueryImpl planItemInstanceQuery) { if (planItemInstanceQuery.getInvolvedGroups() != null) { planItemInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(planItemInstanceQuery.getInvolvedGroups())); } if(planItemInstanceQuery.getCaseInstanceIds() != null) { planItemInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(planItemInstanceQuery.getCaseInstanceIds())); } if (planItemInstanceQuery.getOrQueryObjects() != null && !planItemInstanceQuery.getOrQueryObjects().isEmpty()) { for (PlanItemInstanceQueryImpl oInstanceQuery : planItemInstanceQuery.getOrQueryObjects()) { setSafeInValueLists(oInstanceQuery); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisPlanItemInstanceDataManagerImpl.java
1
请完成以下Java代码
private boolean isDeliveryDateMatching(final PickingJobReference pickingJobReference) { final ZonedDateTime deliveryDate = pickingJobReference.getDeliveryDate(); return deliveryDate != null && isDeliveryDateMatching(deliveryDate.toLocalDate()); } private boolean isDeliveryDateMatching(final LocalDate deliveryDay) {return deliveryDays.isEmpty() || deliveryDays.contains(deliveryDay);} private boolean isHandoverLocationMatching(final PickingJobReference pickingJobReference) {return isHandoverLocationMatching(Optional.ofNullable(pickingJobReference.getHandoverLocationId()).orElse(pickingJobReference.getDeliveryBPLocationId()));} private boolean isHandoverLocationMatching(final BPartnerLocationId handoverLocationId) {return handoverLocationIds.isEmpty() || handoverLocationIds.contains(handoverLocationId);} public Facets retainFacetsOfGroup(@NonNull final PickingJobFacetGroup group) {return PickingJobFacetHandlers.retainFacetsOfGroups(this, ImmutableSet.of(group));} public Set<Facets> toSingleElementFacets()
{ if (isEmpty()) { return ImmutableSet.of(); } return Streams.concat( customerIds.stream().map(customerId -> Facets.builder().customerId(customerId).build()), deliveryDays.stream().map(deliveryDay -> Facets.builder().deliveryDay(deliveryDay).build()), handoverLocationIds.stream().map(handoverLocationId -> Facets.builder().handoverLocationId(handoverLocationId).build()) ) .collect(ImmutableSet.toImmutableSet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobQuery.java
1
请完成以下Java代码
public class PvmAtomicOperationTransitionNotifyListenerStart extends PvmAtomicOperationActivityInstanceStart { protected ScopeImpl getScope(PvmExecutionImpl execution) { return execution.getActivity(); } protected String getEventName() { return ExecutionListener.EVENTNAME_START; } protected void eventNotificationsCompleted(PvmExecutionImpl execution) { super.eventNotificationsCompleted(execution); TransitionImpl transition = execution.getTransition(); PvmActivity destination; if (transition == null) { // this is null after async cont. -> transition is not stored in execution destination = execution.getActivity(); } else { destination = transition.getDestination(); } execution.setTransition(null); execution.setActivity(destination);
if (execution.isProcessInstanceStarting()) { // only call this method if we are currently in the starting phase; // if not, this may make an unnecessary request to fetch the process // instance from the database execution.setProcessInstanceStarting(false); } execution.dispatchDelayedEventsAndPerformOperation(ACTIVITY_EXECUTE); } public String getCanonicalName() { return "transition-notifiy-listener-start"; } @Override public boolean shouldHandleFailureAsBpmnError() { return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationTransitionNotifyListenerStart.java
1
请完成以下Java代码
public int getId() { return id.get(); } public IntegerProperty idProperty() { return id; } public void setId(int id) { this.id.set(id); } public String getName() { return name.get(); } public StringProperty nameProperty() { return name; } public void setName(String name) { this.name.set(name); } public boolean getIsEmployed() { return isEmployed.get();
} public BooleanProperty isEmployedProperty() { return isEmployed; } public void setIsEmployed(boolean isEmployed) { this.isEmployed.set(isEmployed); } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", isEmployed=" + isEmployed + '}'; } }
repos\tutorials-master\javafx\src\main\java\com\baeldung\model\Person.java
1
请在Spring Boot框架中完成以下Java代码
public class TaskCommentResource extends TaskBaseResource { @ApiOperation(value = " Get a comment on a task", tags = { "Task Comments" }, nickname = "getTaskComment") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the task and comment were found and the comment is returned."), @ApiResponse(code = 404, message = "Indicates the requested task was not found or the tasks does not have a comment with the given ID.") }) @GetMapping(value = "/runtime/tasks/{taskId}/comments/{commentId}", produces = "application/json") public CommentResponse getComment(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "commentId") @PathVariable("commentId") String commentId) { HistoricTaskInstance task = getHistoricTaskFromRequest(taskId); Comment comment = taskService.getComment(commentId); if (comment == null || !task.getId().equals(comment.getTaskId())) { throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have a comment with id '" + commentId + "'.", Comment.class); } return restResponseFactory.createRestComment(comment); } @ApiOperation(value = "Delete a comment on a task", tags = { "Task Comments" }, nickname = "deleteTaskComment", code = 204) @ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the task and comment were found and the comment is deleted. Response body is left empty intentionally."), @ApiResponse(code = 404, message = "Indicates the requested task was not found or the tasks does not have a comment with the given ID.") }) @DeleteMapping(value = "/runtime/tasks/{taskId}/comments/{commentId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteComment(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "commentId") @PathVariable("commentId") String commentId) { // Check if task exists Task task = getTaskFromRequestWithoutAccessCheck(taskId); Comment comment = taskService.getComment(commentId); if (comment == null || comment.getTaskId() == null || !comment.getTaskId().equals(task.getId())) { throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have a comment with id '" + commentId + "'.", Comment.class); } if (restApiInterceptor != null) { restApiInterceptor.deleteTaskComment(task, comment); } taskService.deleteComment(commentId); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskCommentResource.java
2
请完成以下Java代码
public int powerOf10(int n){ if (n == 0){ return 1; } return powerOf10(n-1)*10; } public int fibonacci(int n){ if (n <=1 ){ return n; } return fibonacci(n-1) + fibonacci(n-2); } public String toBinary(int n){ if (n <= 1 ){ return String.valueOf(n); }
return toBinary(n / 2) + String.valueOf(n % 2); } public int calculateTreeHeight(BinaryNode root){ if (root!= null){ if (root.getLeft() != null || root.getRight() != null){ return 1 + max(calculateTreeHeight(root.left) , calculateTreeHeight(root.right)); } } return 0; } public int max(int a,int b){ return a>b ? a:b; } }
repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\recursion\RecursionExample.java
1
请在Spring Boot框架中完成以下Java代码
public ApiResponse<PatientNoteMapping> patientNotePatchWithHttpInfo(String apiKey, String id, PatientNote body) throws ApiException { com.squareup.okhttp.Call call = patientNotePatchValidateBeforeCall(apiKey, id, body, null, null); Type localVarReturnType = new TypeToken<PatientNoteMapping>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * PatientenNotiz ändern (asynchronously) * Szenario - das WaWi ändert eine PatientenNotiz in Alberta * @param apiKey (required) * @param id Id des Patienten in Alberta (required) * @param body patientNote to update (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call patientNotePatchAsync(String apiKey, String id, PatientNote body, final ApiCallback<PatientNoteMapping> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = patientNotePatchValidateBeforeCall(apiKey, id, body, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<PatientNoteMapping>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\PatientNoteApi.java
2
请完成以下Java代码
int getLoad(int S_Resource_ID, Timestamp start, Timestamp end) { int load = 0; String sql = "SELECT SUM( CASE WHEN ow.DurationUnit = 's' THEN 1 * (onode.QueuingTime + onode.SetupTime + (onode.Duration * (o.QtyOrdered - o.QtyDelivered - o.QtyScrap)) + onode.MovingTime + onode.WaitingTime) WHEN ow.DurationUnit = 'm' THEN 60 * (onode.QueuingTime + onode.SetupTime + (onode.Duration * (o.QtyOrdered - o.QtyDelivered - o.QtyScrap)) + onode.MovingTime + onode.WaitingTime) WHEN ow.DurationUnit = 'h' THEN 3600 * (onode.QueuingTime + onode.SetupTime + (onode.Duration * (o.QtyOrdered - o.QtyDelivered - o.QtyScrap)) + onode.MovingTime + onode.WaitingTime) WHEN ow.DurationUnit = 'Y' THEN 31536000 * (onode.QueuingTime + onode.SetupTime + (onode.Duration * (o.QtyOrdered - o.QtyDelivered - o.QtyScrap)) + onode.MovingTime + onode.WaitingTime) WHEN ow.DurationUnit = 'M' THEN 2592000 * (onode.QueuingTime + onode.SetupTime + (onode.Duration * (o.QtyOrdered - o.QtyDelivered - o.QtyScrap)) + onode.MovingTime + onode.WaitingTime) WHEN ow.DurationUnit = 'D' THEN 86400 END ) AS Load FROM PP_Order_Node onode INNER JOIN PP_Order_Workflow ow ON (ow.PP_Order_Workflow_ID = onode.PP_Order_Workflow_ID) INNER JOIN PP_Order o ON (o.PP_Order_ID = onode.PP_Order_ID) WHERE onode. = ? AND onode.DateStartSchedule => ? AND onode.DateFinishSchedule =< ? AND onode.AD_Client_ID = ?" ; try { PreparedStatement pstmt = null; pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt.setInt(1, S_Resource_ID); pstmt.setTimestamp(1, start); pstmt.setTimestamp(2, end); pstmt.setInt(3,AD_Client_ID); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { load = rs.getInt(1); } rs.close(); pstmt.close(); return load; } catch (Exception e) { log.error("doIt - " + sql, e); } return 0; } private class Col { int Day = 0; String From = null; String To = null; int Capacity = 0; int Load = 0; int Summary = 0; public Col() { } void setDays(int day) { Day = day; } int getDays() { return Day; } void setCapacity(int capacity) { Capacity = capacity; } int getCapacity() { return Capacity; } void setLoad(int load) { Load = load; }
int getLoad() { return Load; } int getDifference() { return Capacity - Load; } void setSummary(int summary) { Summary = summary; } int getSummary() { return Summary; } void setFrom(String from) { From = from; } String getFrom() { return From; } void setTo(String to) { To = to; } String getTo() { return To; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CRPSummary.java
1
请完成以下Java代码
public int getAD_ChangeLog_Config_ID() { return get_ValueAsInt(COLUMNNAME_AD_ChangeLog_Config_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() {
return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setKeepChangeLogsDays (final int KeepChangeLogsDays) { set_Value (COLUMNNAME_KeepChangeLogsDays, KeepChangeLogsDays); } @Override public int getKeepChangeLogsDays() { return get_ValueAsInt(COLUMNNAME_KeepChangeLogsDays); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog_Config.java
1
请完成以下Java代码
public void onAttributeValueCreated(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); final Object valueOld = null; final Object valueNew = attributeValue.getValue(); calloutExecutor.executeCallout(attributeValueContext, storage, attribute, valueOld, valueNew); } @Override public void onAttributeValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue, final Object valueOld) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); final Object valueNew = attributeValue.getValue(); calloutExecutor.executeCallout(attributeValueContext, storage, attribute, valueOld, valueNew); }
@Override public void onAttributeValueDeleted(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); final Object valueOld = attributeValue.getValue(); final Object valueNew = null; calloutExecutor.executeCallout(attributeValueContext, storage, attribute, valueOld, valueNew); } @Override public String toString() { return "CalloutAttributeStorageListener [calloutExecutor=" + calloutExecutor + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CalloutAttributeStorageListener.java
1
请在Spring Boot框架中完成以下Java代码
public class BPRelationId implements RepoIdAware { int repoId; @JsonCreator public static BPRelationId ofRepoId(final int repoId) { return new BPRelationId(repoId); } @Nullable public static BPRelationId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new BPRelationId(repoId) : null; } @Nullable public static BPRelationId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new BPRelationId(repoId) : null; } public static Optional<BPRelationId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final BPRelationId bpartnerId)
{ return toRepoIdOr(bpartnerId, -1); } public static int toRepoIdOr(@Nullable final BPRelationId bpartnerId, final int defaultValue) { return bpartnerId != null ? bpartnerId.getRepoId() : defaultValue; } private BPRelationId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_BP_Relation_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(final BPRelationId o1, final BPRelationId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPRelationId.java
2
请完成以下Java代码
default <K> ListMultimap<K, T> listMultimap(@NonNull Function<T, K> keyFunction) {return listMultimap(getModelClass(), keyFunction);} /** * Retrieves the records and then splits them in groups based on the indexing key provided by <code>keyFunction</code>. * * @param keyFunction key function used to provide the key used to split the returned records. * @return collection of record groups. */ <K, ET extends T> Collection<List<ET>> listAndSplit(Class<ET> modelClass, Function<ET, K> keyFunction); /** * "Appends" the given {@code query} to {@code this} query be joined as UNION ALL/DISTINCT. * <p> * WARNING: atm, the implementation is minimal and was tested only with {@link #list()} methods. */ void addUnion(IQuery<T> query, boolean distinct); default IQuery<T> addUnions(final Collection<IQuery<T>> queries, final boolean distinct) { queries.forEach(query -> addUnion(query, distinct)); return this; } /** * @return UNION DISTINCT {@link IQuery} reducer */ static <T> BinaryOperator<IQuery<T>> unionDistict() { return (previousDBQuery, dbQuery) -> { if (previousDBQuery == null) { return dbQuery; } else { previousDBQuery.addUnion(dbQuery, true); return previousDBQuery; } }; } /** * Creates a NEW selection from this query result. * * @return selection's or <code>null</code> if there were no records matching */ PInstanceId createSelection(); /** * Appends this query result to an existing selection. * * @param pinstanceId selection ID to be used * @return number of records inserted in selection */ int createSelection(PInstanceId pinstanceId); /** * Use the result of this query and insert it in given <code>toModelClass</code>'s table. * * @return executor which will assist you with the INSERT. */ <ToModelType> IQueryInsertExecutor<ToModelType, T> insertDirectlyInto(Class<ToModelType> toModelClass); /** * Return a stream of all records that match the query criteria.
*/ default Stream<T> stream() throws DBException { return list().stream(); } default Stream<T> iterateAndStream() throws DBException { final Iterator<T> iterator = iterate(getModelClass()); final boolean parallel = false; return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), parallel); } default <ID extends RepoIdAware> Stream<ID> iterateAndStreamIds(@NonNull final IntFunction<ID> idMapper) throws DBException { final Iterator<ID> iterator = iterateIds(idMapper); final boolean parallel = false; return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), parallel); } /** * Return a stream of all records that match the query criteria. * * @param clazz all resulting models will be converted to this interface * @return Stream */ default <ET extends T> Stream<ET> stream(final Class<ET> clazz) throws DBException { return list(clazz).stream(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\IQuery.java
1
请在Spring Boot框架中完成以下Java代码
public <R> R updateById( @NonNull final SAPGLJournalId id, @NonNull Function<SAPGLJournal, R> processor) { final SAPGLJournal glJournal = getById(id); final R result = processor.apply(glJournal); save(glJournal); return result; } public DocStatus getDocStatus(final SAPGLJournalId glJournalId) { return getHeaderRecordByIdIfExists(glJournalId) .map(headerRecord -> DocStatus.ofNullableCodeOrUnknown(headerRecord.getDocStatus())) .orElse(DocStatus.Unknown); } @NonNull SAPGLJournal create( @NonNull final SAPGLJournalCreateRequest createRequest, @NonNull final SAPGLJournalCurrencyConverter currencyConverter) { final I_SAP_GLJournal headerRecord = InterfaceWrapperHelper.newInstance(I_SAP_GLJournal.class); headerRecord.setTotalDr(createRequest.getTotalAcctDR().toBigDecimal()); headerRecord.setTotalCr(createRequest.getTotalAcctCR().toBigDecimal()); headerRecord.setC_DocType_ID(createRequest.getDocTypeId().getRepoId()); headerRecord.setC_AcctSchema_ID(createRequest.getAcctSchemaId().getRepoId()); headerRecord.setPostingType(createRequest.getPostingType().getCode()); headerRecord.setAD_Org_ID(createRequest.getOrgId().getRepoId()); headerRecord.setDescription(createRequest.getDescription()); headerRecord.setDocStatus(DocStatus.Drafted.getCode()); final SAPGLJournalCurrencyConversionCtx conversionCtx = createRequest.getConversionCtx(); headerRecord.setAcct_Currency_ID(conversionCtx.getAcctCurrencyId().getRepoId()); headerRecord.setC_Currency_ID(conversionCtx.getCurrencyId().getRepoId()); headerRecord.setC_ConversionType_ID(CurrencyConversionTypeId.toRepoId(conversionCtx.getConversionTypeId())); Optional.ofNullable(conversionCtx.getFixedConversionRate())
.ifPresent(fixedConversionRate -> headerRecord.setCurrencyRate(fixedConversionRate.getMultiplyRate())); headerRecord.setDateAcct(TimeUtil.asTimestamp(createRequest.getDateDoc())); headerRecord.setDateDoc(TimeUtil.asTimestamp(createRequest.getDateDoc())); headerRecord.setGL_Category_ID(createRequest.getGlCategoryId().getRepoId()); headerRecord.setReversal_ID(SAPGLJournalId.toRepoId(createRequest.getReversalId())); saveRecord(headerRecord); final SAPGLJournal createdJournal = fromRecord(headerRecord, ImmutableList.of()); createRequest.getLines() .forEach(createLineRequest -> createdJournal.addLine(createLineRequest, currencyConverter)); save(createdJournal); return createdJournal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalLoaderAndSaver.java
2
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } /** * 获取字典数据 * * @return */ public static List<DictModel> getDictList() { List<DictModel> list = new ArrayList<>(); DictModel dictModel = null; for (MessageTypeEnum e : MessageTypeEnum.values()) { dictModel = new DictModel(); dictModel.setValue(e.getType()); dictModel.setText(e.getNote()); list.add(dictModel); } return list; }
/** * 根据type获取枚举 * * @param type * @return */ public static MessageTypeEnum valueOfType(String type) { for (MessageTypeEnum e : MessageTypeEnum.values()) { if (e.getType().equals(type)) { return e; } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\MessageTypeEnum.java
1
请在Spring Boot框架中完成以下Java代码
public class ResourceEndpoint { @GetMapping(value = "/default/users/{name}") public ResponseEntity<UserDto> getUserWithDefaultCaching(@PathVariable String name) { return ResponseEntity.ok(new UserDto(name)); } @GetMapping("/users/{name}") public ResponseEntity<UserDto> getUser(@PathVariable String name) { return ResponseEntity .ok() .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) .body(new UserDto(name)); } @GetMapping("/timestamp")
public ResponseEntity<TimestampDto> getServerTimestamp() { return ResponseEntity .ok() .cacheControl(CacheControl.noStore()) .body(new TimestampDto(LocalDateTime .now() .toInstant(ZoneOffset.UTC) .toEpochMilli())); } @GetMapping("/private/users/{name}") public ResponseEntity<UserDto> getUserNotCached(@PathVariable String name) { return ResponseEntity .ok() .body(new UserDto(name)); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\cachecontrol\ResourceEndpoint.java
2
请完成以下Java代码
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; }
public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\customhtml\Course.java
1
请完成以下Java代码
public DocumentFilterDescriptorsProvider createFiltersProvider(@NonNull final CreateFiltersProviderContext context) { final String tableName = StringUtils.trimBlankToNull(context.getTableName()); final AdTabId adTabId = context.getAdTabId(); if (tableName == null || adTabId == null) { return NullDocumentFilterDescriptorsProvider.instance; } final AdTableId adTableId = adTablesRepo.retrieveAdTableId(tableName); final List<IUserQueryField> searchFields = context.getFields() .stream() .map(UserQueryDocumentFilterDescriptorsProviderFactory::createUserQueryField) .collect(ImmutableList.toImmutableList()); final UserQueryRepository repository = UserQueryRepository.builder() .setAD_Tab_ID(adTabId.getRepoId()) .setAD_Table_ID(adTableId.getRepoId()) .setAD_User_ID(UserId.METASFRESH.getRepoId()) // FIXME: hardcoded, see https://github.com/metasfresh/metasfresh-webui/issues/162 .setSearchFields(searchFields) .setColumnDisplayTypeProvider(POInfo.getPOInfoNotNull(tableName))
.build(); return new UserQueryDocumentFilterDescriptorsProvider(repository); } private static UserQueryField createUserQueryField(final DocumentFieldDescriptor field) { return UserQueryField.builder() .columnName(field.getFieldName()) .displayName(field.getCaption()) .widgetType(field.getWidgetType()) // TODO: use a lookup descriptor without validation rules with params .lookupDescriptor(field.getLookupDescriptorForFiltering()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\userQuery\UserQueryDocumentFilterDescriptorsProviderFactory.java
1
请完成以下Java代码
public final class PackageableList implements Iterable<Packageable> { public static PackageableList EMPTY = new PackageableList(ImmutableList.of()); private final ImmutableList<Packageable> list; private PackageableList(@NonNull final Collection<Packageable> list) { this.list = list.stream() .sorted(Comparator.comparing(Packageable::getShipmentScheduleId)) // keep them ordered by shipmentScheduleId which is usually the order line ordering .collect(ImmutableList.toImmutableList()); } public static PackageableList ofCollection(final Collection<Packageable> list) { return !list.isEmpty() ? new PackageableList(list) : EMPTY; } public static PackageableList of(final Packageable... arr) { return ofCollection(ImmutableList.copyOf(arr)); } public static Collector<Packageable, ?, PackageableList> collect() { return GuavaCollectors.collectUsingListAccumulator(PackageableList::ofCollection); } public boolean isEmpty() {return list.isEmpty();} public int size() {return list.size();} public Stream<Packageable> stream() {return list.stream();} @Override 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代码
private I_M_ProductScalePrice createScalePrice(final String trxName) { return InterfaceWrapperHelper.newInstance(I_M_ProductScalePrice.class, PlainContextAware.newWithTrxName(Env.getCtx(), trxName)); } /** * Returns an existing scale price or (if <code>createNew</code> is true) creates a new one. */ @Nullable @Override public I_M_ProductScalePrice retrieveOrCreateScalePrices( final int productPriceId, final BigDecimal qty, final boolean createNew, final String trxName) { final PreparedStatement pstmt = DB.prepareStatement( SQL_SCALEPRICE_FOR_QTY, trxName); ResultSet rs = null; try { pstmt.setInt(1, productPriceId); pstmt.setBigDecimal(2, qty); pstmt.setMaxRows(1); rs = pstmt.executeQuery(); if (rs.next()) { logger.debug("Returning existing instance for M_ProductPrice " + productPriceId + " and quantity " + qty); return new X_M_ProductScalePrice(Env.getCtx(), rs, trxName); } if (createNew)
{ logger.debug("Returning new instance for M_ProductPrice " + productPriceId + " and quantity " + qty); final I_M_ProductScalePrice newInstance = createScalePrice(trxName); newInstance.setM_ProductPrice_ID(productPriceId); newInstance.setQty(qty); return newInstance; } return null; } catch (final SQLException e) { throw new DBException(e, SQL_SCALEPRICE_FOR_QTY); } finally { DB.close(rs, pstmt); } } @Override public I_M_ProductScalePrice retrieveScalePrices(final int productPriceId, final BigDecimal qty, final String trxName) { return retrieveOrCreateScalePrices(productPriceId, qty, false, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\ProductPA.java
1
请完成以下Java代码
public Date getDueDate() { return dueDate; } public Date getDueBefore() { return dueBefore; } public Date getDueAfter() { return dueAfter; } public boolean isWithoutDueDate() { return withoutDueDate; } public SuspensionState getSuspensionState() { return suspensionState; } public boolean isIncludeTaskLocalVariables() { return includeTaskLocalVariables; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isBothCandidateAndAssigned() { return bothCandidateAndAssigned; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase;
} public String getDescriptionLikeIgnoreCase() { return descriptionLikeIgnoreCase; } public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getLocale() { return locale; } public boolean isOrActive() { return orActive; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
class AddToColumnQueryUpdater<T> implements ISqlQueryUpdater<T> { private final String columnName; private final BigDecimal value; private final IQueryFilter<T> onlyWhenFilter; public AddToColumnQueryUpdater(final String columnName, final BigDecimal value, @Nullable final IQueryFilter<T> onlyWhenFilter) { Check.assumeNotEmpty(columnName, "columnName not empty"); this.columnName = columnName; Check.assumeNotNull(value, "value not null"); this.value = value; this.onlyWhenFilter = onlyWhenFilter; } @Override public String getSql(final Properties ctx, final List<Object> params) { final StringBuilder sql = new StringBuilder(); final StringBuilder sqlEnding = new StringBuilder(); sql.append(columnName).append("="); if (onlyWhenFilter == null) { // nothing } else if (onlyWhenFilter instanceof ISqlQueryFilter) { final ISqlQueryFilter onlyWhenSqlFilter = ISqlQueryFilter.cast(onlyWhenFilter); sql.append("(CASE WHEN ").append(onlyWhenSqlFilter.getSql()).append(" THEN ");
params.addAll(onlyWhenSqlFilter.getSqlParams(ctx)); // sqlEnding.append(" ELSE ").append(columnName).append(" END)"); } else { throw new DBException("Cannot convert filter to SQL: "+onlyWhenFilter); } sql.append(columnName).append(" + ?").append(sqlEnding); params.add(value); return sql.toString(); } @Override public boolean update(final T model) { if (onlyWhenFilter != null && !onlyWhenFilter.accept(model)) { return MODEL_SKIPPED; // not updated } BigDecimal valueOld = InterfaceWrapperHelper.getValueOrNull(model, columnName); if(valueOld == null) { valueOld = BigDecimal.ZERO; } final BigDecimal valueNew = valueOld.add(value); return InterfaceWrapperHelper.setValue(model, columnName, valueNew); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AddToColumnQueryUpdater.java
1
请完成以下Java代码
public void init (int WindowNo, FormFrame frame) { log.debug(""); m_WindowNo = WindowNo; m_frame = frame; try { // Top Selection Panel // m_frame.getContentPane().add(selectionPanel, BorderLayout.NORTH); // Center initPanel(); CScrollPane scroll = new CScrollPane (this); m_frame.getContentPane().add(scroll, BorderLayout.CENTER); // South confirmPanel.setActionListener(this); m_frame.getContentPane().add(confirmPanel, BorderLayout.SOUTH); } catch(Exception e) { log.error("", e); } sizeIt(); } // init /** * Size Window */ private void sizeIt() { // Frame m_frame.pack(); // Dimension size = m_frame.getPreferredSize(); // size.width = WINDOW_WIDTH; // m_frame.setSize(size); } // size /** * Dispose */ @Override public void dispose() { if (m_frame != null) m_frame.dispose(); m_frame = null; removeAll(); } // dispose /** Window No */ private int m_WindowNo = 0; /** FormFrame */ private FormFrame m_frame; /** Logger */ private static Logger log = LogManager.getLogger(ViewPI.class); /** Confirmation Panel */ private ConfirmPanel confirmPanel = ConfirmPanel.newWithOK(); /**
* Init Panel */ private void initPanel() { BoxLayout layout = new BoxLayout(this, BoxLayout.PAGE_AXIS); MGoal[] goals = MGoal.getGoals(Env.getCtx()); for (int i = 0; i < goals.length; i++) { PerformanceIndicator pi = new PerformanceIndicator(goals[i]); pi.addActionListener(this); add (pi); } } // initPanel /** * Action Listener for Drill Down * @param e event */ @Override public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals(ConfirmPanel.A_OK)) dispose(); else if (e.getSource() instanceof PerformanceIndicator) { PerformanceIndicator pi = (PerformanceIndicator)e.getSource(); log.info(pi.getName()); MGoal goal = pi.getGoal(); if (goal.getMeasure() != null) new PerformanceDetail(goal); } } // actionPerformed } // ViewPI
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\ViewPI.java
1
请完成以下Java代码
public void updateTable(final I_DLM_Partition_Config_Reference ref) { if (ref.getDLM_Referencing_Column_ID() <= 0) { ref.setDLM_Referenced_Table_ID(0); return; } final I_AD_Column adColumn = ref.getDLM_Referencing_Column(); final int displayType = adColumn.getAD_Reference_ID(); if (!DisplayType.isLookup(displayType)) { return; } final ADReferenceService adReferenceService = ADReferenceService.get(); final ADRefTable tableRefInfo; final ReferenceId adReferenceValueId = ReferenceId.ofRepoIdOrNull(adColumn.getAD_Reference_Value_ID()); if (adReferenceService.isTableReference(adReferenceValueId)) { tableRefInfo = adReferenceService.retrieveTableRefInfo(adReferenceValueId); }
else { final String columnName = adColumn.getColumnName(); tableRefInfo = adReferenceService.getTableDirectRefInfo(columnName); } if (tableRefInfo == null) { // what we do further up is not very sophisticated. e.g. for "CreatedBy", we currently don't find the table name. // therefore, don't set the table to null since we don't know that there is no table for the given column // ref.setDLM_Referenced_Table_ID(0); return; } final IADTableDAO adTableDAO = Services.get(IADTableDAO.class); ref.setDLM_Referenced_Table_ID(adTableDAO.retrieveTableId(tableRefInfo.getTableName())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\DLM_Partition_Config_Reference.java
1
请在Spring Boot框架中完成以下Java代码
public void setLabel(String label) { this.label = label; } public Region parent(String parent) { this.parent = parent; return this; } /** * Id der übergeordneten Region * @return parent **/ @Schema(example = "5afc1d30b37364c26e9ca501", description = "Id der übergeordneten Region") public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public Region 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; } Region region = (Region) o; return Objects.equals(this._id, region._id) &&
Objects.equals(this.label, region.label) && Objects.equals(this.parent, region.parent) && Objects.equals(this.timestamp, region.timestamp); } @Override public int hashCode() { return Objects.hash(_id, label, parent, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Region {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" label: ").append(toIndentedString(label)).append("\n"); sb.append(" parent: ").append(toIndentedString(parent)).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\Region.java
2
请在Spring Boot框架中完成以下Java代码
public class CCacheConfigDefaults { public static final CCacheConfigDefaults DEFAULTS = builder() .cacheMapType(CCache.CacheMapType.LRU) .initialCapacity(0) .maximumSize(1000) .expireMinutes(0) .captureStacktrace(false) .build(); @NonNull CCache.CacheMapType cacheMapType; int initialCapacity; int maximumSize; int expireMinutes; boolean captureStacktrace;
private static final String PROPERTY_PREFIX = "metasfresh.cache.defaults."; public static CCacheConfigDefaults computeFrom(@NonNull final SpringContextHolder springContextHolder) { return builder() .cacheMapType(springContextHolder.getProperty(PROPERTY_PREFIX + "cacheMapType").map(CCache.CacheMapType::valueOf).orElse(DEFAULTS.cacheMapType)) .initialCapacity(springContextHolder.getProperty(PROPERTY_PREFIX + "initialCapacity").map(NumberUtils::asIntOrZero).orElse(DEFAULTS.initialCapacity)) .maximumSize(springContextHolder.getProperty(PROPERTY_PREFIX + "maximumSize").map(NumberUtils::asIntOrZero).orElse(DEFAULTS.maximumSize)) .expireMinutes(springContextHolder.getProperty(PROPERTY_PREFIX + "expireMinutes").map(NumberUtils::asIntOrZero).orElse(DEFAULTS.expireMinutes)) .captureStacktrace(springContextHolder.getProperty(PROPERTY_PREFIX + "captureStacktrace").map(StringUtils::toBoolean).orElse(DEFAULTS.captureStacktrace)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCacheConfigDefaults.java
2
请完成以下Java代码
protected final void invalidateAndGoBackToPickingSlotsView() { // https://github.com/metasfresh/metasfresh-webui-frontend/issues/1447 // commenting this out because we now close the current view; currently this is a must, // because currently the frontend then load *this* view's data into the pickingSlotView // invalidateView(); invalidatePickingSlotsView(); invalidatePackablesView(); // After this process finished successfully go back to the picking slots view getResult().setWebuiViewToOpen(WebuiViewToOpen.builder() .viewId(getPickingSlotView().getViewId().getViewId()) .target(ViewOpenTarget.IncludedView) .build()); } protected final void invalidatePickingSlotsView() { final PickingSlotView pickingSlotsView = getPickingSlotViewOrNull(); if (pickingSlotsView == null) { return; } invalidateView(pickingSlotsView.getViewId()); } protected final void invalidatePackablesView() { final PickingSlotView pickingSlotsView = getPickingSlotViewOrNull(); if (pickingSlotsView == null) {
return; } final ViewId packablesViewId = pickingSlotsView.getParentViewId(); if (packablesViewId == null) { return; } invalidateView(packablesViewId); } protected final void addHUIdToCurrentPickingSlot(@NonNull final HuId huId) { final PickingSlotView pickingSlotsView = getPickingSlotView(); final PickingSlotRow pickingSlotRow = getPickingSlotRow(); final PickingSlotId pickingSlotId = pickingSlotRow.getPickingSlotId(); final ShipmentScheduleId shipmentScheduleId = pickingSlotsView.getCurrentShipmentScheduleId(); pickingCandidateService.pickHU(PickRequest.builder() .shipmentScheduleId(shipmentScheduleId) .pickFrom(PickFrom.ofHuId(huId)) .pickingSlotId(pickingSlotId) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\process\HUsToPickViewBasedProcess.java
1
请完成以下Java代码
public static int toRepoId(@Nullable final OrgId orgId) { return orgId != null ? orgId.getRepoId() : -1; } public static int toRepoIdOrAny(@Nullable final OrgId orgId) { return orgId != null ? orgId.getRepoId() : ANY.repoId; } @Override @JsonValue public int getRepoId() { return repoId; } public boolean isAny() { return repoId == Env.CTXVALUE_AD_Org_ID_Any; } /** * @return {@code true} if the org in question is not {@code *} (i.e. "ANY"), but a specific organisation's ID */ public boolean isRegular() { return !isAny(); } public void ifRegular(@NonNull final Consumer<OrgId> consumer)
{ if (isRegular()) { consumer.accept(this); } } @Nullable public OrgId asRegularOrNull() {return isRegular() ? this : null;} public static boolean equals(@Nullable final OrgId id1, @Nullable final OrgId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\OrgId.java
1
请完成以下Java代码
public static <T> T post(String url, String interfaceName, RequestBody requestBody, Object param, Class<T> clazz) { Request request = new Request.Builder() //请求的url .url(url) .post(requestBody) .build(); Response response = null; String result = ""; String errorMsg = ""; try { //创建/Call response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) { logger.error("访问外部系统异常 {}: {}", url, response.toString()); errorMsg = String.format("访问外部系统异常:%s", response.toString()); throw new RemoteAccessException(errorMsg); } result = response.body().string(); } catch (RemoteAccessException e) {
logger.warn(e.getMessage(), e); result = e.getMessage(); throw e; } catch (Exception e) { logger.warn(e.getMessage(), e); if (Objects.isNull(response)) { errorMsg = String.format("访问外部系统异常::%s", e.getMessage()); throw new RemoteAccessException(errorMsg, e); } errorMsg = String.format("访问外部系统异常:::%s", response.toString()); throw new RemoteAccessException(errorMsg, e); } finally { logger.info("请求 {} {},请求参数:{}, 返回参数:{}", interfaceName, url, JSON.toJSONString(param), StringUtils.isEmpty(result) ? errorMsg : result); } return JSON.parseObject(result, clazz); } }
repos\spring-boot-student-master\spring-boot-student-okhttp\src\main\java\com\xiaolyuh\util\OkHttpClientUtil.java
1
请完成以下Java代码
protected static DefaultCaseDiagramCanvas initCaseDiagramCanvas(CmmnModel cmmnModel, String imageType, String activityFontName, String labelFontName, String annotationFontName, ClassLoader customClassLoader) { // We need to calculate maximum values to know how big the image will be in its entirety double minX = Double.MAX_VALUE; double maxX = 0; double minY = Double.MAX_VALUE; double maxY = 0; for (Case caseModel : cmmnModel.getCases()) { Stage stage = caseModel.getPlanModel(); GraphicInfo stageInfo = cmmnModel.getGraphicInfo(stage.getId()); // width if (stageInfo.getX() + stageInfo.getWidth() > maxX) { maxX = stageInfo.getX() + stageInfo.getWidth(); } if (stageInfo.getX() < minX) { minX = stageInfo.getX(); } // height if (stageInfo.getY() + stageInfo.getHeight() > maxY) { maxY = stageInfo.getY() + stageInfo.getHeight();
} if (stageInfo.getY() < minY) { minY = stageInfo.getY(); } } return new DefaultCaseDiagramCanvas((int) maxX + 10, (int) maxY + 10, (int) minX, (int) minY, imageType, activityFontName, labelFontName, annotationFontName, customClassLoader); } public Map<Class<? extends CmmnElement>, ActivityDrawInstruction> getActivityDrawInstructions() { return activityDrawInstructions; } public void setActivityDrawInstructions( Map<Class<? extends CmmnElement>, ActivityDrawInstruction> activityDrawInstructions) { this.activityDrawInstructions = activityDrawInstructions; } protected interface ActivityDrawInstruction { void draw(DefaultCaseDiagramCanvas caseDiagramCanvas, CmmnModel cmmnModel, CaseElement caseElement); } }
repos\flowable-engine-main\modules\flowable-cmmn-image-generator\src\main\java\org\flowable\cmmn\image\impl\DefaultCaseDiagramGenerator.java
1
请在Spring Boot框架中完成以下Java代码
final List<JsonExternalReferenceTarget> computeTargets(@NonNull final AttachmentMetadata metadata) { final ImmutableList.Builder<JsonExternalReferenceTarget> targets = ImmutableList.builder(); final String createdBy = metadata.getCreatedBy(); if (!EmptyUtil.isEmpty(createdBy)) { targets.add(JsonExternalReferenceTarget.ofTypeAndId(GetAttachmentRouteConstants.ESR_TYPE_USERID, formatExternalId(createdBy))); } final String patientId = metadata.getPatientId(); if (!EmptyUtil.isEmpty(patientId)) { targets.add(JsonExternalReferenceTarget.ofTypeAndId(GetAttachmentRouteConstants.ESR_TYPE_BPARTNER, formatExternalId(patientId))); } final ImmutableList<JsonExternalReferenceTarget> computedTargets = targets.build(); if (EmptyUtil.isEmpty(computedTargets)) { throw new RuntimeException("Attachment targets cannot be null!"); } return computedTargets; } @NonNull final List<JsonTag> computeTags(@NonNull final Attachment attachment) { final ImmutableList.Builder<JsonTag> tags = ImmutableList.builder(); final AttachmentMetadata metadata = attachment.getMetadata(); final String id = attachment.getId(); if (!EmptyUtil.isEmpty(id)) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ID, id)); } final String uploadDate = attachment.getUploadDate(); if (!EmptyUtil.isEmpty(uploadDate)) {
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_UPLOAD_DATE, uploadDate)); } final BigDecimal type = metadata.getType(); if (type != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_TYPE, String.valueOf(type))); } final OffsetDateTime createdAt = metadata.getCreatedAt(); if (createdAt != null) { tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_CREATEDAT, String.valueOf(createdAt))); } tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ENDPOINT, GetAttachmentRouteConstants.ALBERTA_ATTACHMENT_ENDPOINT_VALUE)); return tags.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\attachment\processor\AttachmentProcessor.java
2
请完成以下Java代码
public UserQuery orderByUserId() { return orderBy(UserQueryProperty.USER_ID); } @Override public UserQuery orderByUserEmail() { return orderBy(UserQueryProperty.EMAIL); } @Override public UserQuery orderByUserFirstName() { return orderBy(UserQueryProperty.FIRST_NAME); } @Override public UserQuery orderByUserLastName() { return orderBy(UserQueryProperty.LAST_NAME); } // results ////////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getUserEntityManager(commandContext).findUserCountByQueryCriteria(this); } @Override public List<User> executeList(CommandContext commandContext) { return CommandContextUtil.getUserEntityManager(commandContext).findUserByQueryCriteria(this); } // getters ////////////////////////////////////////////////////////// @Override public String getId() { return id; } public List<String> getIds() { return ids; } public String getIdIgnoreCase() { return idIgnoreCase; } public String getFirstName() { return firstName; } public String getFirstNameLike() { return firstNameLike; } public String getFirstNameLikeIgnoreCase() { return firstNameLikeIgnoreCase; } public String getLastName() { return lastName; } public String getLastNameLike() { return lastNameLike; }
public String getLastNameLikeIgnoreCase() { return lastNameLikeIgnoreCase; } public String getEmail() { return email; } public String getEmailLike() { return emailLike; } public String getGroupId() { return groupId; } public List<String> getGroupIds() { return groupIds; } public String getFullNameLike() { return fullNameLike; } public String getFullNameLikeIgnoreCase() { return fullNameLikeIgnoreCase; } public String getDisplayName() { return displayName; } public String getDisplayNameLike() { return displayNameLike; } public String getDisplayNameLikeIgnoreCase() { return displayNameLikeIgnoreCase; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\UserQueryImpl.java
1
请完成以下Java代码
public void onValidationError(String params, String msg) { processRemove.run(); callback.onValidationError(params, msg); } @Override public void onError(String params, Exception e) { try { if (e instanceof TimeoutException) { return; } processRemove.run(); } finally { callback.onError(params, e); } } }; } @Override public void persistUpdates(String endpoint) { LwM2MModelConfig modelConfig = currentModelConfigs.get(endpoint); if (modelConfig != null && !modelConfig.isEmpty()) { modelStore.put(modelConfig); } }
@Override public void removeUpdates(String endpoint) { currentModelConfigs.remove(endpoint); modelStore.remove(endpoint); } @PreDestroy private void destroy() { currentModelConfigs.values().forEach(model -> { if (model != null && !model.isEmpty()) { modelStore.put(model); } }); } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\model\LwM2MModelConfigServiceImpl.java
1
请完成以下Java代码
public void setC_BPartner_Customer_ID (final int C_BPartner_Customer_ID) { if (C_BPartner_Customer_ID < 1) set_Value (COLUMNNAME_C_BPartner_Customer_ID, null); else set_Value (COLUMNNAME_C_BPartner_Customer_ID, C_BPartner_Customer_ID); } @Override public int getC_BPartner_Customer_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Customer_ID); } @Override public de.metas.contracts.commission.model.I_C_Customer_Trade_Margin getC_Customer_Trade_Margin() { return get_ValueAsPO(COLUMNNAME_C_Customer_Trade_Margin_ID, de.metas.contracts.commission.model.I_C_Customer_Trade_Margin.class); } @Override public void setC_Customer_Trade_Margin(final de.metas.contracts.commission.model.I_C_Customer_Trade_Margin C_Customer_Trade_Margin) { set_ValueFromPO(COLUMNNAME_C_Customer_Trade_Margin_ID, de.metas.contracts.commission.model.I_C_Customer_Trade_Margin.class, C_Customer_Trade_Margin); } @Override public void setC_Customer_Trade_Margin_ID (final int C_Customer_Trade_Margin_ID) { if (C_Customer_Trade_Margin_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Customer_Trade_Margin_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Customer_Trade_Margin_ID, C_Customer_Trade_Margin_ID); } @Override public int getC_Customer_Trade_Margin_ID() { return get_ValueAsInt(COLUMNNAME_C_Customer_Trade_Margin_ID); } @Override public void setC_Customer_Trade_Margin_Line_ID (final int C_Customer_Trade_Margin_Line_ID) { if (C_Customer_Trade_Margin_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Customer_Trade_Margin_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Customer_Trade_Margin_Line_ID, C_Customer_Trade_Margin_Line_ID); } @Override public int getC_Customer_Trade_Margin_Line_ID() { return get_ValueAsInt(COLUMNNAME_C_Customer_Trade_Margin_Line_ID); } @Override public void setMargin (final int Margin) { set_Value (COLUMNNAME_Margin, Margin); } @Override public int getMargin() { return get_ValueAsInt(COLUMNNAME_Margin); } @Override public void setM_Product_Category_ID (final 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, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_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 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\commission\model\X_C_Customer_Trade_Margin_Line.java
1
请完成以下Java代码
public class X_M_Product_Mapping extends org.compiere.model.PO implements I_M_Product_Mapping, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 13779372L; /** Standard Constructor */ public X_M_Product_Mapping (Properties ctx, int M_Product_Mapping_ID, String trxName) { super (ctx, M_Product_Mapping_ID, trxName); /** if (M_Product_Mapping_ID == 0) { setM_Product_Mapping_ID (0); } */ } /** Load Constructor */ public X_M_Product_Mapping (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override 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 Produkt-Zuordnung. @param M_Product_Mapping_ID Produkt-Zuordnung */ @Override public void setM_Product_Mapping_ID (int M_Product_Mapping_ID) { if (M_Product_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Mapping_ID, Integer.valueOf(M_Product_Mapping_ID)); } /** Get Produkt-Zuordnung. @return Produkt-Zuordnung */ @Override
public int getM_Product_Mapping_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Mapping_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\product\model\X_M_Product_Mapping.java
1
请完成以下Java代码
private HUPIItemProductId getPackingMaterialId(final IPricingContext pricingCtx) { final Object referencedObj = pricingCtx.getReferencedObject(); if (referencedObj == null) { return null; } // // check if we have an piip-aware if (referencedObj instanceof I_M_HU_PI_Item_Product_Aware) { final int packingMaterialRepoId = ((I_M_HU_PI_Item_Product_Aware)referencedObj).getM_HU_PI_Item_Product_ID(); return HUPIItemProductId.ofRepoIdOrNull(packingMaterialRepoId); } // // check if there is a M_HU_PI_Item_Product_ID(_Override) column. if (InterfaceWrapperHelper.hasModelColumnName(referencedObj, I_M_HU_PI_Item_Product_Aware.COLUMNNAME_M_HU_PI_Item_Product_ID)) { final Integer valueOverrideOrValue = InterfaceWrapperHelper.getValueOverrideOrValue(referencedObj, I_M_HU_PI_Item_Product_Aware.COLUMNNAME_M_HU_PI_Item_Product_ID); return valueOverrideOrValue == null ? null : HUPIItemProductId.ofRepoIdOrNull(valueOverrideOrValue); }
return null; } public static IProductPriceQueryMatcher createHUPIItemProductMatcher(@Nullable final HUPIItemProductId packingMaterialId) { if (packingMaterialId == null || !packingMaterialId.isRegular()) { return HUPIItemProductMatcher_None; } else { return ProductPriceQueryMatcher.of(HUPIItemProductMatcher_NAME, EqualsQueryFilter.of(I_M_ProductPrice.COLUMNNAME_M_HU_PI_Item_Product_ID, packingMaterialId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pricing\spi\impl\HUPricing.java
1
请完成以下Java代码
private Optional<Object> extractAttributeValueToTransfer(final I_M_HU hu, final I_M_Attribute attribute, final IAttributeStorageFactory attributeStorageFactory) { if (hu != null) { final IAttributeStorage vhuStorage = attributeStorageFactory.getAttributeStorage(hu); if (vhuStorage.hasAttribute(attribute)) { final Object value = vhuStorage.getValue(attribute); if (value != null) { return Optional.of(value); } } } return Optional.empty(); } public List<ShipmentScheduleWithHU> getCandidates() { return ImmutableList.copyOf(candidates); } /** * {@code false} by default. Set to {@code} true if there aren't any real picked HUs, but we still want to createa a shipment line. */ public void setManualPackingMaterial(final boolean manualPackingMaterial) { this._manualPackingMaterial = manualPackingMaterial; } private boolean isManualPackingMaterial() { return _manualPackingMaterial || getQtyTypeToUse().isOnlyUseToDeliver(); }
/** * Sets a online {@link Set} which contains the list of TU Ids which were already assigned. * <p> * This set will be updated by this builder when TUs are assigned. * <p> * When this shipment line will try to assign an TU which is on this list, it will set the {@link I_M_HU_Assignment#setIsTransferPackingMaterials(boolean)} to <code>false</code>. */ public void setAlreadyAssignedTUIds(final Set<HuId> alreadyAssignedTUIds) { this.alreadyAssignedTUIds = alreadyAssignedTUIds; } public void setQtyTypeToUse(final M_ShipmentSchedule_QuantityTypeToUse qtyTypeToUse) { this.qtyTypeToUse = qtyTypeToUse; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\spi\impl\ShipmentLineBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getDecisionKey() { return decisionKey; } public void setDecisionKey(String decisionKey) { this.decisionKey = decisionKey; } public String getDecisionName() {
return decisionName; } public void setDecisionName(String decisionName) { this.decisionName = decisionName; } public String getDecisionVersion() { return decisionVersion; } public void setDecisionVersion(String decisionVersion) { this.decisionVersion = decisionVersion; } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java
2
请完成以下Java代码
public TimeRange createTimeRange( @Nullable final Instant from, @Nullable final Instant to) { final Instant toEffective = to != null ? to : calculateTo(); final Instant fromEffective = from != null ? from : calculateFrom(toEffective); return TimeRange.main(fromEffective, toEffective); } public TimeRange createTimeRange( @Nullable final java.util.Date dateFrom, @Nullable final java.util.Date dateTo) { final Instant from = dateFrom == null ? null : dateFrom.toInstant(); final Instant to = dateTo == null ? null : dateTo.toInstant(); return createTimeRange(from, to); } private Instant calculateTo() { Instant to = SystemTime.asInstant(); if (defaultTimeRangeEndOffset != null) { to = to.plus(defaultTimeRangeEndOffset); } return to; } private Instant calculateFrom(@NonNull final Instant to) { if (defaultTimeRange == null || defaultTimeRange.isZero()) { return Instant.ofEpochMilli(0);
} else { return to.minus(defaultTimeRange.abs()); } } public KPITimeRangeDefaults compose(final KPITimeRangeDefaults fallback) { return builder() .defaultTimeRange(CoalesceUtil.coalesce(getDefaultTimeRange(), fallback.getDefaultTimeRange())) .defaultTimeRangeEndOffset(CoalesceUtil.coalesce(getDefaultTimeRangeEndOffset(), fallback.getDefaultTimeRangeEndOffset())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\KPITimeRangeDefaults.java
1
请在Spring Boot框架中完成以下Java代码
public List<CaseDefinition> findCaseDefinitionsByQueryCriteria(CaseDefinitionQueryImpl caseDefinitionQuery, Page page) { configureCaseDefinitionQuery(caseDefinitionQuery); return getDbEntityManager().selectList("selectCaseDefinitionsByQueryCriteria", caseDefinitionQuery, page); } public long findCaseDefinitionCountByQueryCriteria(CaseDefinitionQueryImpl caseDefinitionQuery) { configureCaseDefinitionQuery(caseDefinitionQuery); return (Long) getDbEntityManager().selectOne("selectCaseDefinitionCountByQueryCriteria", caseDefinitionQuery); } @SuppressWarnings("unchecked") public List<CaseDefinition> findCaseDefinitionByDeploymentId(String deploymentId) { return getDbEntityManager().selectList("selectCaseDefinitionByDeploymentId", deploymentId); } protected void configureCaseDefinitionQuery(CaseDefinitionQueryImpl query) { getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } @Override public CaseDefinitionEntity findLatestDefinitionByKey(String key) { return findLatestCaseDefinitionByKey(key); } @Override public CaseDefinitionEntity findLatestDefinitionById(String id) { return findCaseDefinitionById(id); } @Override public CaseDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) {
return getDbEntityManager().getCachedEntity(CaseDefinitionEntity.class, definitionId); } @Override public CaseDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return findLatestCaseDefinitionByKeyAndTenantId(definitionKey, tenantId); } @Override public CaseDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { throw new UnsupportedOperationException("Currently finding case definition by version tag and tenant is not implemented."); } @Override public CaseDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { return findCaseDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId); } @Override public CaseDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return findCaseDefinitionByDeploymentAndKey(deploymentId, definitionKey); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionManager.java
2