instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class SystecResponseStringParser implements IParser<ISystecCmd> { @Override @SuppressWarnings("unchecked") public <T> T parse(final ISystecCmd cmd, final String stringToParse, final String elementName, final Class<T> clazz) { try { final SystecResultStringElement elementInfo = cmd.getResultElements().get(elementName); final String subString = stringToParse.substring(elementInfo.getStartByte() - 1, elementInfo.getStartByte() - 1 + elementInfo.getLength()).trim(); final Format format = elementInfo.getFormat(); if (format == null) { return (T)subString;
} return (T)format.parseObject(subString); } catch (final Exception e) { throw new ParserException(cmd, stringToParse, elementName, clazz, e); } } @Override public String toString() { return String.format("SystecResponseStringParser []"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\systec\SystecResponseStringParser.java
1
请完成以下Java代码
public void setProductName (final @Nullable java.lang.String ProductName) { throw new IllegalArgumentException ("ProductName is virtual column"); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { throw new IllegalArgumentException ("ProductValue is virtual column"); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setQtyLU (final @Nullable BigDecimal QtyLU) { set_Value (COLUMNNAME_QtyLU, QtyLU); } @Override public BigDecimal getQtyLU() {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final @Nullable BigDecimal QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public BigDecimal getQtyTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShippingPackage.java
1
请完成以下Java代码
public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; }
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELExecutionContext.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ApiModelProperty(value = "Can be any arbitrary value. When a valid formatted media-type (e.g. application/xml, text/plain) is included, the binary content HTTP response content-type will be set the given value.") public String getType() { return type; } public void setType(String type) { this.type = type; }
public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(value = "contentUrl:In case the attachment is a link to an external resource, the externalUrl contains the URL to the external content. If the attachment content is present in the Flowable engine, the contentUrl will contain an URL where the binary content can be streamed from.") public String getExternalUrl() { return externalUrl; } public void setExternalUrl(String externalUrl) { this.externalUrl = externalUrl; } public String getContentUrl() { return contentUrl; } public void setContentUrl(String contentUrl) { this.contentUrl = contentUrl; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\AttachmentResponse.java
2
请完成以下Java代码
public int getPP_Product_BOMVersions_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRevision (final @Nullable java.lang.String Revision) { set_Value (COLUMNNAME_Revision, Revision); } @Override public java.lang.String getRevision() { return get_ValueAsString(COLUMNNAME_Revision); } @Override public org.compiere.model.I_AD_Sequence getSerialNo_Sequence() { return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence) { set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence); } @Override public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID) {
if (SerialNo_Sequence_ID < 1) set_Value (COLUMNNAME_SerialNo_Sequence_ID, null); else set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID); } @Override public int getSerialNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOM.java
1
请完成以下Java代码
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) { final SqlDocumentEntityDataBindingDescriptor binding = SqlDocumentEntityDataBindingDescriptor.cast(entityDescriptor.getDataBinding()); final String sql = binding.getSqlSelectVersionById() .orElseThrow(() -> new AdempiereException("Versioning is not supported for " + entityDescriptor)); final Timestamp version = DB.getSQLValueTSEx(ITrx.TRXNAME_ThreadInherited, sql, documentIdAsInt); return version == null ? VERSION_DEFAULT : String.valueOf(version.getTime()); } @Override public int retrieveLastLineNo(final DocumentQuery query) { logger.debug("Retrieving last LineNo: query={}", query);
final DocumentEntityDescriptor entityDescriptor = query.getEntityDescriptor(); assertThisRepository(entityDescriptor); final SqlDocumentQueryBuilder sqlBuilder = SqlDocumentQueryBuilder.of(query); final SqlAndParams sql = sqlBuilder.getSqlMaxLineNo(); return DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql.getSql(), sql.getSqlParams()); } public boolean isReadonly(@NonNull final GridTabVO gridTabVO) { return saveHandlers.isReadonly(gridTabVO); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentsRepository.java
1
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } @Override public void setName(String name) { nameAttribute.setValue(this, name); } @Override public Integer getCapacity() { return capacityAttribute.getValue(this); } @Override public void setCapacity(Integer capacity) { capacityAttribute.setValue(this, capacity); } @Override public Boolean isUnlimited() { return isUnlimitedAttribute.getValue(this); } @Override public void setUnlimited(Boolean isUnlimited) { isUnlimitedAttribute.setValue(this, isUnlimited); } @Override public ItemDefinition getItemSubject() { return itemSubjectRefAttribute.getReferenceTargetElement(this); }
@Override public void setItemSubject(ItemDefinition itemSubject) { itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject); } @Override public DataState getDataState() { return dataStateChild.getChild(this); } @Override public void setDataState(DataState dataState) { dataStateChild.setChild(this, dataState); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataStoreImpl.java
1
请完成以下Java代码
private I_C_UOM getUOM() { return Services.get(IUOMDAO.class).getById(orderLine.getC_UOM_ID()); } /** * @returns QtyOrdered of the wrapped order line */ @Override public BigDecimal getQty() { return orderLine.getQtyOrdered(); } /** * Sets both QtyOrdered and QtyEntered of the wrapped order line.
* * @param qtyOrdered ordered quantity in stock UOM, which is also converted to qtyEntered. */ @Override protected void setQty(final BigDecimal qtyOrdered) { orderLine.setQtyOrdered(qtyOrdered); final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class); final Quantity qtyInStockUOM = Quantitys.of(qtyOrdered, ProductId.ofRepoId(orderLine.getM_Product_ID())); final Quantity qtyEntered = orderLineBL.convertQtyToUOM(qtyInStockUOM, orderLine); orderLine.setQtyEntered(qtyEntered.toBigDecimal()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\OrderLinePackingMaterialDocumentLine.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final BookstoreService bookstoreService; public MainApplication(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> { System.out.println("\n------------------- Joana Nimar's Books --------------------"); List<Book> detachedBooks = bookstoreService.fetchBooksOfAuthor("Joana Nimar"); detachedBooks.forEach(b -> System.out.println(b)); System.out.println("\n---------- Books of Joana Nimar updated in detached state------------"); // ,update first book title detachedBooks.get(0).setTitle("A History of Ancient Rome"); // remove second title detachedBooks.remove(1); // add a new book Book book = new Book();
book.setTitle("History In 100 Minutes"); book.setIsbn("005-JN"); detachedBooks.add(book); detachedBooks.forEach(b -> System.out.println(b)); System.out.println("\n----------------- Merging books of Joana Nimar ----------------"); bookstoreService.updateBooksOfAuthor("Joana Nimar", detachedBooks); System.out.println("\n----------------- Books of Joana Nimar After Merge ----------------"); List<Book> books = bookstoreService.fetchBooksOfAuthor("Joana Nimar"); books.forEach(b -> System.out.println(b)); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootMergeCollections\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public void setMSV3_LieferPzn (java.lang.String MSV3_LieferPzn) { set_Value (COLUMNNAME_MSV3_LieferPzn, MSV3_LieferPzn); } /** Get MSV3_LieferPzn. @return MSV3_LieferPzn */ @Override public java.lang.String getMSV3_LieferPzn () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_LieferPzn); } /** Set Substitution. @param MSV3_Substitution_ID Substitution */ @Override public void setMSV3_Substitution_ID (int MSV3_Substitution_ID) { if (MSV3_Substitution_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Substitution_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Substitution_ID, Integer.valueOf(MSV3_Substitution_ID)); } /** Get Substitution. @return Substitution */ @Override public int getMSV3_Substitution_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Substitution_ID); if (ii == null) return 0;
return ii.intValue(); } /** * MSV3_Substitutionsgrund AD_Reference_ID=540818 * Reference name: MSV3_Substitutionsgrund */ public static final int MSV3_SUBSTITUTIONSGRUND_AD_Reference_ID=540818; /** Nachfolgeprodukt = Nachfolgeprodukt */ public static final String MSV3_SUBSTITUTIONSGRUND_Nachfolgeprodukt = "Nachfolgeprodukt"; /** ReUndParallelImport = ReUndParallelImport */ public static final String MSV3_SUBSTITUTIONSGRUND_ReUndParallelImport = "ReUndParallelImport"; /** Vorschlag = Vorschlag */ public static final String MSV3_SUBSTITUTIONSGRUND_Vorschlag = "Vorschlag"; /** Set Substitutionsgrund. @param MSV3_Substitutionsgrund Substitutionsgrund */ @Override public void setMSV3_Substitutionsgrund (java.lang.String MSV3_Substitutionsgrund) { set_Value (COLUMNNAME_MSV3_Substitutionsgrund, MSV3_Substitutionsgrund); } /** Get Substitutionsgrund. @return Substitutionsgrund */ @Override public java.lang.String getMSV3_Substitutionsgrund () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Substitutionsgrund); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Substitution.java
1
请完成以下Java代码
public List<Task> findTasksByParentTaskId(String parentTaskId) { return taskDataManager.findTasksByParentTaskId(parentTaskId); } @Override public void deleteTask(String taskId, String deleteReason, boolean cascade, boolean cancel) { TaskEntity task = findById(taskId); if (task != null) { if (task.getExecutionId() != null) { throw new ActivitiException("The task cannot be deleted because is part of a running process"); } deleteTask(task, deleteReason, cascade, cancel); } else if (cascade) { getHistoricTaskInstanceEntityManager().delete(taskId); } } @Override public void deleteTask(String taskId, String deleteReason, boolean cascade) { this.deleteTask(taskId, deleteReason, cascade, false);
} @Override public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) { taskDataManager.updateTaskTenantIdForDeployment(deploymentId, newTenantId); } public TaskDataManager getTaskDataManager() { return taskDataManager; } public void setTaskDataManager(TaskDataManager taskDataManager) { this.taskDataManager = taskDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @ApiModelProperty(example = "null") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "null") public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl;
} @ApiModelProperty(example = "5") public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-process-instances/5") public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricIdentityLinkResponse.java
2
请完成以下Java代码
public void setQualityRating (final @Nullable BigDecimal QualityRating) { set_Value (COLUMNNAME_QualityRating, QualityRating); } @Override public BigDecimal getQualityRating() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QualityRating); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setShelfLifeMinDays (final int ShelfLifeMinDays) { set_Value (COLUMNNAME_ShelfLifeMinDays, ShelfLifeMinDays); } @Override public int getShelfLifeMinDays() { return get_ValueAsInt(COLUMNNAME_ShelfLifeMinDays); } @Override public void setShelfLifeMinPct (final int ShelfLifeMinPct) { set_Value (COLUMNNAME_ShelfLifeMinPct, ShelfLifeMinPct); } @Override public int getShelfLifeMinPct() { return get_ValueAsInt(COLUMNNAME_ShelfLifeMinPct); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setUsedForCustomer (final boolean UsedForCustomer) {
set_Value (COLUMNNAME_UsedForCustomer, UsedForCustomer); } @Override public boolean isUsedForCustomer() { return get_ValueAsBoolean(COLUMNNAME_UsedForCustomer); } @Override public void setUsedForVendor (final boolean UsedForVendor) { set_Value (COLUMNNAME_UsedForVendor, UsedForVendor); } @Override public boolean isUsedForVendor() { return get_ValueAsBoolean(COLUMNNAME_UsedForVendor); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } @Override public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo) { set_Value (COLUMNNAME_VendorProductNo, VendorProductNo); } @Override public java.lang.String getVendorProductNo() { return get_ValueAsString(COLUMNNAME_VendorProductNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product.java
1
请完成以下Java代码
public void closeById(@NonNull final ViewId pickingSlotViewId, @NonNull final ViewCloseAction closeAction) { final DocumentId rowId = extractRowId(pickingSlotViewId); final PackageableView packageableView = getPackageableViewByPickingSlotViewId(pickingSlotViewId); packageableView.removePickingSlotView(rowId, closeAction); } @Override public void invalidateView(final ViewId pickingSlotViewId) { final PickingSlotView pickingSlotView = getOrCreatePickingSlotView(pickingSlotViewId, false/* create */); if (pickingSlotView == null) { return; } final PackageableView packageableView = getPackageableViewByPickingSlotViewId(pickingSlotViewId); if (packageableView != null) { //we have to invalidate all the related pickingSlotViews in order to make sure the //changes available in UI when selecting different `packageableRows`
packageableView.invalidatePickingSlotViews(); } pickingSlotView.invalidateAll(); ViewChangesCollector.getCurrentOrAutoflush() .collectFullyChanged(pickingSlotView); } @Override public Stream<IView> streamAllViews() { // Do we really have to implement this? return Stream.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotViewsIndexStorage.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemOnPart.class, CMMN_ELEMENT_PLAN_ITEM_ON_PART) .extendsType(OnPart.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<PlanItemOnPart>() { public PlanItemOnPart newInstance(ModelTypeInstanceContext instanceContext) { return new PlanItemOnPartImpl(instanceContext); } }); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(PlanItem.class) .build(); exitCriterionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERION_REF) .idAttributeReference(ExitCriterion.class) .build();
sentryRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SENTRY_REF) .namespace(CMMN10_NS) .idAttributeReference(Sentry.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); standardEventChild = sequenceBuilder.element(PlanItemTransitionStandardEvent.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemOnPartImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static String trimUrl(String url) { // 清除首尾的反斜杠 if (url.startsWith(Back_Slash)) { url = url.substring(1); } if (url.endsWith(Back_Slash)) { url = url.substring(0,url.length()-1); } // 将"{xxx}"替换为"*" // TODO 正则表达式要继续完善(纠正/user/{xxxxx}/{yyyy}——>user/*的情况) url = url.replaceAll("\\{(.*)\\}","*"); return url; } /** * 获取指定方法上的@Login的值和@Role的值 * @param method 目标方法 * @param accessAuthEntity * @return */ private AccessAuthEntity getLoginAndPermission(Method method, AccessAuthEntity accessAuthEntity) { // 获取@Permission的值 Permission permission = AnnotationUtil.getAnnotationValueByMethod(method, Permission.class); if (permission!=null && StringUtils.isNotEmpty(permission.value())) { accessAuthEntity.setPermission(permission.value()); accessAuthEntity.setLogin(true); return accessAuthEntity; } // 获取@Login的值
Login login = AnnotationUtil.getAnnotationValueByMethod(method, Login.class); if (login!=null) { accessAuthEntity.setLogin(true); } accessAuthEntity.setLogin(false); return accessAuthEntity; } public static void main(String[] args) { System.out.println("user:"+trimUrl("user")); System.out.println("{}:"+trimUrl("{}")); System.out.println("/user:"+trimUrl("/user")); System.out.println("/user/:"+trimUrl("/user/")); System.out.println("user/{xxxx}:"+trimUrl("user/{xxxx}")); System.out.println("/user/{xxxxx}/{yyyy}:"+trimUrl("/user/{xxxxx}/{yyyy}")); System.out.println("/user/home/{sdsds}:"+trimUrl("/user/home/{sdsds}")); System.out.println("/user/{home}/{zzzzz}/:"+trimUrl("/user/{home}/{zzzzz}/")); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\init\InitAuth.java
2
请完成以下Java代码
public <ImportRecordType> void registerImportProcess( @NonNull final Class<ImportRecordType> modelImportClass, @NonNull final Class<? extends IImportProcess<ImportRecordType>> importProcessClass) { final ImportProcessDescriptor descriptor = importProcessDescriptorsMap.register(modelImportClass, importProcessClass); logger.info("Registered import process: {}", descriptor); relatedProcessesRegistry.registerImportTable(descriptor.getImportTableName()); } @Override public void setDeleteImportDataProcessClass(@NonNull final Class<?> deleteImportDataProcessClass) { relatedProcessesRegistry.setDeleteImportDataProcessClass(deleteImportDataProcessClass); } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcess(@NonNull final Class<ImportRecordType> modelImportClass) { final IImportProcess<ImportRecordType> importProcess = newImportProcessOrNull(modelImportClass); if (importProcess == null) { throw new AdempiereException("No import process found for " + modelImportClass); } return importProcess; } @Nullable private <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessOrNull(@NonNull final Class<ImportRecordType> modelImportClass) { final Class<?> importProcessClass = importProcessDescriptorsMap.getImportProcessClassByModelImportClassOrNull(modelImportClass); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } private <ImportRecordType> IImportProcess<ImportRecordType> newInstance(final Class<?> importProcessClass) { try { @SuppressWarnings("unchecked") final IImportProcess<ImportRecordType> importProcess = (IImportProcess<ImportRecordType>)importProcessClass.newInstance(); return importProcess; }
catch (final Exception e) { throw new AdempiereException("Failed instantiating " + importProcessClass, e); } } @Nullable private <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableNameOrNull(@NonNull final String importTableName) { final Class<?> importProcessClass = importProcessDescriptorsMap.getImportProcessClassByImportTableNameOrNull(importTableName); if (importProcessClass == null) { return null; } return newInstance(importProcessClass); } @Override public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableName(@NonNull final String importTableName) { final IImportProcess<ImportRecordType> importProcess = newImportProcessForTableNameOrNull(importTableName); if (importProcess == null) { throw new AdempiereException("No import process found for " + importTableName); } return importProcess; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\impl\ImportProcessFactory.java
1
请完成以下Java代码
public final class WebuiDocumentReferenceId { @JsonCreator public static WebuiDocumentReferenceId ofString(@NonNull final String value) { return new WebuiDocumentReferenceId(value); } @JsonCreator public static WebuiDocumentReferenceId ofRelatedDocumentsId(@NonNull final RelatedDocumentsId relatedDocumentsId) { return new WebuiDocumentReferenceId(relatedDocumentsId.toJson()); } private final String value; private WebuiDocumentReferenceId(@NonNull final String value) { Check.assumeNotEmpty(value, "value is not empty"); this.value = value; } @Deprecated
@Override public String toString() { return toJson(); } @JsonValue public String toJson() { return value; } public RelatedDocumentsId toRelatedDocumentsId() { return RelatedDocumentsId.ofString(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\WebuiDocumentReferenceId.java
1
请完成以下Java代码
public class PlanItemDefinition extends CaseElement implements HasLifecycleListeners { protected String planItemRef; protected PlanItemControl defaultControl; protected List<FlowableListener> lifecycleListeners = new ArrayList<>(); public String getPlanItemRef() { return planItemRef; } public void setPlanItemRef(String planItemRef) { this.planItemRef = planItemRef; } public PlanItemControl getDefaultControl() { return defaultControl; } public void setDefaultControl(PlanItemControl defaultControl) { this.defaultControl = defaultControl; }
@Override public List<FlowableListener> getLifecycleListeners() { return lifecycleListeners; } @Override public void setLifecycleListeners(List<FlowableListener> lifecycleListeners) { this.lifecycleListeners = lifecycleListeners; } public void setValues(PlanItemDefinition otherElement) { super.setValues(otherElement); setPlanItemRef(otherElement.getPlanItemRef()); setDefaultControl(otherElement.getDefaultControl()); setLifecycleListeners(otherElement.lifecycleListeners); } @Override public String toString() { return "PlanItemDefinition " + id + (name != null ? " " + name : ""); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\PlanItemDefinition.java
1
请完成以下Java代码
public class JeecgDataAutorUtils { public static final String MENU_DATA_AUTHOR_RULES = "MENU_DATA_AUTHOR_RULES"; public static final String MENU_DATA_AUTHOR_RULE_SQL = "MENU_DATA_AUTHOR_RULE_SQL"; public static final String SYS_USER_INFO = "SYS_USER_INFO"; /** * 往链接请求里面,传入数据查询条件 * * @param request * @param dataRules */ public static synchronized void installDataSearchConditon(HttpServletRequest request, List<SysPermissionDataRuleModel> dataRules) { @SuppressWarnings("unchecked") // 1.先从request获取MENU_DATA_AUTHOR_RULES,如果存则获取到LIST List<SysPermissionDataRuleModel> list = (List<SysPermissionDataRuleModel>)loadDataSearchConditon(); if (list==null) { // 2.如果不存在,则new一个list list = new ArrayList<SysPermissionDataRuleModel>(); } for (SysPermissionDataRuleModel tsDataRule : dataRules) { list.add(tsDataRule); } // 3.往list里面增量存指 request.setAttribute(MENU_DATA_AUTHOR_RULES, list); } /** * 获取请求对应的数据权限规则 * * @return */ @SuppressWarnings("unchecked") public static synchronized List<SysPermissionDataRuleModel> loadDataSearchConditon() { return (List<SysPermissionDataRuleModel>) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULES); } /** * 获取请求对应的数据权限SQL * * @return */ public static synchronized String loadDataSearchConditonSqlString() { return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL); }
/** * 往链接请求里面,传入数据查询条件 * * @param request * @param sql */ public static synchronized void installDataSearchConditon(HttpServletRequest request, String sql) { String ruleSql = (String) loadDataSearchConditonSqlString(); if (!StringUtils.hasText(ruleSql)) { request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL,sql); } } /** * 将用户信息存到request * @param request * @param userinfo */ public static synchronized void installUserInfo(HttpServletRequest request, SysUserCacheInfo userinfo) { request.setAttribute(SYS_USER_INFO, userinfo); } /** * 将用户信息存到request * @param userinfo */ public static synchronized void installUserInfo(SysUserCacheInfo userinfo) { SpringContextUtils.getHttpServletRequest().setAttribute(SYS_USER_INFO, userinfo); } /** * 从request获取用户信息 * @return */ public static synchronized SysUserCacheInfo loadUserInfo() { return (SysUserCacheInfo) SpringContextUtils.getHttpServletRequest().getAttribute(SYS_USER_INFO); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\util\JeecgDataAutorUtils.java
1
请完成以下Java代码
public QtyCalculationsBOM getQtyCalculationsBOM(@NonNull final I_PP_Order order) { final ImmutableList<QtyCalculationsBOMLine> lines = orderBOMsRepo.retrieveOrderBOMLines(order) .stream() .map(orderBOMLineRecord -> toQtyCalculationsBOMLine(order, orderBOMLineRecord)) .collect(ImmutableList.toImmutableList()); return QtyCalculationsBOM.builder() .lines(lines) .orderId(PPOrderId.ofRepoIdOrNull(order.getPP_Order_ID())) .build(); } @Override public void save(final I_PP_Order_BOMLine orderBOMLine) { orderBOMsRepo.save(orderBOMLine); } @Override public Set<ProductId> getProductIdsToIssue(final PPOrderId ppOrderId) { return getOrderBOMLines(ppOrderId, I_PP_Order_BOMLine.class) .stream()
.filter(bomLine -> BOMComponentType.ofNullableCodeOrComponent(bomLine.getComponentType()).isIssue()) .map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(@NonNull final I_PP_Order ppOrder) { final WarehouseId warehouseId = WarehouseId.ofRepoId(ppOrder.getM_Warehouse_ID()); return getIssueFromWarehouseIds(warehouseId); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(final WarehouseId ppOrderWarehouseId) { return warehouseDAO.getWarehouseIdsOfSameGroup(ppOrderWarehouseId, WarehouseGroupAssignmentType.MANUFACTURING); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMBL.java
1
请完成以下Java代码
public Collection<Sentry> getExitCriteria() { if (!isCmmn11()) { return Collections.unmodifiableCollection(getExitCriterias()); } else { List<Sentry> sentries = new ArrayList<Sentry>(); Collection<ExitCriterion> exitCriterions = getExitCriterions(); for (ExitCriterion exitCriterion : exitCriterions) { Sentry sentry = exitCriterion.getSentry(); if (sentry != null) { sentries.add(sentry); } } return Collections.unmodifiableCollection(sentries); } } public Collection<EntryCriterion> getEntryCriterions() { return entryCriterionCollection.get(this); } public Collection<ExitCriterion> getExitCriterions() { return exitCriterionCollection.get(this); } public ItemControl getItemControl() { return itemControlChild.getChild(this); } public void setItemControl(ItemControl itemControl) { itemControlChild.setChild(this, itemControl); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItem.class, CMMN_ELEMENT_PLAN_ITEM) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<PlanItem>() { public PlanItem newInstance(ModelTypeInstanceContext instanceContext) { return new PlanItemImpl(instanceContext); }
}); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); planItemDefinitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .idAttributeReference(PlanItemDefinition.class) .build(); entryCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ENTRY_CRITERIA_REFS) .namespace(CMMN10_NS) .idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class) .build(); exitCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERIA_REFS) .namespace(CMMN10_NS) .idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); itemControlChild = sequenceBuilder.element(ItemControl.class) .build(); entryCriterionCollection = sequenceBuilder.elementCollection(EntryCriterion.class) .build(); exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemImpl.java
1
请在Spring Boot框架中完成以下Java代码
public SseEmitter receiveByRequestId(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.receiveByRequestId(requestId); } /** * 根据请求ID停止某个请求的处理 * * @param requestId 请求的唯一标识符,用于识别和停止特定的请求 * @return 返回一个Result对象,表示停止请求的结果 * @author chenrui * @date 2025/2/25 11:42 */ @IgnoreAuth @GetMapping(value = "/stop/{requestId}") public Result<?> stop(@PathVariable(name = "requestId", required = true) String requestId) { return chatService.stop(requestId); } /** * 上传文件 * for [QQYUN-12135]AI聊天,上传图片提示非法token * * @param request * @param response * @return * @throws Exception * @author chenrui
* @date 2025/4/25 11:04 */ @IgnoreAuth @PostMapping(value = "/upload") public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws Exception { String bizPath = "airag"; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 获取上传文件对象 MultipartFile file = multipartRequest.getFile("file"); String savePath; if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) { savePath = CommonUtils.uploadLocal(file, bizPath, uploadpath); } else { savePath = CommonUtils.upload(file, bizPath, uploadType); } Result<?> result = new Result<>(); result.setMessage(savePath); result.setSuccess(true); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\controller\AiragChatController.java
2
请完成以下Java代码
final ProcessPreconditionsResolution rejectResolutionOrNull(final HUEditorRow document) { if (!document.isHUStatusActive()) { return ProcessPreconditionsResolution.rejectWithInternalReason("Only active HUs can be reversed"); } final List<I_M_ReceiptSchedule> receiptSchedules = getM_ReceiptSchedules(); if(receiptSchedules.isEmpty()) { return ProcessPreconditionsResolution.rejectWithInternalReason("Thre are no receipt schedules"); } return null; } @Override @RunOutOfTrx protected String doIt() throws Exception { final List<I_M_ReceiptSchedule> receiptSchedules = getM_ReceiptSchedules(); final List<HuId> huIdsToReverse = retrieveHUsToReverse(); boolean hasChanges = false; try { for (final I_M_ReceiptSchedule receiptSchedule : receiptSchedules) { final ReceiptCorrectHUsProcessor processor = ReceiptCorrectHUsProcessor.builder() .setM_ReceiptSchedule(receiptSchedule) .tolerateNoHUsFound() .build(); if (processor.isNoHUsFound()) { continue; } final List<Integer> asRepoIds = RepoIdAwares.asRepoIds(huIdsToReverse); final List<I_M_InOut> receiptsToReverse = processor.getReceiptsToReverseFromHUIds(asRepoIds); if (receiptsToReverse.isEmpty()) { continue; } processor.reverseReceipts(receiptsToReverse); hasChanges = true; } } finally { if (hasChanges) { // Reset the view's affected HUs getView().removeHUIdsAndInvalidate(huIdsToReverse); // Notify all active views that given receipt schedules were changed viewsRepo.notifyRecordsChangedAsync(TableRecordReferenceSet.of(TableRecordReference.ofSet(receiptSchedules))); } }
if (!hasChanges) { throw new AdempiereException("@NotFound@ @M_InOut_ID@"); } return MSG_OK; } @Override protected HUEditorView getView() { return getView(HUEditorView.class); } private List<I_M_ReceiptSchedule> getM_ReceiptSchedules() { return getView() .getReferencingDocumentPaths().stream() .map(referencingDocumentPath -> documentsCollection.getTableRecordReference(referencingDocumentPath).getModel(this, I_M_ReceiptSchedule.class)) .collect(GuavaCollectors.toImmutableList()); } private List<HuId> retrieveHUsToReverse() { // gh #1955: prevent an OutOfMemoryError final IQueryFilter<I_M_HU> processFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); return Services.get(IQueryBL.class).createQueryBuilder(I_M_HU.class, this) .filter(processFilter) .addOnlyActiveRecordsFilter() .create() .listIds() .stream() .map(HuId::ofRepoId) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReverseReceipt.java
1
请完成以下Java代码
public boolean isInOutApprovedForInvoicing() { return get_ValueAsBoolean(COLUMNNAME_IsInOutApprovedForInvoicing); } @Override public org.compiere.model.I_M_InOutLine getM_InOutLine() { return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class); } @Override public void setM_InOutLine(final org.compiere.model.I_M_InOutLine M_InOutLine) { set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine); } @Override public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } @Override public void setQtyDelivered (final @Nullable BigDecimal QtyDelivered) { set_ValueNoCheck (COLUMNNAME_QtyDelivered, QtyDelivered); } @Override public BigDecimal getQtyDelivered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDelivered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyDeliveredInUOM_Catch (final @Nullable BigDecimal QtyDeliveredInUOM_Catch) { set_ValueNoCheck (COLUMNNAME_QtyDeliveredInUOM_Catch, QtyDeliveredInUOM_Catch); } @Override public BigDecimal getQtyDeliveredInUOM_Catch() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM_Catch); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyDeliveredInUOM_Nominal (final @Nullable BigDecimal QtyDeliveredInUOM_Nominal) { set_Value (COLUMNNAME_QtyDeliveredInUOM_Nominal, QtyDeliveredInUOM_Nominal); } @Override public BigDecimal getQtyDeliveredInUOM_Nominal()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM_Nominal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyDeliveredInUOM_Override (final @Nullable BigDecimal QtyDeliveredInUOM_Override) { set_ValueNoCheck (COLUMNNAME_QtyDeliveredInUOM_Override, QtyDeliveredInUOM_Override); } @Override public BigDecimal getQtyDeliveredInUOM_Override() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM_Override); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoiced (final BigDecimal QtyInvoiced) { set_Value (COLUMNNAME_QtyInvoiced, QtyInvoiced); } @Override public BigDecimal getQtyInvoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoiced); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_InvoiceCandidate_InOutLine.java
1
请完成以下Java代码
public BankAccount getById(@NonNull final BankAccountId bankAccountId) { return bankAccountDAO.getById(bankAccountId); } @NonNull public BankAccount getByIdNotNull(@NonNull final BankAccountId bankAccountId) { return Optional.ofNullable(getById(bankAccountId)) .orElseThrow(() -> new AdempiereException("No Bank Account found for " + bankAccountId)); } public String createBankAccountName(@NonNull final BankAccountId bankAccountId) { final BankAccount bankAccount = getById(bankAccountId); final CurrencyCode currencyCode = currencyRepo.getCurrencyCodeById(bankAccount.getCurrencyId()); final BankId bankId = bankAccount.getBankId(); if (bankId != null) { final Bank bank = bankRepo.getById(bankId); return bank.getBankName() + "_" + currencyCode.toThreeLetterCode(); } return currencyCode.toThreeLetterCode(); } public DataImportConfigId getDataImportConfigIdForBankAccount(@NonNull final BankAccountId bankAccountId) { final BankId bankId = bankAccountDAO.getBankId(bankAccountId); return bankRepo.retrieveDataImportConfigIdForBank(bankId); } public boolean isImportAsSingleSummaryLine(@NonNull final BankAccountId bankAccountId) { final BankId bankId = bankAccountDAO.getBankId(bankAccountId); return bankRepo.isImportAsSingleSummaryLine(bankId); }
@NonNull public Optional<BankId> getBankIdBySwiftCode(@NonNull final String swiftCode) { return bankRepo.getBankIdBySwiftCode(swiftCode); } @NonNull public Optional<BankAccountId> getBankAccountId( @NonNull final BankId bankId, @NonNull final String accountNo) { return bankAccountDAO.getBankAccountId(bankId, accountNo); } @NonNull public Optional<BankAccountId> getBankAccountIdByIBAN(@NonNull final String iban) { return bankAccountDAO.getBankAccountIdByIBAN(iban); } @NonNull public Optional<String> getBankName(@NonNull final BankAccountId bankAccountId) { return Optional.of(bankAccountDAO.getById(bankAccountId)) .map(BankAccount::getBankId) .map(bankRepo::getById) .map(Bank::getBankName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\api\BankAccountService.java
1
请完成以下Java代码
public void validate(final I_C_CountryArea_Assign assignment) { final I_C_CountryArea countryArea = assignment.getC_CountryArea(); for (final I_C_CountryArea_Assign instance : retrieveCountryAreaAssignments(countryArea, assignment.getC_Country_ID())) { if (isTimeConflict(assignment, instance)) { throw new AdempiereException("Period overlaps with existing period: " + instance.getValidFrom() + ((instance.getValidTo() == null) ? "" : (" to " + instance.getValidTo())) + " for the country " + assignment.getC_Country() + " in area " + countryArea.getName()); } } } /** * @param newEntry * @param oldEntry * @return true if <code>newEntry</code>'s and <code>oldEntry</code>'s date/time intervals are overlapping */ protected boolean isTimeConflict(final I_C_CountryArea_Assign newEntry, final I_C_CountryArea_Assign oldEntry) { if (newEntry.equals(oldEntry)) { return false; }
if (newEntry.getValidFrom().compareTo(oldEntry.getValidFrom()) <= 0) { return (newEntry.getValidTo() == null) || (newEntry.getValidTo().compareTo(oldEntry.getValidFrom()) > 0); } else { return (oldEntry.getValidTo() == null) || (oldEntry.getValidTo().compareTo(newEntry.getValidFrom()) > 0); } } public boolean isMemberOf(@NonNull final CountryAreaId countryAreaId, @NonNull final CountryId countryId) { return retrieveCountryAreaAssignments(Env.getCtx(), countryAreaId.getRepoId(), ITrx.TRXNAME_None) .stream() .map(I_C_CountryArea_Assign::getC_Country_ID) .map(CountryId::ofRepoId) .anyMatch(countryId::equals); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\CountryAreaBL.java
1
请完成以下Java代码
protected boolean matchProductName(String productName) { return this.productName != null && this.productName.equalsIgnoreCase(productName); } /** * Return the driver class name. * @return the class name or {@code null} */ public @Nullable String getDriverClassName() { return this.driverClassName; } /** * Return the XA driver source class name. * @return the class name or {@code null} */ public @Nullable String getXaDataSourceClassName() { return this.xaDataSourceClassName; } /** * Return the validation query. * @return the validation query or {@code null} */ public @Nullable String getValidationQuery() { return this.validationQuery; } /** * Find a {@link DatabaseDriver} for the given URL. * @param url the JDBC URL * @return the database driver or {@link #UNKNOWN} if not found */ public static DatabaseDriver fromJdbcUrl(@Nullable String url) {
if (StringUtils.hasLength(url)) { Assert.isTrue(url.startsWith("jdbc"), "'url' must start with \"jdbc\""); String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH); for (DatabaseDriver driver : values()) { for (String urlPrefix : driver.getUrlPrefixes()) { String prefix = ":" + urlPrefix + ":"; if (driver != UNKNOWN && urlWithoutPrefix.startsWith(prefix)) { return driver; } } } } return UNKNOWN; } /** * Find a {@link DatabaseDriver} for the given product name. * @param productName product name * @return the database driver or {@link #UNKNOWN} if not found */ public static DatabaseDriver fromProductName(@Nullable String productName) { if (StringUtils.hasLength(productName)) { for (DatabaseDriver candidate : values()) { if (candidate.matchProductName(productName)) { return candidate; } } } return UNKNOWN; } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\DatabaseDriver.java
1
请完成以下Java代码
public class Player implements Comparable<Player> { private String name; private int age; private int numberOfPlayed; private int numberOfWins; public Player(String name, int age, int numberOfPlayed, int numberOfWins) { this.name = name; this.age = age; this.numberOfPlayed = numberOfPlayed; this.numberOfWins = numberOfWins; } public String getName() { return name; } public int getAge() {
return age; } public int getNumberOfPlayed() { return numberOfPlayed; } public int getNumberOfWins() { return numberOfWins; } @Override public int compareTo(Player o) { return Integer.compare(age, o.age); } }
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\treeset\collectintotreeset\Player.java
1
请完成以下Java代码
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { if (force) { notificationRequestDao.removeById(tenantId, id.getId()); } else { NotificationRequest notificationRequest = findNotificationRequestById(tenantId, (NotificationRequestId) id); deleteNotificationRequest(tenantId, notificationRequest); } } @Override public PageData<NotificationRequest> findScheduledNotificationRequests(PageLink pageLink) { return notificationRequestDao.findAllByStatus(NotificationRequestStatus.SCHEDULED, pageLink); } @Override public void updateNotificationRequest(TenantId tenantId, NotificationRequestId requestId, NotificationRequestStatus requestStatus, NotificationRequestStats stats) { notificationRequestDao.updateById(tenantId, requestId, requestStatus, stats); } // notifications themselves are left in the database until removed by ttl @Override public void deleteNotificationRequestsByTenantId(TenantId tenantId) { notificationRequestDao.removeByTenantId(tenantId); } @Override public void deleteByTenantId(TenantId tenantId) { deleteNotificationRequestsByTenantId(tenantId); } @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findNotificationRequestById(tenantId, new NotificationRequestId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(notificationRequestDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_REQUEST; } private static class NotificationRequestValidator extends DataValidator<NotificationRequest> {} }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationRequestService.java
1
请完成以下Java代码
public void setFlashPromotionLimit(Integer flashPromotionLimit) { this.flashPromotionLimit = flashPromotionLimit; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @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(", flashPromotionId=").append(flashPromotionId); sb.append(", flashPromotionSessionId=").append(flashPromotionSessionId); sb.append(", productId=").append(productId); sb.append(", flashPromotionPrice=").append(flashPromotionPrice); sb.append(", flashPromotionCount=").append(flashPromotionCount); sb.append(", flashPromotionLimit=").append(flashPromotionLimit); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotionProductRelation.java
1
请完成以下Java代码
public void setA_Asset_ID (int A_Asset_ID) { if (A_Asset_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Asset_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Asset_ID, Integer.valueOf(A_Asset_ID)); } /** Get Asset. @return Asset used internally or by customers */ public int getA_Asset_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Asset Retirement. @param A_Asset_Retirement_ID Internally used asset is not longer used. */ public void setA_Asset_Retirement_ID (int A_Asset_Retirement_ID) { if (A_Asset_Retirement_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Asset_Retirement_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Asset_Retirement_ID, Integer.valueOf(A_Asset_Retirement_ID)); } /** Get Asset Retirement. @return Internally used asset is not longer used. */ public int getA_Asset_Retirement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Retirement_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Retirement_ID())); } /** Set Market value Amount. @param AssetMarketValueAmt Market value of the asset */ public void setAssetMarketValueAmt (BigDecimal AssetMarketValueAmt) { set_Value (COLUMNNAME_AssetMarketValueAmt, AssetMarketValueAmt); } /** Get Market value Amount. @return Market value of the asset */ public BigDecimal getAssetMarketValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetMarketValueAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Asset value. @param AssetValueAmt Book Value of the asset */ public void setAssetValueAmt (BigDecimal AssetValueAmt) {
set_Value (COLUMNNAME_AssetValueAmt, AssetValueAmt); } /** Get Asset value. @return Book Value of the asset */ public BigDecimal getAssetValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetValueAmt); if (bd == null) return Env.ZERO; return bd; } public I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException { return (I_C_InvoiceLine)MTable.get(getCtx(), I_C_InvoiceLine.Table_Name) .getPO(getC_InvoiceLine_ID(), get_TrxName()); } /** Set Invoice Line. @param C_InvoiceLine_ID Invoice Detail Line */ public void setC_InvoiceLine_ID (int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_Value (COLUMNNAME_C_InvoiceLine_ID, null); else set_Value (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID)); } /** Get Invoice Line. @return Invoice Detail Line */ public int getC_InvoiceLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Retirement.java
1
请完成以下Java代码
public void execute(DelegateExecution execution) { CommandContext commandContext = Context.getCommandContext(); ExecutionEntity executionEntity = (ExecutionEntity) execution; String signalName = null; if (StringUtils.isNotEmpty(signalEventDefinition.getSignalRef())) { signalName = signalEventDefinition.getSignalRef(); } else { Expression signalExpression = commandContext .getProcessEngineConfiguration() .getExpressionManager() .createExpression(signalEventDefinition.getSignalExpression()); signalName = signalExpression.getValue(execution).toString(); } commandContext.getEventSubscriptionEntityManager().insertSignalEvent(signalName, signal, executionEntity); } @Override public void trigger(DelegateExecution execution, String triggerName, Object triggerData) { ExecutionEntity executionEntity = (ExecutionEntity) execution; BoundaryEvent boundaryEvent = (BoundaryEvent) execution.getCurrentFlowElement(); if (boundaryEvent.isCancelActivity()) { String eventName = null; if (signal != null) { eventName = signal.getName(); } else {
eventName = signalEventDefinition.getSignalRef(); } EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager(); List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions(); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if ( eventSubscription instanceof SignalEventSubscriptionEntity && eventSubscription.getEventName().equals(eventName) ) { eventSubscriptionEntityManager.delete(eventSubscription); } } } super.trigger(executionEntity, triggerName, triggerData); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\BoundarySignalEventActivityBehavior.java
1
请完成以下Java代码
public List<String> getDependsOnColumnNames() { return columnNames; } @Override public AggregationKey buildAggregationKey(I_C_Invoice_Candidate model) { final List<Object> keyValues = getValues(model); final ArrayKey key = Util.mkKey(keyValues.toArray()); final AggregationId aggregationId = null; return new AggregationKey(key, aggregationId); } private List<Object> getValues(@NonNull final I_C_Invoice_Candidate ic) { final List<Object> values = new ArrayList<>(); final I_C_DocType invoiceDocType = Optional.ofNullable(DocTypeId.ofRepoIdOrNull(ic.getC_DocTypeInvoice_ID())) .map(docTypeBL::getById) .orElse(null); final DocTypeId docTypeIdToBeUsed = Optional.ofNullable(invoiceDocType) .filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() <= 0) .map(I_C_DocType::getC_DocType_ID) .map(DocTypeId::ofRepoId) .orElse(null); values.add(docTypeIdToBeUsed); values.add(ic.getAD_Org_ID()); final BPartnerLocationAndCaptureId billLocation = invoiceCandBL.getBillLocationId(ic, false); values.add(billLocation.getBpartnerRepoId()); values.add(billLocation.getBPartnerLocationRepoId()); final int currencyId = ic.getC_Currency_ID(); values.add(currencyId <= 0 ? 0 : currencyId);
// Dates // 08511 workaround - we don't add dates in header aggregation key values.add(null); // ic.getDateInvoiced()); values.add(null); // ic.getDateAcct()); // task 08437 // IsSOTrx values.add(ic.isSOTrx()); // Pricing System final int pricingSystemId = IPriceListDAO.M_PricingSystem_ID_None; // 08511 workaround values.add(pricingSystemId); values.add(invoiceCandBL.isTaxIncluded(ic)); // task 08451 final Boolean compact = true; values.add(compact ? toHashcode(ic.getDescriptionHeader()) : ic.getDescriptionHeader()); values.add(compact ? toHashcode(ic.getDescriptionBottom()) : ic.getDescriptionBottom()); final DocTypeInvoicingPoolId docTypeInvoicingPoolId = Optional.ofNullable(invoiceDocType) .filter(docType -> docType.getC_DocType_Invoicing_Pool_ID() > 0) .map(I_C_DocType::getC_DocType_Invoicing_Pool_ID) .map(DocTypeInvoicingPoolId::ofRepoId) .orElse(null); values.add(docTypeInvoicingPoolId); return values; } private static int toHashcode(final String s) { if (Check.isEmpty(s, true)) { return 0; } return s.hashCode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\agg\key\impl\ICHeaderAggregationKeyBuilder_OLD.java
1
请完成以下Java代码
public final class PrintMessageWithoutMainMethod { //Using Static Blocks static { System.out.println("Hello World!!"); System.exit(0); } //Using Nested Classes static { NestedClass.printMessage(); } //Executing Code During Class Initialization private static final int STATUS = getStatus(); private static int getStatus() {
System.out.println("Hello World!!"); System.exit(0); return 0; } public static void main(String[] args) { } static class NestedClass { static void printMessage() { System.out.println("Message from nested class"); } } }
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\printmessagewithoutmain\PrintMessageWithoutMainMethod.java
1
请在Spring Boot框架中完成以下Java代码
public class Contract extends AbstractEntity { @NonNull private java.sql.Date dateFrom; @NonNull private java.sql.Date dateTo; @ManyToOne(fetch = FetchType.EAGER) @NonNull private BPartner bpartner; private String rfq_uuid; @OneToMany(fetch = FetchType.EAGER, mappedBy = "contract", cascade = CascadeType.REMOVE) private List<ContractLine> contractLines = new ArrayList<>(); public Contract() { } @Override protected void toString(final MoreObjects.ToStringHelper toStringHelper) { toStringHelper .add("dateFrom", dateFrom) .add("dateTo", dateTo) .add("lines", contractLines) .add("bpartner", bpartner); } public BPartner getBpartner() { return bpartner; } public void setBpartner(final BPartner bpartner) { this.bpartner = bpartner; } public LocalDate getDateFrom() { return DateUtils.toLocalDate(dateFrom); } public void setDateFrom(@NonNull final LocalDate dateFrom) { this.dateFrom = DateUtils.toSqlDate(dateFrom); } public LocalDate getDateTo() { return DateUtils.toLocalDate(dateTo); } public void setDateTo(@NonNull final LocalDate dateTo) { this.dateTo = DateUtils.toSqlDate(dateTo); } public void setRfq_uuid(final String rfq_uuid) { this.rfq_uuid = rfq_uuid; } public boolean isRfq() { return rfq_uuid != null; } public List<ContractLine> getContractLines() { return Collections.unmodifiableList(contractLines); } @Nullable public ContractLine getContractLineForProductOrNull(final Product product)
{ for (final ContractLine contractLine : getContractLines()) { if (Product.COMPARATOR_Id.compare(contractLine.getProduct(), product) != 0) { continue; } return contractLine; } return null; } public Collection<Product> getProducts() { final Set<Product> products = new TreeSet<>(Product.COMPARATOR_Id); for (final ContractLine contractLine : getContractLines()) { if (contractLine.isDeleted()) { continue; } final Product product = contractLine.getProduct(); if (product.isDeleted()) { continue; } products.add(product); } return products; } public boolean matchesDate(final LocalDate date) { return DateUtils.between(date, getDateFrom(), getDateTo()); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Contract.java
2
请完成以下Java代码
private AsyncBatchId createAsyncBatch() { // Create Async Batch for tracking return asyncBatchBL.newAsyncBatch() .setContext(getCtx()) .setAD_PInstance_Creator_ID(getPinstanceId()) .setOrgId(p_OrgId) .setC_Async_Batch_Type(C_Async_Batch_InternalName_InvoiceCandidate_Processing) .setName(C_Async_Batch_InternalName_InvoiceCandidate_Processing) .buildAndEnqueue(); } @Override protected String doIt() throws Exception { final AsyncBatchId asyncBatchId = createAsyncBatch(); final I_C_Async_Batch asyncBatch = asyncBatchBL.getAsyncBatchById(asyncBatchId); asyncBatchDAO.setPInstance_IDAndSave(asyncBatch, getPinstanceId()); final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(getCtx(), InvoiceEnqueueingWorkpackageProcessor.class); queue .newWorkPackage() .setC_Async_Batch(asyncBatchBL.getAsyncBatchById(asyncBatchId)) .parameters(invoicingParams.asMap()) .buildAndEnqueue(); return MSG_OK; } private int createSelection() { final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = createICQueryBuilder(); // // Create selection and return how many items were added final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); final int selectionCount = queryBuilder .create() .setRequiredAccess(Access.READ) .createSelection(adPInstanceId); return selectionCount; } private IQueryBuilder<I_C_Invoice_Candidate> createICQueryBuilder() { final IQuery<I_M_Product_Category> subQuery_ProductcategFilter = queryBL
.createQueryBuilder(I_M_Product_Category.class) .addEqualsFilter(I_M_Product_Category.COLUMNNAME_M_Product_Category_ID, p_ProductCategoryId) .setJoinOr() .addEqualsFilter(I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID, p_ProductCategoryId) .create(); final IQuery<I_M_Product> subQuery_Product = queryBL .createQueryBuilder(I_M_Product.class) .addInSubQueryFilter() .matchingColumnNames(I_M_Product.COLUMNNAME_M_Product_Category_ID, I_M_Product_Category.COLUMNNAME_M_Product_Category_ID) .subQuery(subQuery_ProductcategFilter) .end() .create(); return queryBL .createQueryBuilder(I_C_Invoice_Candidate.class, getCtx(), ITrx.TRXNAME_None) .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_AD_Org_ID, p_OrgId) .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false) .addInSubQueryFilter() .matchingColumnNames(I_C_Invoice_Candidate.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID) .subQuery(subQuery_Product) .end() .addOnlyContextClient(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Invoice_Candidate_EnqueueSelectionForInvoicingAndPDFConcatenating.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { yesB_actionPerformed(e); } }); yesB.setText(Local.getString("Yes")); //yesB.setFocusable(false); this.getRootPane().setDefaultButton(yesB); noB.setText(Local.getString("No")); noB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { noB_actionPerformed(e); } }); // noB.setFocusable(false); buttonsPanel.add(yesB, null); getContentPane().add(panel1); panel1.add(areaPanel, BorderLayout.CENTER); areaPanel.add(textLabel, BorderLayout.WEST); panel1.add(buttonsPanel, BorderLayout.SOUTH); buttonsPanel.add(yesAllB, null); buttonsPanel.add(noB, null); buttonsPanel.add(cancelB, null); } void yesAllB_actionPerformed(ActionEvent e) { option = YES_TO_ALL_OPTION; this.dispose(); }
void cancelB_actionPerformed(ActionEvent e) { option = CANCEL_OPTION; this.dispose(); } void yesB_actionPerformed(ActionEvent e) { option = YES_OPTION; this.dispose(); } void noB_actionPerformed(ActionEvent e) { option = NO_OPTION; this.dispose(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\ReplaceOptionsDialog.java
1
请完成以下Java代码
public void updateDeliveryToAddress(final I_C_Order order) { documentLocationBL.updateRenderedAddressAndCapturedLocation(OrderDocumentLocationAdapterFactory.deliveryLocationAdapter(order)); } @CalloutMethod(columnNames = I_C_Order.COLUMNNAME_DropShip_User_ID, skipIfCopying = true) public void updateDropShipUserRenderedAddress(final I_C_Order order) { documentLocationBL.updateRenderedAddress(OrderDocumentLocationAdapterFactory.deliveryLocationAdapter(order)); } @CalloutMethod(columnNames = { I_C_Order.COLUMNNAME_IsUseHandOver_Location, I_C_Order.COLUMNNAME_HandOver_Partner_ID, I_C_Order.COLUMNNAME_HandOver_Location_ID }, skipIfCopying = true) public void updateHandOverAddress(final I_C_Order order) { documentLocationBL.updateRenderedAddressAndCapturedLocation(OrderDocumentLocationAdapterFactory.handOverLocationAdapter(order)); } @CalloutMethod(columnNames = I_C_Order.COLUMNNAME_HandOver_User_ID, skipIfCopying = true) public void updateHandOverUserRenderedAddress(final I_C_Order order) { documentLocationBL.updateRenderedAddress(OrderDocumentLocationAdapterFactory.handOverLocationAdapter(order)); } @CalloutMethod(columnNames = { I_C_Order.COLUMNNAME_C_BPartner_Location_ID, I_C_Order.COLUMNNAME_AD_User_ID }) public void setContactDetails(final I_C_Order order) { if (order.getC_BPartner_Location_ID() <= 0) { return; } final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(order.getC_BPartner_ID(), order.getC_BPartner_Location_ID()); final I_C_BPartner_Location bPartnerLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(bPartnerLocationId); Check.assumeNotNull(bPartnerLocationRecord, "C_BPartner_Location cannot be missing for webui selection! Id: {}", bPartnerLocationId); final Optional<I_AD_User> userRecord = Optional.ofNullable(UserId.ofRepoIdOrNull(order.getAD_User_ID())) .map(userDAO::getById);
if (userRecord.isPresent()) { final I_AD_User user = userRecord.get(); order.setBPartnerName(firstNotBlank(user.getName(), bPartnerLocationRecord.getBPartnerName())); order.setEMail(firstNotBlank(user.getEMail(), bPartnerLocationRecord.getEMail())); order.setPhone(firstNotBlank(user.getPhone(), bPartnerLocationRecord.getPhone())); } else { order.setBPartnerName(bPartnerLocationRecord.getBPartnerName()); order.setEMail(bPartnerLocationRecord.getEMail()); order.setPhone(bPartnerLocationRecord.getPhone()); } } @CalloutMethod(columnNames = { I_C_Order.COLUMNNAME_M_Shipper_ID }, skipIfCopying = true) public void updateDeliveryViaRule(final I_C_Order order) { final ShipperId shipperId = ShipperId.ofRepoIdOrNull(order.getM_Shipper_ID()); if (shipperId != null) { order.setDeliveryViaRule(X_C_Order.DELIVERYVIARULE_Shipper); } else { order.setDeliveryViaRule(X_C_Order.DELIVERYVIARULE_Pickup); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\callout\C_Order.java
1
请在Spring Boot框架中完成以下Java代码
public class Order { @Id @Column(name = "order_id") private Long orderId; @Column(name = "customer_id") private Long customerId; @Column(name = "total_price") private BigDecimal totalPrice; @Enumerated(EnumType.STRING) @Column(name = "order_status") private Status orderStatus; @Column(name = "order_date") private LocalDate orderDate; @Column(name = "delivery_address") private String deliveryAddress; public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public BigDecimal getTotalPrice() { return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } public Status getOrderStatus() { return orderStatus; } public void setOrderStatus(Status orderStatus) { this.orderStatus = orderStatus; } public LocalDate getOrderDate() { return orderDate;
} public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public String getDeliveryAddress() { return deliveryAddress; } public void setDeliveryAddress(String deliveryAddress) { this.deliveryAddress = deliveryAddress; } protected Order() {} public Order(Long orderId, Long customerId, BigDecimal totalPrice, Status orderStatus, LocalDate orderDate, String deliveryAddress) { this.orderId = orderId; this.customerId = customerId; this.totalPrice = totalPrice; this.orderStatus = orderStatus; this.orderDate = orderDate; this.deliveryAddress = deliveryAddress; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Order order = (Order) o; return Objects.equals(orderId, order.orderId); } @Override public int hashCode() { return Objects.hash(orderId); } }
repos\springboot-demo-master\sharding-jdbc\src\main\java\com\et\sharding\jdbc\Order.java
2
请在Spring Boot框架中完成以下Java代码
private Map<String, String> getIdentityProviderUrlMap(String authRequestPrefixUrl, String[] authRequestQueryParams, RelyingPartyRegistrationRepository idpRepo) { Map<String, String> idps = new LinkedHashMap<>(); if (idpRepo instanceof Iterable) { Iterable<RelyingPartyRegistration> repo = (Iterable<RelyingPartyRegistration>) idpRepo; StringBuilder authRequestQuery = new StringBuilder("?"); for (String authRequestQueryParam : authRequestQueryParams) { authRequestQuery.append(authRequestQueryParam + "&"); } authRequestQuery.deleteCharAt(authRequestQuery.length() - 1); String authenticationRequestUriQuery = authRequestPrefixUrl + authRequestQuery; repo.forEach( (p) -> idps.put(authenticationRequestUriQuery.replace("{registrationId}", p.getRegistrationId()), p.getRegistrationId())); } return idps; } private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> getAuthenticationRequestRepository( B http) { Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> repository = getBeanOrNull(http, Saml2AuthenticationRequestRepository.class); if (repository == null) { return new HttpSessionSaml2AuthenticationRequestRepository(); } return repository; } private <C> C getSharedOrBean(B http, Class<C> clazz) { C shared = http.getSharedObject(clazz); if (shared != null) { return shared; } return getBeanOrNull(http, clazz); } private <C> C getBeanOrNull(B http, Class<C> clazz) { ApplicationContext context = http.getSharedObject(ApplicationContext.class); if (context == null) { return null; } return context.getBeanProvider(clazz).getIfUnique(); } private <C> void setSharedObject(B http, Class<C> clazz, C object) { if (http.getSharedObject(clazz) == null) { http.setSharedObject(clazz, object); } }
static class PathQueryRequestMatcher implements RequestMatcher { private final RequestMatcher matcher; PathQueryRequestMatcher(RequestMatcher pathMatcher, String... params) { List<RequestMatcher> matchers = new ArrayList<>(); matchers.add(pathMatcher); for (String param : params) { String[] parts = param.split("="); if (parts.length == 1) { matchers.add(new ParameterRequestMatcher(parts[0])); } else { matchers.add(new ParameterRequestMatcher(parts[0], parts[1])); } } this.matcher = new AndRequestMatcher(matchers); } @Override public boolean matches(HttpServletRequest request) { return matcher(request).isMatch(); } @Override public MatchResult matcher(HttpServletRequest request) { return this.matcher.matcher(request); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2LoginConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
private void forwardToDeviceActor(TransportToDeviceActorMsg toDeviceActorMsg, TbCallback callback) { if (statsEnabled) { stats.log(toDeviceActorMsg); } actorContext.tell(new TransportToDeviceActorMsgWrapper(toDeviceActorMsg, callback)); } private void forwardToEventService(ErrorEventProto eventProto, TbCallback callback) { Event event = ErrorEvent.builder() .tenantId(toTenantId(eventProto.getTenantIdMSB(), eventProto.getTenantIdLSB())) .entityId(new UUID(eventProto.getEntityIdMSB(), eventProto.getEntityIdLSB())) .serviceId(eventProto.getServiceId()) .ts(System.currentTimeMillis()) .method(eventProto.getMethod()) .error(eventProto.getError()) .build(); forwardToEventService(event, callback); } private void forwardToEventService(LifecycleEventProto eventProto, TbCallback callback) { Event event = LifecycleEvent.builder() .tenantId(toTenantId(eventProto.getTenantIdMSB(), eventProto.getTenantIdLSB())) .entityId(new UUID(eventProto.getEntityIdMSB(), eventProto.getEntityIdLSB())) .serviceId(eventProto.getServiceId()) .ts(System.currentTimeMillis()) .lcEventType(eventProto.getLcEventType()) .success(eventProto.getSuccess()) .error(StringUtils.isNotEmpty(eventProto.getError()) ? eventProto.getError() : null) .build(); forwardToEventService(event, callback); } private void forwardToEventService(Event event, TbCallback callback) { DonAsynchron.withCallback(actorContext.getEventService().saveAsync(event), result -> callback.onSuccess(),
callback::onFailure, actorContext.getDbCallbackExecutor()); } void forwardToRuleEngineCallService(TransportProtos.RestApiCallResponseMsgProto restApiCallResponseMsg, TbCallback callback) { ruleEngineCallService.onQueueMsg(restApiCallResponseMsg, callback); } private void throwNotHandled(Object msg, TbCallback callback) { log.warn("Message not handled: {}", msg); callback.onFailure(new RuntimeException("Message not handled!")); } private TenantId toTenantId(long tenantIdMSB, long tenantIdLSB) { return TenantId.fromUUID(new UUID(tenantIdMSB, tenantIdLSB)); } @Override protected void stopConsumers() { super.stopConsumers(); mainConsumer.stop(); mainConsumer.awaitStop(); usageStatsConsumer.stop(); firmwareStatesConsumer.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbCoreConsumerService.java
2
请在Spring Boot框架中完成以下Java代码
public String toString() { return "ItemHint{name='" + this.name + "', values=" + this.values + ", providers=" + this.providers + '}'; } /** * A hint for a value. */ public static class ValueHint { private final Object value; private final String description; public ValueHint(Object value, String description) { this.value = value; this.description = description; } public Object getValue() { return this.value; } public String getDescription() { return this.description; } @Override public String toString() { return "ValueHint{value=" + this.value + ", description='" + this.description + '\'' + '}'; } } /** * A value provider. */ public static class ValueProvider { private final String name; private final Map<String, Object> parameters; public ValueProvider(String name, Map<String, Object> parameters) { this.name = name;
this.parameters = parameters; } public String getName() { return this.name; } public Map<String, Object> getParameters() { return this.parameters; } @Override public String toString() { return "ValueProvider{name='" + this.name + "', parameters=" + this.parameters + '}'; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemHint.java
2
请完成以下Java代码
public void setTargetRef(String targetRef) { this.targetRef = targetRef; } public String getMessageRef() { return messageRef; } public void setMessageRef(String messageRef) { this.messageRef = messageRef; } @Override public String toString() { return sourceRef + " --> " + targetRef; }
@Override public MessageFlow clone() { MessageFlow clone = new MessageFlow(); clone.setValues(this); return clone; } public void setValues(MessageFlow otherFlow) { super.setValues(otherFlow); setName(otherFlow.getName()); setSourceRef(otherFlow.getSourceRef()); setTargetRef(otherFlow.getTargetRef()); setMessageRef(otherFlow.getMessageRef()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MessageFlow.java
1
请完成以下Java代码
public void subscribe() { consumer.subscribe(); } public void subscribe(Set<TopicPartitionInfo> partitions) { consumer.subscribe(partitions); } public void launch() { log.info("[{}] Launching consumer", name); consumerTask = consumerExecutor.submit(() -> { if (threadPrefix != null) { ThingsBoardThreadFactory.addThreadNamePrefix(threadPrefix); } try { consumerLoop(consumer); } catch (Throwable e) { log.error("Failure in consumer loop", e); } log.info("[{}] Consumer stopped", name); }); } private void consumerLoop(TbQueueConsumer<M> consumer) { while (!stopped && !consumer.isStopped()) { try { List<M> msgs = consumer.poll(pollInterval); if (msgs.isEmpty()) { continue; } msgPackProcessor.process(msgs, consumer); } catch (Exception e) { if (!consumer.isStopped()) { log.warn("Failed to process messages from queue", e); try { Thread.sleep(pollInterval); } catch (InterruptedException interruptedException) { log.trace("Failed to wait until the server has capacity to handle new requests", interruptedException); } }
} } } public void stop() { log.debug("[{}] Stopping consumer", name); stopped = true; consumer.unsubscribe(); try { if (consumerTask != null) { consumerTask.get(10, TimeUnit.SECONDS); } } catch (InterruptedException | ExecutionException | TimeoutException e) { log.error("[{}] Failed to await consumer loop stop", name, e); } } public interface MsgPackProcessor<M extends TbQueueMsg> { void process(List<M> msgs, TbQueueConsumer<M> consumer) throws Exception; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\consumer\QueueConsumerManager.java
1
请完成以下Java代码
public int getPort() { return this.port != null ? this.port : DEFAULT_LOCATOR_PORT; } @Override public int compareTo(Locator other) { int result = this.getHost().compareTo(other.getHost()); return result != 0 ? result : (this.getPort() - other.getPort()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Locator)) { return false; } Locator that = (Locator) obj;
return this.getHost().equals(that.getHost()) && this.getPort() == that.getPort(); } @Override public int hashCode() { int hashValue = 17; hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getHost()); hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPort()); return hashValue; } @Override public String toString() { return String.format("%s[%d]", getHost(), getPort()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\CloudCacheService.java
1
请在Spring Boot框架中完成以下Java代码
public ClientRegionFactoryBean<Object, Object> yellowPagesRegion(GemFireCache gemfireCache) { ClientRegionFactoryBean<Object, Object> clientRegion = new ClientRegionFactoryBean<>(); clientRegion.setCache(gemfireCache); clientRegion.setClose(false); clientRegion.setShortcut(ClientRegionShortcut.CACHING_PROXY); clientRegion.setRegionConfigurers( interestRegisteringRegionConfigurer(), subscriptionCacheListenerRegionConfigurer() ); return clientRegion; } // end::region[] // tag::interest-registration[] @Bean RegionConfigurer interestRegisteringRegionConfigurer() { return new RegionConfigurer() { @Override @SuppressWarnings("unchecked") public void configure(String beanName, ClientRegionFactoryBean<?, ?> clientRegion) { Interest interest = new RegexInterest(".*", InterestResultPolicy.NONE, false, true); clientRegion.setInterests(ArrayUtils.asArray(interest)); } }; } // end::interest-registration[] // tag::subscription-cache-listener[] @Bean RegionConfigurer subscriptionCacheListenerRegionConfigurer() { return new RegionConfigurer() { @Override
@SuppressWarnings("unchecked") public void configure(String beanName, ClientRegionFactoryBean<?, ?> clientRegion) { CacheListener subscriptionCacheListener = new AbstractCommonEventProcessingCacheListener() { @Override protected void processEntryEvent(EntryEvent event, EntryEventType eventType) { if (event.isOriginRemote()) { System.err.printf("[%1$s] EntryEvent for [%2$s] with value [%3$s]%n", event.getKey(), event.getOperation(), event.getNewValue()); } } }; clientRegion.setCacheListeners(ArrayUtils.asArray(subscriptionCacheListener)); } }; } // end::subscription-cache-listener[] } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\near\src\main\java\example\app\caching\near\client\config\GeodeConfiguration.java
2
请完成以下Java代码
public final boolean isPoolable() throws SQLException { return getStatementImpl().isPoolable(); } @Override public final void closeOnCompletion() throws SQLException { getStatementImpl().closeOnCompletion(); } @Override public final boolean isCloseOnCompletion() throws SQLException { return getStatementImpl().isCloseOnCompletion(); } @Override public final String getSql() { return this.vo.getSql(); } protected final String convertSqlAndSet(final String sql) { final String sqlConverted = DB.getDatabase().convertStatement(sql); vo.setSql(sqlConverted); MigrationScriptFileLoggerHolder.logMigrationScript(sql); return sqlConverted; } @Override public final void commit() throws SQLException { if (this.ownedConnection != null && !this.ownedConnection.getAutoCommit()) { this.ownedConnection.commit(); } }
@Nullable private static Trx getTrx(@NonNull final CStatementVO vo) { final ITrxManager trxManager = Services.get(ITrxManager.class); final String trxName = vo.getTrxName(); if (trxManager.isNull(trxName)) { return (Trx)ITrx.TRX_None; } else { final ITrx trx = trxManager.get(trxName, false); // createNew=false // NOTE: we assume trx if of type Trx because we need to invoke getConnection() return (Trx)trx; } } @Override public String toString() { return "AbstractCStatementProxy [ownedConnection=" + this.ownedConnection + ", closed=" + closed + ", p_vo=" + vo + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\AbstractCStatementProxy.java
1
请完成以下Java代码
public String asString() { return "spring.cloud.gateway.route.id"; } }, /** * HTTP Method. */ METHOD { @Override public String asString() { return "http.method"; } }, /** * HTTP Status. */ STATUS { @Override public String asString() { return "http.status_code"; } }, /** * HTTP URI taken from the Route. */ ROUTE_URI {
@Override public String asString() { return "spring.cloud.gateway.route.uri"; } } } @NonNullApi enum HighCardinalityKeys implements KeyName { /** * Full HTTP URI. */ URI { @Override public String asString() { return "http.uri"; } } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\observation\GatewayDocumentedObservation.java
1
请完成以下Java代码
public String getPhone () { return (String)get_Value(COLUMNNAME_Phone); } public I_R_Group getR_Group() throws RuntimeException { return (I_R_Group)MTable.get(getCtx(), I_R_Group.Table_Name) .getPO(getR_Group_ID(), get_TrxName()); } /** Set Group. @param R_Group_ID Request Group */ public void setR_Group_ID (int R_Group_ID) { if (R_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_R_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_R_Group_ID, Integer.valueOf(R_Group_ID)); } /** Get Group. @return Request Group */ public int getR_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Group_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(); } public I_R_Status getR_Status() throws RuntimeException { return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name) .getPO(getR_Status_ID(), get_TrxName()); } /** Set Status. @param R_Status_ID Request Status */ public void setR_Status_ID (int R_Status_ID) { throw new IllegalArgumentException ("R_Status_ID is virtual column"); } /** Get Status. @return Request Status */ public int getR_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_R_Group_Prospect.java
1
请完成以下Java代码
public @Nullable Duration getTimeout() { return this.timeout; } public void setTimeout(@Nullable Duration timeout) { this.timeout = timeout; } /** * Return the {@link SessionTrackingMode session tracking modes}. * @return the session tracking modes */ public @Nullable Set<Session.SessionTrackingMode> getTrackingModes() { return this.trackingModes; } public void setTrackingModes(@Nullable Set<Session.SessionTrackingMode> trackingModes) { this.trackingModes = trackingModes; } /** * Return whether to persist session data between restarts. * @return {@code true} to persist session data between restarts. */ public boolean isPersistent() { return this.persistent; } public void setPersistent(boolean persistent) { this.persistent = persistent; } /** * Return the directory used to store session data. * @return the session data store directory */ public @Nullable File getStoreDir() { return this.storeDir; } public void setStoreDir(@Nullable File storeDir) { this.sessionStoreDirectory.setDirectory(storeDir); this.storeDir = storeDir; }
public Cookie getCookie() { return this.cookie; } public SessionStoreDirectory getSessionStoreDirectory() { return this.sessionStoreDirectory; } /** * Available session tracking modes (mirrors * {@link jakarta.servlet.SessionTrackingMode}). */ public enum SessionTrackingMode { /** * Send a cookie in response to the client's first request. */ COOKIE, /** * Rewrite the URL to append a session ID. */ URL, /** * Use SSL build-in mechanism to track the session. */ SSL } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\Session.java
1
请完成以下Java代码
public ReferredDocumentType1Choice createReferredDocumentType1Choice() { return new ReferredDocumentType1Choice(); } /** * Create an instance of {@link ReferredDocumentType2 } * */ public ReferredDocumentType2 createReferredDocumentType2() { return new ReferredDocumentType2(); } /** * Create an instance of {@link RegulatoryAuthority2 } * */ public RegulatoryAuthority2 createRegulatoryAuthority2() { return new RegulatoryAuthority2(); } /** * Create an instance of {@link RegulatoryReporting3 } * */ public RegulatoryReporting3 createRegulatoryReporting3() { return new RegulatoryReporting3(); } /** * Create an instance of {@link RemittanceAmount1 } * */ public RemittanceAmount1 createRemittanceAmount1() { return new RemittanceAmount1(); } /** * Create an instance of {@link RemittanceInformation5CH } * */ public RemittanceInformation5CH createRemittanceInformation5CH() { return new RemittanceInformation5CH(); } /** * Create an instance of {@link ServiceLevel8Choice } * */
public ServiceLevel8Choice createServiceLevel8Choice() { return new ServiceLevel8Choice(); } /** * Create an instance of {@link StructuredRegulatoryReporting3 } * */ public StructuredRegulatoryReporting3 createStructuredRegulatoryReporting3() { return new StructuredRegulatoryReporting3(); } /** * Create an instance of {@link StructuredRemittanceInformation7 } * */ public StructuredRemittanceInformation7 createStructuredRemittanceInformation7() { return new StructuredRemittanceInformation7(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "http://www.six-interbank-clearing.com/de/pain.001.001.03.ch.02.xsd", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ObjectFactory.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isLenient() { return this.lenient; } public void setLenient(boolean lenient) { this.lenient = lenient; } public boolean isIgnoreUnknownKeys() { return this.ignoreUnknownKeys; } public void setIgnoreUnknownKeys(boolean ignoreUnknownKeys) { this.ignoreUnknownKeys = ignoreUnknownKeys; } public boolean isEncodeDefaults() { return this.encodeDefaults; } public void setEncodeDefaults(boolean encodeDefaults) { this.encodeDefaults = encodeDefaults; } public boolean isExplicitNulls() { return this.explicitNulls; } public void setExplicitNulls(boolean explicitNulls) { this.explicitNulls = explicitNulls; } public boolean isCoerceInputValues() { return this.coerceInputValues; } public void setCoerceInputValues(boolean coerceInputValues) { this.coerceInputValues = coerceInputValues; } public boolean isAllowStructuredMapKeys() { return this.allowStructuredMapKeys; } public void setAllowStructuredMapKeys(boolean allowStructuredMapKeys) { this.allowStructuredMapKeys = allowStructuredMapKeys; } public boolean isAllowSpecialFloatingPointValues() { return this.allowSpecialFloatingPointValues; } public void setAllowSpecialFloatingPointValues(boolean allowSpecialFloatingPointValues) { this.allowSpecialFloatingPointValues = allowSpecialFloatingPointValues; } public String getClassDiscriminator() { return this.classDiscriminator; } public void setClassDiscriminator(String classDiscriminator) { this.classDiscriminator = classDiscriminator; } public ClassDiscriminatorMode getClassDiscriminatorMode() { return this.classDiscriminatorMode; } public void setClassDiscriminatorMode(ClassDiscriminatorMode classDiscriminatorMode) { this.classDiscriminatorMode = classDiscriminatorMode; } public boolean isDecodeEnumsCaseInsensitive() { return this.decodeEnumsCaseInsensitive; } public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) {
this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive; } public boolean isUseAlternativeNames() { return this.useAlternativeNames; } public void setUseAlternativeNames(boolean useAlternativeNames) { this.useAlternativeNames = useAlternativeNames; } public boolean isAllowTrailingComma() { return this.allowTrailingComma; } public void setAllowTrailingComma(boolean allowTrailingComma) { this.allowTrailingComma = allowTrailingComma; } public boolean isAllowComments() { return this.allowComments; } public void setAllowComments(boolean allowComments) { this.allowComments = allowComments; } /** * Enum representing strategies for JSON property naming. The values correspond to * {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot * be directly referenced. */ public enum JsonNamingStrategy { /** * Snake case strategy. */ SNAKE_CASE, /** * Kebab case strategy. */ KEBAB_CASE } }
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
2
请完成以下Java代码
public PurchaseRow getById(final DocumentId rowId) throws EntityNotFoundException { return rows.getById(rowId); } public PurchaseRow getById(final PurchaseRowId rowId) throws EntityNotFoundException { return rows.getById(rowId); } @Override public LookupValuesPage getFilterParameterDropdown(final String filterId, final String filterParameterName, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public LookupValuesPage getFilterParameterTypeahead(final String filterId, final String filterParameterName, final String query, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public DocumentFilterList getStickyFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentFilterList getFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { throw new UnsupportedOperationException(); } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamTopLevelRowsByIds(rowIds); } public List<PurchaseRow> getRows() { return rows.getAll(); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { }
@Override public void patchViewRow( @NonNull final RowEditingContext ctx, @NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests) { final PurchaseRowId idOfChangedRow = PurchaseRowId.fromDocumentId(ctx.getRowId()); final PurchaseRowChangeRequest rowChangeRequest = PurchaseRowChangeRequest.of(fieldChangeRequests); patchViewRow(idOfChangedRow, rowChangeRequest); } public void patchViewRow( @NonNull final PurchaseRowId idOfChangedRow, @NonNull final PurchaseRowChangeRequest rowChangeRequest) { rows.patchRow(idOfChangedRow, rowChangeRequest); // notify the frontend final DocumentId groupRowDocumentId = idOfChangedRow.toGroupRowId().toDocumentId(); ViewChangesCollector .getCurrentOrAutoflush() .collectRowChanged(this, groupRowDocumentId); } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseView.java
1
请完成以下Java代码
public void addMouseListener (MouseListener ml) { super.addMouseListener(ml); final JButton arrowButton = getArrowButton(); if (arrowButton != null && !Trace.getCallerClass(1).startsWith("javax")) { arrowButton.addMouseListener(ml); } } /** * Remove Mouse Listener. * @param ml */ @Override public void removeMouseListener (MouseListener ml) { super.removeMouseListener(ml); final JButton arrowButton = getArrowButton(); if (arrowButton != null) { arrowButton.removeMouseListener(ml); } } // removeMouseListener /** * Set Action Command * @param actionCommand command */ @Override public void setActionCommand (String actionCommand) { super.setActionCommand (actionCommand); if (getName() == null && actionCommand != null && actionCommand.length() > 0) setName(actionCommand); } // setActionCommand public boolean isSelectionNone() { final Object selectedItem = getSelectedItem(); if (selectedItem == null) {
return true; } else { return Check.isEmpty(selectedItem.toString(), true); } } @Override public E getSelectedItem() { final Object selectedItemObj = super.getSelectedItem(); @SuppressWarnings("unchecked") final E selectedItem = (E)selectedItemObj; return selectedItem; } /** * Enables auto completion (while user writes) on this combobox. * * @return combobox's auto-completion instance for further configurations */ public final ComboBoxAutoCompletion<E> enableAutoCompletion() { return ComboBoxAutoCompletion.enable(this); } /** * Disable autocompletion on this combobox. * * If the autocompletion was not enabled, this method does nothing. */ public final void disableAutoCompletion() { ComboBoxAutoCompletion.disable(this); } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return JComboBoxCopyPasteSupportEditor.ofComponent(this); } } // CComboBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CComboBox.java
1
请完成以下Java代码
public void apply(Object model) { // nothing } /** * @return false */ @Override public boolean isCreateNewRecord() { return false; } @Override public void setSource(Object model) {
// nothing } /** * @return always false */ @Override public boolean isValid() { return false; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\NullGridTabRowBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderDeliveryAddress orderDeliveryAddress = (OrderDeliveryAddress) o; return Objects.equals(this.gender, orderDeliveryAddress.gender) && Objects.equals(this.title, orderDeliveryAddress.title) && Objects.equals(this.name, orderDeliveryAddress.name) && Objects.equals(this.address, orderDeliveryAddress.address) && Objects.equals(this.additionalAddress, orderDeliveryAddress.additionalAddress) && Objects.equals(this.additionalAddress2, orderDeliveryAddress.additionalAddress2) && Objects.equals(this.postalCode, orderDeliveryAddress.postalCode) && Objects.equals(this.city, orderDeliveryAddress.city); } @Override public int hashCode() { return Objects.hash(gender, title, name, address, additionalAddress, additionalAddress2, postalCode, city); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderDeliveryAddress {\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" additionalAddress: ").append(toIndentedString(additionalAddress)).append("\n"); sb.append(" additionalAddress2: ").append(toIndentedString(additionalAddress2)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderDeliveryAddress.java
2
请完成以下Java代码
protected String doIt() throws Exception { final Iterator<I_M_ShipmentSchedule> scheds = getSelectedShipmentSchedules(); int counter = 0; for (final I_M_ShipmentSchedule shipmentSchedule : IteratorUtils.asIterable(scheds)) { if (!shipmentSchedule.isProcessed()) { addLog(msgBL.getMsg(getCtx(), MSG_SHIPMENT_SCHEDULES_SKIP_OPEN, new Object[] { shipmentSchedule.getM_ShipmentSchedule_ID() })); continue; } openInTrx(shipmentSchedule); counter++; } return "@Processed@: " + counter; } private Iterator<I_M_ShipmentSchedule> getSelectedShipmentSchedules()
{ final IQueryFilter<I_M_ShipmentSchedule> selectedSchedsFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); return queryBL.createQueryBuilder(I_M_ShipmentSchedule.class) .addOnlyActiveRecordsFilter() .filter(selectedSchedsFilter) .create() .iterate(I_M_ShipmentSchedule.class); } private void openInTrx(final I_M_ShipmentSchedule shipmentSchedule) { Services.get(ITrxManager.class) .runInNewTrx((TrxRunnable)localTrxName -> { InterfaceWrapperHelper.setThreadInheritedTrxName(shipmentSchedule); shipmentScheduleBL.openShipmentSchedule(shipmentSchedule); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_OpenProcessed.java
1
请完成以下Java代码
public WFActivityType getHandledActivityType() { return HANDLED_ACTIVITY_TYPE; } @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(msgBL.getMsg(jsonOpts.getAdLanguage(), ARE_YOU_SURE)) .build()); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completeDistributionWFActivity) {
final HUConsolidationJob job = getHUConsolidationJob(wfProcess); return computeActivityState(job); } public static WFActivityStatus computeActivityState(final HUConsolidationJob job) { // TODO return WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.assertActivityType(HANDLED_ACTIVITY_TYPE); return HUConsolidationApplication.mapJob(request.getWfProcess(), jobService::complete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\workflows_api\activity_handlers\CompleteWFActivityHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class CityServiceImpl implements CityService { private final CityRepository cityRepository; @Autowired public CityServiceImpl(CityRepository cityRepository) { this.cityRepository = cityRepository; } @Override public Flux<City> findAll() { return cityRepository.findAll(); } @Override public Mono<City> insertByCity(City city) { return cityRepository.save(city); }
@Override public Mono<City> update(City city) { return cityRepository.save(city); } @Override public Mono<Void> delete(Long id) { return cityRepository.deleteById(id); } @Override public Mono<City> findById(Long id) { return cityRepository.findById(id); } }
repos\springboot-learning-example-master\springboot-webflux-10-book-manage-sys\src\main\java\demo\springboot\service\impl\CityServiceImpl.java
2
请完成以下Java代码
public class ConsulSendingHandler extends AbstractMessageHandler { private final ConsulClient consul; private final String eventName; public ConsulSendingHandler(ConsulClient consul, String eventName) { this.consul = consul; this.eventName = eventName; } @Override protected void handleMessageInternal(Message<?> message) { if (this.logger.isTraceEnabled()) { this.logger.trace("Publishing message" + message); }
// 转换成 String Object payload = message.getPayload(); if (payload instanceof byte[]) { payload = new String((byte[]) payload); } // TODO: support headers // TODO: support consul event filters: NodeFilter, ServiceFilter, TagFilter Response<Event> event = this.consul.eventFire(this.eventName, (String) payload, new EventParams(), QueryParams.DEFAULT); // TODO: return event? } }
repos\SpringBoot-Labs-master\labx-29-spring-cloud-consul-bus\labx-29-sc-bus-consul-demo-listener-actuator\src\main\java\org\springframework\cloud\consul\binder\ConsulSendingHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Builder signingAlgorithms(Consumer<List<String>> signingMethodAlgorithmsConsumer) { return (Builder) super.signingAlgorithms(signingMethodAlgorithmsConsumer); } /** * {@inheritDoc} */ @Override public Builder verificationX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.verificationX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder encryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.encryptionX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder singleSignOnServiceLocation(String singleSignOnServiceLocation) { return (Builder) super.singleSignOnServiceLocation(singleSignOnServiceLocation); } /** * {@inheritDoc} */ @Override public Builder singleSignOnServiceBinding(Saml2MessageBinding singleSignOnServiceBinding) { return (Builder) super.singleSignOnServiceBinding(singleSignOnServiceBinding); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) { return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation);
} /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) { return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) { return (Builder) super.singleLogoutServiceBinding(singleLogoutServiceBinding); } /** * Build an * {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails} * @return */ @Override public OpenSamlAssertingPartyDetails build() { return new OpenSamlAssertingPartyDetails(super.build(), this.descriptor); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\OpenSamlAssertingPartyDetails.java
2
请完成以下Java代码
public void setDunningDate (Timestamp DunningDate) { set_Value (COLUMNNAME_DunningDate, DunningDate); } /** Get Dunning Date. @return Date of Dunning */ public Timestamp getDunningDate () { return (Timestamp)get_Value(COLUMNNAME_DunningDate); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getDunningDate())); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Send. @param SendIt Send */ public void setSendIt (String SendIt) { set_Value (COLUMNNAME_SendIt, SendIt); } /** Get Send. @return Send */ public String getSendIt () { return (String)get_Value(COLUMNNAME_SendIt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRun.java
1
请完成以下Java代码
protected void prepare() { if (I_AD_MigrationStep.Table_Name.equals(getTableName()) && getRecord_ID() > 0) { migrationStep = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_AD_MigrationStep.class, null); } } public Action getAction() { return action; } public void setAction(Action action) { this.action = action; } public I_AD_MigrationStep getMigrationStep() { return migrationStep; } @Override protected String doIt() throws Exception { if (migrationStep == null || migrationStep.getAD_MigrationStep_ID() <= 0) { throw new AdempiereException("@NotFound@ AD_MigrationStep_ID@"); } final IMigrationExecutorProvider executorProvider = Services.get(IMigrationExecutorProvider.class); final IMigrationExecutorContext migrationCtx = executorProvider.createInitialContext(getCtx());
final IMigrationExecutor executor = executorProvider.newMigrationExecutor(migrationCtx, migrationStep.getAD_Migration_ID()); executor.setMigrationSteps(Arrays.asList(migrationStep)); if (action == null) { action = getAction(migrationStep); } executor.execute(action); return "Executed: " + action; } protected Action getAction(I_AD_MigrationStep step) { if (X_AD_MigrationStep.STATUSCODE_Applied.equals(migrationStep.getStatusCode())) { return IMigrationExecutor.Action.Rollback; } else { return IMigrationExecutor.Action.Apply; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationStepApply.java
1
请完成以下Java代码
class ProcessExitException extends RuntimeException { private final int exitCode; private final String[] command; private final String stdOut; private final String stdErr; ProcessExitException(int exitCode, String[] command, String stdOut, String stdErr) { this(exitCode, command, stdOut, stdErr, null); } ProcessExitException(int exitCode, String[] command, String stdOut, String stdErr, @Nullable Throwable cause) { super(buildMessage(exitCode, command, stdOut, stdErr), cause); this.exitCode = exitCode; this.command = command; this.stdOut = stdOut; this.stdErr = stdErr; } private static String buildMessage(int exitCode, String[] command, String stdOut, String strErr) { return "'%s' failed with exit code %d.\n\nStdout:\n%s\n\nStderr:\n%s".formatted(String.join(" ", command), exitCode, stdOut, strErr); } int getExitCode() {
return this.exitCode; } String[] getCommand() { return this.command; } String getStdOut() { return this.stdOut; } String getStdErr() { return this.stdErr; } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\ProcessExitException.java
1
请完成以下Java代码
public String getMsg(final Properties ctx, @NonNull final AdMessageKey adMessage, final Object[] params) { if (params == null || params.length == 0) { return adMessage.toAD_Message(); } return adMessage + "_" + Arrays.toString(params); } @Override public String getMsg(@NonNull final AdMessageKey adMessage, final List<Object> params) { if (params == null || params.isEmpty()) { return adMessage.toAD_Message(); } return adMessage.toAD_Message() + "_" + params; } @Override public Map<String, String> getMsgMap(final String adLanguage, final String prefix, final boolean removePrefix) { return ImmutableMap.of(); } @Override public String parseTranslation(final Properties ctx, final String message) { return message; } @Override public String parseTranslation(final String adLanguage, final String message) { return message; } @Override public String translate(final Properties ctx, final String text) { return text; } @Override public String translate(final String adLanguage, final String text) { return text; } @Override public String translate(final Properties ctx, final String text, final boolean isSOTrx) { return text; } @Override public ITranslatableString translatable(final String text) { return TranslatableStrings.constant(text); }
@Override public ITranslatableString getTranslatableMsgText(@NonNull final AdMessageKey adMessage, final Object... msgParameters) { if (msgParameters == null || msgParameters.length == 0) { return TranslatableStrings.constant(adMessage.toAD_Message()); } else { return TranslatableStrings.constant(adMessage.toAD_Message() + " - " + Joiner.on(", ").useForNull("-").join(msgParameters)); } } @Override public void cacheReset() { // nothing } @Override public String getBaseLanguageMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { return TranslatableStrings.adMessage(adMessage, msgParameters) .translate(Language.getBaseAD_Language()); } @Override public Optional<AdMessageId> getIdByAdMessage(@NonNull final AdMessageKey value) { return Optional.empty(); } @Override public boolean isMessageExists(final AdMessageKey adMessage) { return false; } @Override public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId) { return Optional.empty(); } @Nullable @Override public String getErrorCode(final @NonNull AdMessageKey messageKey) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\PlainMsgBL.java
1
请完成以下Java代码
public class WEBUI_M_HU_MoveTUsToDirectWarehouse extends HUEditorProcessTemplate implements IProcessPrecondition { private final DocumentCollection documentsCollection = SpringContextHolder.instance.getBean(DocumentCollection.class); @Param(parameterName = "QtyTU") private int p_QtyTU; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (!selectedRowIds.isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final DocumentId rowId = selectedRowIds.getSingleDocumentId(); final HUEditorRow huRow = getView().getById(rowId); if (huRow.isLU()) { if (!huRow.hasIncludedTUs()) { return ProcessPreconditionsResolution.rejectWithInternalReason("no TUs"); } } else if (huRow.isTU()) { // OK } else { return ProcessPreconditionsResolution.rejectWithInternalReason("not a LU or TU"); } if (!huRow.isHUStatusActive()) { return ProcessPreconditionsResolution.rejectWithInternalReason("HUStatus is not Active"); } return ProcessPreconditionsResolution.accept(); }
@Override // @RunOutOfTrx // run in transaction! protected String doIt() { if (p_QtyTU <= 0) { throw new FillMandatoryException("QtyTU"); } final I_M_HU topLevelHU = getRecord(I_M_HU.class); final HUsToNewTUsRequest request = HUsToNewTUsRequest.forSourceHuAndQty(topLevelHU, p_QtyTU); final LUTUResult.TUsList tus = HUTransformService.newInstance().husToNewTUs(request); if (tus.getQtyTU().toInt() != p_QtyTU) { throw new AdempiereException(WEBUI_HU_Constants.MSG_NotEnoughTUsFound, p_QtyTU, tus.getQtyTU()); } HUMoveToDirectWarehouseService.newInstance() .setDocumentsCollection(documentsCollection) .setHUView(getView()) .setMovementDate(SystemTime.asInstant()) // now // .setDescription(description) // none .setFailOnFirstError(true) .setLoggable(this) .move(tus.toHURecords().iterator()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveTUsToDirectWarehouse.java
1
请完成以下Java代码
public static boolean containsAny(Object collection, Object value) { return anyOf(collection, value); } /** * one of the values of value must not be in collection * * @return {@code true} if a least one element of value is not within the collection, * {@code false} if all elements of value are within the collection */ public static boolean notAllOf(Object collection, Object value) { if (collection == null) { throw new IllegalArgumentException("collection cannot be null"); } if (value == null) { throw new IllegalArgumentException("value cannot be null"); } // collection to check against Collection targetCollection = getTargetCollection(collection, value); // elements to check if (DMNParseUtil.isParseableCollection(value)) { Collection valueCollection = DMNParseUtil.parseCollection(value, targetCollection); return valueCollection == null || !targetCollection.containsAll(valueCollection); } else if (DMNParseUtil.isJavaCollection(value)) { return !targetCollection.containsAll((Collection) value); } else if (DMNParseUtil.isArrayNode(value)) { Collection valueCollection = DMNParseUtil.getCollectionFromArrayNode(JsonUtil.asFlowableArrayNode(value)); return valueCollection == null || !targetCollection.containsAll(valueCollection); } else { Object formattedValue = DMNParseUtil.getFormattedValue(value, targetCollection); return !targetCollection.contains(formattedValue); } }
/** * @deprecated use {@link #notAllOf(Object, Object)} instead */ @Deprecated public static boolean notContainsAny(Object collection, Object value) { return notAllOf(collection, value); } protected static Collection getTargetCollection(Object collection, Object value) { Collection targetCollection; if (!DMNParseUtil.isCollection(collection)) { if (DMNParseUtil.isParseableCollection(collection)) { targetCollection = DMNParseUtil.parseCollection(collection, value); } else { targetCollection = Arrays.asList(collection); } } else if (DMNParseUtil.isArrayNode(collection)) { targetCollection = DMNParseUtil.getCollectionFromArrayNode(JsonUtil.asFlowableArrayNode(collection)); } else { targetCollection = (Collection) collection; } return targetCollection; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\util\CollectionUtil.java
1
请完成以下Java代码
/* package */ class DLMConnectionUtils { private static final String FUNCTION_DLM_LEVEL = "dlm.get_dlm_level()"; private static final String FUNCTION_DLM_COALESCE_LEVEL = "dlm.get_dlm_coalesce_level()"; private static final String SETTING_DLM_LEVEL = "metasfresh.DLM_Level"; private static final String SETTING_DLM_COALESCE_LEVEL = "metasfresh.DLM_Coalesce_Level"; private DLMConnectionUtils() { } /** * Sets <code>search_path</code> to <code>"$user", dlm, public</code> to give views in the <code>dlm</code> schema precedence over equally named tables in the <code>public</code> schema. * * @param c * @throws SQLException */ public static void setSearchPathForDLM(final Connection c) throws SQLException { changeSetting(c, "search_path", "\"$user\", dlm, public"); } public static void changeDLMCoalesceLevel(final Connection c, final int dlmCoalesceLevel) throws SQLException { changeSetting(c, SETTING_DLM_COALESCE_LEVEL, dlmCoalesceLevel); } public static void changeDLMLevel(final Connection c, final int dlmLevel) throws SQLException { changeSetting(c, SETTING_DLM_LEVEL, dlmLevel); } public static int retrieveCurrentDLMLevel(final Connection c) throws SQLException { return restrieveSetting(c, FUNCTION_DLM_LEVEL); } public static int retrieveCurrentDLMCoalesceLevel(final Connection c) throws SQLException
{ return restrieveSetting(c, FUNCTION_DLM_COALESCE_LEVEL); } private static int restrieveSetting(final Connection c, final String functionName) throws SQLException { final ResultSet rs = c.prepareStatement("SELECT " + functionName).executeQuery(); final Integer dlmLevel = rs.next() ? rs.getInt(1) : null; Check.errorIf(dlmLevel == null, "Unable to retrieve the current setting for {} from the DB", SETTING_DLM_COALESCE_LEVEL); return dlmLevel; } private static void changeSetting(final Connection c, final String setting, final int value) throws SQLException { final String valueStr = Integer.toString(value); changeSetting(c, setting, valueStr); } private static void changeSetting(final Connection c, final String setting, final String valueStr) throws SQLException { final PreparedStatement ps = c.prepareStatement("select set_config('" + setting + "'::text, ?::text, ?::boolean)"); ps.setString(1, valueStr); ps.setBoolean(2, false); ps.execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\DLMConnectionUtils.java
1
请完成以下Java代码
public static BufferedImage createQRwithText(String data, String topText, String bottomText) throws WriterException, IOException { QRCodeWriter barcodeWriter = new QRCodeWriter(); BitMatrix matrix = barcodeWriter.encode(data, BarcodeFormat.QR_CODE, 200, 200); return modifiedQRCode(matrix, topText, bottomText); } public static BufferedImage modifiedQRCode(BitMatrix matrix, String topText, String bottomText) throws IOException { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); BufferedImage image = new BufferedImage(matrixWidth, matrixHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, matrixWidth, matrixHeight); graphics.setColor(Color.BLACK); for (int i = 0; i < matrixWidth; i++) { for (int j = 0; j < matrixHeight; j++) { if (matrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } FontMetrics fontMetrics = graphics.getFontMetrics(); int topTextWidth = fontMetrics.stringWidth(topText);
int bottomTextWidth = fontMetrics.stringWidth(bottomText); int finalWidth = Math.max(matrixWidth, Math.max(topTextWidth, bottomTextWidth)) + 1; int finalHeight = matrixHeight + fontMetrics.getHeight() + fontMetrics.getAscent() + 1; BufferedImage finalImage = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_RGB); Graphics2D finalGraphics = finalImage.createGraphics(); finalGraphics.setColor(Color.WHITE); finalGraphics.fillRect(0, 0, finalWidth, finalHeight); finalGraphics.setColor(Color.BLACK); finalGraphics.drawImage(image, (finalWidth - matrixWidth) / 2, fontMetrics.getAscent() + 2, null); finalGraphics.drawString(topText, (finalWidth - topTextWidth) / 2, fontMetrics.getAscent() + 2); finalGraphics.drawString(bottomText, (finalWidth - bottomTextWidth) / 2, finalHeight - fontMetrics.getDescent() - 2); return finalImage; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\barcodes\generators\ZxingBarcodeGeneratorWithText.java
1
请完成以下Java代码
public List<EngineDeployer> getDeployers() { return deployers; } public void setDeployers(List<EngineDeployer> deployers) { this.deployers = deployers; } public DeploymentCache<ProcessDefinitionCacheEntry> getProcessDefinitionCache() { return processDefinitionCache; } public void setProcessDefinitionCache(DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache) { this.processDefinitionCache = processDefinitionCache; } public DeploymentCache<ProcessDefinitionInfoCacheObject> getProcessDefinitionInfoCache() { return processDefinitionInfoCache; } public void setProcessDefinitionInfoCache(DeploymentCache<ProcessDefinitionInfoCacheObject> processDefinitionInfoCache) { this.processDefinitionInfoCache = processDefinitionInfoCache; } public DeploymentCache<Object> getKnowledgeBaseCache() { return knowledgeBaseCache; } public void setKnowledgeBaseCache(DeploymentCache<Object> knowledgeBaseCache) { this.knowledgeBaseCache = knowledgeBaseCache; } public DeploymentCache<Object> getAppResourceCache() { return appResourceCache; } public void setAppResourceCache(DeploymentCache<Object> appResourceCache) {
this.appResourceCache = appResourceCache; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; } public ProcessDefinitionEntityManager getProcessDefinitionEntityManager() { return processDefinitionEntityManager; } public void setProcessDefinitionEntityManager(ProcessDefinitionEntityManager processDefinitionEntityManager) { this.processDefinitionEntityManager = processDefinitionEntityManager; } public DeploymentEntityManager getDeploymentEntityManager() { return deploymentEntityManager; } public void setDeploymentEntityManager(DeploymentEntityManager deploymentEntityManager) { this.deploymentEntityManager = deploymentEntityManager; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\deploy\DeploymentManager.java
1
请完成以下Java代码
public void setSubjectMatter(final Boolean subjectMatter) { this.subjectMatter = subjectMatter; this.subjectMatterSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setMetasfreshBPartnerId(final JsonMetasfreshId metasfreshBPartnerId) { this.metasfreshBPartnerId = metasfreshBPartnerId; this.metasfreshBPartnerIdSet = true; } public void setBirthday(final LocalDate birthday) { this.birthday = birthday; this.birthdaySet = true; }
public void setInvoiceEmailEnabled(@Nullable final Boolean invoiceEmailEnabled) { this.invoiceEmailEnabled = invoiceEmailEnabled; invoiceEmailEnabledSet = true; } public void setTitle(final String title) { this.title = title; this.titleSet = true; } public void setPhone2(final String phone2) { this.phone2 = phone2; this.phone2Set = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestContact.java
1
请在Spring Boot框架中完成以下Java代码
public final class NullSecurityContextRepository implements SecurityContextRepository { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); @Override public boolean containsContext(HttpServletRequest request) { return false; } /** * @deprecated please see {@link SecurityContextRepository#loadContext} */ @Override @Deprecated public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { return this.securityContextHolderStrategy.createEmptyContext(); }
@Override public void saveContext(SecurityContext context, HttpServletRequest request, @Nullable HttpServletResponse response) { } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\NullSecurityContextRepository.java
2
请在Spring Boot框架中完成以下Java代码
private CustomerId getCustomerId(TenantId tenantId, String customerName) { if (StringUtils.isEmpty(customerName)) { return null; } Optional<Customer> customerOpt = customerService.findCustomerByTenantIdAndTitle(tenantId, customerName); if (customerOpt.isPresent()) { return customerOpt.get().getId(); } else { Customer customer = new Customer(); customer.setTenantId(tenantId); customer.setTitle(customerName); return customerService.saveCustomer(customer).getId(); } } private Optional<DashboardId> getDashboardId(TenantId tenantId, String dashboardName) { return Optional.ofNullable(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, dashboardName)).map(IdBased::getId); } private Optional<DashboardId> getDashboardId(TenantId tenantId, CustomerId customerId, String dashboardName) { PageData<DashboardInfo> dashboardsPage;
PageLink pageLink = null; do { pageLink = pageLink == null ? new PageLink(DASHBOARDS_REQUEST_LIMIT) : pageLink.nextPageLink(); dashboardsPage = dashboardService.findDashboardsByTenantIdAndCustomerId(tenantId, customerId, pageLink); Optional<DashboardInfo> dashboardInfoOpt = dashboardsPage.getData().stream() .filter(dashboardInfo -> dashboardName.equals(dashboardInfo.getName())) .findAny(); if (dashboardInfoOpt.isPresent()) { return dashboardInfoOpt.map(DashboardInfo::getId); } } while (dashboardsPage.hasNext()); return Optional.empty(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\AbstractOAuth2ClientMapper.java
2
请在Spring Boot框架中完成以下Java代码
public void setPriceValidFrom(XMLGregorianCalendar value) { this.priceValidFrom = value; } /** * Gets the value of the priceValidTo property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getPriceValidTo() { return priceValidTo; } /** * Sets the value of the priceValidTo property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setPriceValidTo(XMLGregorianCalendar value) { this.priceValidTo = value; } /** * Gets the value of the parties property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parties property.
* * <p> * For example, to add a new item, do as follows: * <pre> * getParties().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BusinessEntityType } * * */ public List<BusinessEntityType> getParties() { if (parties == null) { parties = new ArrayList<BusinessEntityType>(); } return this.parties; } }
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\PriceSpecificationType.java
2
请在Spring Boot框架中完成以下Java代码
public RelyingPartyRegistration getRelyingPartyRegistration() { return this.relyingPartyRegistration; } /** * Returns inflated and decoded XML representation of the SAML 2 Response * @return inflated and decoded XML representation of the SAML 2 Response */ public String getSaml2Response() { return this.saml2Response; } /** * @return false */ @Override public boolean isAuthenticated() { return false; } /** * The state of this object cannot be changed. Will always throw an exception
* @param authenticated ignored */ @Override public void setAuthenticated(boolean authenticated) { throw new IllegalArgumentException(); } /** * Returns the authentication request sent to the assertion party or {@code null} if * no authentication request is present * @return the authentication request sent to the assertion party * @since 5.6 */ public AbstractSaml2AuthenticationRequest getAuthenticationRequest() { return this.authenticationRequest; } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2AuthenticationToken.java
2
请完成以下Java代码
public static EngineInfo retry(String resourceUrl) { LOGGER.debug("retying initializing of resource {}", resourceUrl); try { return initCmmnEngineFromResource(new URL(resourceUrl)); } catch (MalformedURLException e) { throw new FlowableException("invalid url: " + resourceUrl, e); } } /** * provides access to cmmn engine to application clients in a managed server environment. */ public static Map<String, CmmnEngine> getCmmnEngines() { return cmmnEngines; } /** * closes all cmmn engines. This method should be called when the server shuts down. */ public static synchronized void destroy() { if (isInitialized()) { Map<String, CmmnEngine> engines = new HashMap<>(cmmnEngines); cmmnEngines = new HashMap<>(); for (String cmmnEngineName : engines.keySet()) { CmmnEngine cmmnEngine = engines.get(cmmnEngineName); try { cmmnEngine.close(); } catch (Exception e) { LOGGER.error("exception while closing {}", (cmmnEngineName == null ? "the default cmmn engine" : "cmmn engine " + cmmnEngineName), e); } }
cmmnEngineInfosByName.clear(); cmmnEngineInfosByResourceUrl.clear(); cmmnEngineInfos.clear(); setInitialized(false); } } public static boolean isInitialized() { return isInitialized; } public static void setInitialized(boolean isInitialized) { CmmnEngines.isInitialized = isInitialized; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngines.java
1
请完成以下Java代码
public final static String getIpAddress(HttpServletRequest request) throws IOException { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); // LOG.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip= {}" ,ip); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); // LOG.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip= {}" , ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); // LOG.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip= {}" , ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); // LOG.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip= {}" , ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); // LOG.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip= {}" , ip);
} if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); // LOG.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip= {}" , ip); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; } }
repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\utils\NetworkUtil.java
1
请完成以下Java代码
public MTreeNode getRoot() { return (MTreeNode)super.getRoot(); } public boolean saveChildren(MTreeNode parent) { return saveChildren(parent, parent.getChildrenList()); } public boolean saveChildren(MTreeNode parent, List<MTreeNode> children) { try { m_MTree.updateNodeChildren(parent, children); } catch (Exception e) {
ADialog.error(0, null, "Error", e.getLocalizedMessage()); log.error(e.getLocalizedMessage(), e); return false; } return true; } // metas: begin public void filterIds(final List<Integer> ids) { Check.assumeNotNull(ids, "Param 'ids' is not null"); Services.get(IADTreeBL.class).filterIds(getRoot(), ids); reload(); } // metas: end }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\AdempiereTreeModel.java
1
请完成以下Java代码
public class nobr extends MultiPartElement implements Printable { /** * */ private static final long serialVersionUID = -3116149804660625675L; /** Private initialization routine. */ { setElementType("nobr"); setCase(LOWERCASE); setAttributeQuote(true); } /** Basic constructor. Use the set* methods to set the values of the attributes. */ public nobr() { } /** Use the set* methods to set the values of the attributes. @param element set the value of &lt;nobr&gt;value&lt;/nobr&gt; */ public nobr(Element element) { addElement(element); } /** Use the set* methods to set the values of the attributes. @param value set the value of &lt;nobr&gt;value&lt;/nobr&gt; */ public nobr(String value) { addElement(value); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public nobr addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element.
*/ public nobr addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public nobr addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public nobr addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public nobr removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\nobr.java
1
请完成以下Java代码
public static class InstanceBuilder<T> extends AbstractBuilder<T, InstanceBuilder<T>> { private final T instance; public InstanceBuilder(ConfigurationService service, T instance) { super(service); this.instance = instance; } @Override protected InstanceBuilder<T> getThis() { return this; } @Override protected void validate() { Objects.requireNonNull(this.instance, "instance may not be null"); } @Override protected T doBind() { T toBind = getTargetObject(this.instance); Bindable<T> bindable = Bindable.ofInstance(toBind); return bindOrCreate(bindable, this.normalizedProperties, this.name, this.service.validator.get(), this.service.conversionService.get()); } } public static abstract class AbstractBuilder<T, B extends AbstractBuilder<T, B>> { protected final ConfigurationService service; protected BiFunction<T, Map<String, Object>, ApplicationEvent> eventFunction; protected String name; protected Map<String, Object> normalizedProperties; protected Map<String, String> properties; public AbstractBuilder(ConfigurationService service) { this.service = service; } protected abstract B getThis(); public B name(String name) { this.name = name; return getThis(); }
public B eventFunction(BiFunction<T, Map<String, Object>, ApplicationEvent> eventFunction) { this.eventFunction = eventFunction; return getThis(); } public B normalizedProperties(Map<String, Object> normalizedProperties) { this.normalizedProperties = normalizedProperties; return getThis(); } public B properties(Map<String, String> properties) { this.properties = properties; return getThis(); } protected abstract void validate(); protected Map<String, Object> normalizeProperties() { Map<String, Object> normalizedProperties = new HashMap<>(); this.properties.forEach(normalizedProperties::put); return normalizedProperties; } protected abstract T doBind(); public T bind() { validate(); Assert.hasText(this.name, "name may not be empty"); Assert.isTrue(this.properties != null || this.normalizedProperties != null, "properties and normalizedProperties both may not be null"); if (this.normalizedProperties == null) { this.normalizedProperties = normalizeProperties(); } T bound = doBind(); if (this.eventFunction != null && this.service.publisher != null) { ApplicationEvent applicationEvent = this.eventFunction.apply(bound, this.normalizedProperties); this.service.publisher.publishEvent(applicationEvent); } return bound; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ConfigurationService.java
1
请完成以下Java代码
public class MybatisRedisCache implements Cache { private static final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class); // 读写锁 private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); private RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean("redisTemplate"); private String id; public MybatisRedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } logger.info("Redis Cache id " + id); this.id = id; } @Override public String getId() { return this.id; } @Override public void putObject(Object key, Object value) { if (value != null) { // 向Redis中添加数据,有效时间是2天 redisTemplate.opsForValue().set(key.toString(), value, 2, TimeUnit.DAYS); } } @Override public Object getObject(Object key) { try { if (key != null) { Object obj = redisTemplate.opsForValue().get(key.toString()); return obj; } } catch (Exception e) { logger.error("redis "); } return null; } @Override public Object removeObject(Object key) { try { if (key != null) { redisTemplate.delete(key.toString()); } } catch (Exception e) {
} return null; } @Override public void clear() { logger.debug("清空缓存"); try { Set<String> keys = redisTemplate.keys("*:" + this.id + "*"); if (!CollectionUtils.isEmpty(keys)) { redisTemplate.delete(keys); } } catch (Exception e) { } } @Override public int getSize() { Long size = (Long) redisTemplate.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.dbSize(); } }); return size.intValue(); } @Override public ReadWriteLock getReadWriteLock() { return this.readWriteLock; } }
repos\spring-boot-student-master\spring-boot-student-mybatis-redis\src\main\java\com\xiaolyuh\redis\cache\MybatisRedisCache.java
1
请完成以下Java代码
public byte[] getReportDataByteArray() { return SpringResourceUtils.toByteArray(reportData); } public static ReportResultData ofFile(@NonNull final File file) { final String reportFilename = file.getName(); return ReportResultData.builder() .reportData(new FileSystemResource(file)) .reportFilename(reportFilename) .reportContentType(MimeType.getMimeType(reportFilename)) .build(); } public static ReportResultData ofFile(final @NotNull File file, @NotNull final String reportFilename) { return ReportResultData.builder() .reportData(new FileSystemResource(file)) .reportFilename(reportFilename) .reportContentType(MimeType.getMimeType(reportFilename)) .build(); } @JsonIgnore public boolean isEmpty() { try { return reportData.contentLength() <= 0; } catch (final IOException e) { return true; // reportdata couldn't be resolved, so we say it's empty } }
public File writeToTemporaryFile(@NonNull final String filenamePrefix) { final File file = createTemporaryFile(filenamePrefix); try { FileUtils.copyInputStreamToFile(reportData.getInputStream(), file); return file; } catch (final IOException ex) { throw new AdempiereException("Failed writing " + file.getAbsolutePath(), ex); } } @NonNull private File createTemporaryFile(@NonNull final String filenamePrefix) { try { final String ext = MimeType.getExtensionByType(reportContentType); final String suffix = Check.isNotBlank(ext) ? "." + ext : ""; return File.createTempFile(filenamePrefix, suffix); } catch (final IOException ex) { throw new AdempiereException("Failed creating temporary file with `" + filenamePrefix + "` prefix", ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ReportResultData.java
1
请完成以下Java代码
final class JarModeRunner { static final String DISABLE_SYSTEM_EXIT = JarModeRunner.class.getName() + ".DISABLE_SYSTEM_EXIT"; static final String SUPPRESSED_SYSTEM_EXIT_CODE = JarModeRunner.class.getName() + ".SUPPRESSED_SYSTEM_EXIT_CODE"; private JarModeRunner() { } static void main(String[] args) { String mode = System.getProperty("jarmode"); boolean disableSystemExit = Boolean.getBoolean(DISABLE_SYSTEM_EXIT); try { runJarMode(mode, args); if (disableSystemExit) { System.setProperty(SUPPRESSED_SYSTEM_EXIT_CODE, "0"); } } catch (Throwable ex) { printError(ex); if (disableSystemExit) { System.setProperty(SUPPRESSED_SYSTEM_EXIT_CODE, "1"); return; } System.exit(1);
} } private static void runJarMode(String mode, String[] args) { List<JarMode> candidates = SpringFactoriesLoader.loadFactories(JarMode.class, ClassUtils.getDefaultClassLoader()); for (JarMode candidate : candidates) { if (candidate.accepts(mode)) { candidate.run(mode, args); return; } } throw new JarModeErrorException("Unsupported jarmode '" + mode + "'"); } private static void printError(Throwable ex) { if (ex instanceof JarModeErrorException) { String message = ex.getMessage(); System.err.println("Error: " + message); System.err.println(); return; } ex.printStackTrace(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\JarModeRunner.java
1
请在Spring Boot框架中完成以下Java代码
public List<Customer> createCustomers(List<Customer> customers) { return customers.stream() .map(this::createCustomer) .filter(Optional::isPresent) .map(Optional::get) .collect(toList()); } public Optional<Customer> createCustomer(Customer customer) { LOGGER.info("Creating Customer : {}", customer); if (!customerRepoMap.containsKey(customer.getEmail()) && customer.getId() == 0) { Customer customerToCreate = new Customer(customerRepoMap.size() + 1, customer.getName(), customer.getEmail()); customerToCreate.setAddress(customer.getAddress()); customerRepoMap.put(customerToCreate.getEmail(), customerToCreate); LOGGER.info("Created Customer : {}", customerToCreate); return Optional.of(customerToCreate); } return Optional.empty(); } public Optional<Customer> updateCustomer(Customer customer) { LOGGER.info("Updating Customer : {}", customer); Customer customerToUpdate = customerRepoMap.get(customer.getEmail()); if (customerToUpdate != null && customerToUpdate.getId() == customer.getId()) { customerToUpdate.setName(customer.getName()); customerToUpdate.setAddress(customer.getAddress());
LOGGER.info("Updated Customer : {}", customerToUpdate); } return Optional.ofNullable(customerToUpdate); } public Optional<Customer> deleteCustomer(Customer customer) { LOGGER.info("Deleting Customer : {}", customer); Customer customerToDelete = customerRepoMap.get(customer.getEmail()); if (customerToDelete != null && customerToDelete.getId() == customer.getId()) { customerRepoMap.remove(customer.getEmail()); LOGGER.info("Deleted Customer : {}", customerToDelete); } return Optional.ofNullable(customerToDelete); } }
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\service\CustomerService.java
2
请完成以下Java代码
public Object getValue(ValueFields valueFields) { byte[] bytes = valueFields.getBytes(); if (valueFields.getTextValue() != null && bytes != null) { String entityClass = valueFields.getTextValue(); List<Object> result = new ArrayList<Object>(); String[] ids = deserializeIds(bytes); for (String id : ids) { result.add(mappings.getJPAEntity(entityClass, id)); } return result; } return null; } /** * @return a bytearray containing all ID's in the given string serialized as an array. */ protected byte[] serializeIds(List<String> ids) { try { String[] toStore = ids.toArray(new String[] {}); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(toStore); return baos.toByteArray();
} catch (IOException ioe) { throw new ActivitiException("Unexpected exception when serializing JPA id's", ioe); } } protected String[] deserializeIds(byte[] bytes) { try { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream in = new ObjectInputStream(bais); Object read = in.readObject(); if (!(read instanceof String[])) { throw new ActivitiIllegalArgumentException("Deserialized value is not an array of ID's: " + read); } return (String[]) read; } catch (IOException ioe) { throw new ActivitiException("Unexpected exception when deserializing JPA id's", ioe); } catch (ClassNotFoundException e) { throw new ActivitiException("Unexpected exception when deserializing JPA id's", e); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JPAEntityListVariableType.java
1
请完成以下Java代码
public String getId() { return id; } public Date getDuedate() { return dueDate; } public void setDuedate(Date dueDate) { this.dueDate = dueDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public int getRetries() { return retries; } public void setRetries(int retries) { this.retries = retries; } public int getMaxIterations() { return maxIterations; } public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; } public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode()); result = prime * result + ((endDate == null) ? 0 : endDate.hashCode()); result = prime * result + ((exceptionMessage == null) ? 0 : exceptionMessage.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + maxIterations; result = prime * result + ((repeat == null) ? 0 : repeat.hashCode()); result = prime * result + retries; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimerPayload other = (TimerPayload) obj; if (dueDate == null) { if (other.dueDate != null) return false; } else if (!dueDate.equals(other.dueDate)) return false; if (endDate == null) { if (other.endDate != null) return false; } else if (!endDate.equals(other.endDate)) return false; if (exceptionMessage == null) { if (other.exceptionMessage != null) return false; } else if (!exceptionMessage.equals(other.exceptionMessage)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (maxIterations != other.maxIterations) return false; if (repeat == null) { if (other.repeat != null) return false; } else if (!repeat.equals(other.repeat)) return false; if (retries != other.retries) return false; return true; } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\TimerPayload.java
1
请在Spring Boot框架中完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers( "/registration**", "/js/**", "/css/**", "/img/**", "/webjars/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .invalidateHttpSession(true) // .clearAuthentication(true) .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout") .permitAll(); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider auth = new DaoAuthenticationProvider(); auth.setUserDetailsService(userService); auth.setPasswordEncoder(passwordEncoder()); return auth; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\config\SecurityConfiguration.java
2
请完成以下Java代码
public Object getWrappedModel() { return qtyReportEvent; } @Override public Timestamp getDate() { return qtyReportEvent.getDatePromised(); } @Override public BigDecimal getQty() { return qtyReportEvent.getQtyPromised(); } @Override public void setM_PricingSystem_ID(final int M_PricingSystem_ID) { qtyReportEvent.setM_PricingSystem_ID(M_PricingSystem_ID); } @Override public void setM_PriceList_ID(final int M_PriceList_ID) {
qtyReportEvent.setM_PriceList_ID(M_PriceList_ID); } @Override public void setCurrencyId(final CurrencyId currencyId) { qtyReportEvent.setC_Currency_ID(CurrencyId.toRepoId(currencyId)); } @Override public void setPrice(final BigDecimal price) { qtyReportEvent.setPrice(price); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMPricingAware_QtyReportEvent.java
1
请在Spring Boot框架中完成以下Java代码
private void prepareSuccessResponse(@NonNull final Exchange exchange) { exchange.getIn().setBody(null); exchange.getIn().setHeader(HTTP_RESPONSE_CODE, HttpStatus.OK.value() ); } private void prepareRestAPIContext(@NonNull final Exchange exchange) { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); final GRSRestAPIContext context = GRSRestAPIContext.builder() .request(request) .build(); exchange.setProperty(GRSSignumConstants.ROUTE_PROPERTY_GRS_REST_API_CONTEXT, context); } private void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus externalStatus) { final GRSRestAPIContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_GRS_REST_API_CONTEXT, GRSRestAPIContext.class); final JsonExternalSystemRequest request = context.getRequest(); final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder() .status(externalStatus) .pInstanceId(request.getAdPInstanceId()) .build(); final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder() .jsonStatusRequest(jsonStatusRequest) .externalSystemConfigType(getExternalSystemTypeCode()) .externalSystemChildConfigValue(request.getExternalSystemChildConfigValue()) .serviceValue(getServiceValue()) .build(); exchange.getIn().setBody(camelRequest, JsonExternalSystemRequest.class); } private void prepareHttpErrorResponse(@NonNull final Exchange exchange) { final JsonError jsonError = ErrorProcessor.processHttpErrorEncounteredResponse(exchange); exchange.getIn().setBody(jsonError);
} @Override public String getServiceValue() { return "defaultRestAPIGRS"; } @Override public String getExternalSystemTypeCode() { return GRSSIGNUM_SYSTEM_NAME; } @Override public String getEnableCommand() { return ENABLE_RESOURCE_ROUTE; } @Override public String getDisableCommand() { return DISABLE_RESOURCE_ROUTE; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\restapi\GRSRestAPIRouteBuilder.java
2
请完成以下Java代码
public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [name=").append(name).append(", id=").append(id).append("]"); return builder.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && age == user.age && Objects.equals(name, user.name) && Objects.equals(creationDate, user.creationDate) && Objects.equals(email, user.email) && Objects.equals(status, user.status); } @Override public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status); } public LocalDate getLastLoginDate() { return lastLoginDate; } public void setLastLoginDate(LocalDate lastLoginDate) { this.lastLoginDate = lastLoginDate; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\domain\User.java
1
请完成以下Java代码
public class MPaySelectionLine extends X_C_PaySelectionLine { public MPaySelectionLine(Properties ctx, int C_PaySelectionLine_ID, String trxName) { super(ctx, C_PaySelectionLine_ID, trxName); if (is_new()) { // setC_PaySelection_ID (0); // setPaymentRule (null); // S // setLine (0); // @SQL=SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM C_PaySelectionLine WHERE C_PaySelection_ID=@C_PaySelection_ID@ // setC_Invoice_ID (0); setIsSOTrx(false); setOpenAmt(BigDecimal.ZERO); setPayAmt(BigDecimal.ZERO); setDiscountAmt(BigDecimal.ZERO); setDifferenceAmt(BigDecimal.ZERO); setIsManual(false); } }
public MPaySelectionLine(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } @Override public String toString() { final StringBuilder sb = new StringBuilder("MPaySelectionLine["); sb.append(get_ID()).append(",C_Invoice_ID=").append(getC_Invoice_ID()) .append(",PayAmt=").append(getPayAmt()) .append(",DifferenceAmt=").append(getDifferenceAmt()) .append("]"); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MPaySelectionLine.java
1
请完成以下Java代码
public ClassLoader run() { return clazz.getClassLoader(); } }); } else { return clazz.getClassLoader(); } } public static void setContextClassloader(final ClassLoader classLoader) { if(System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { Thread.currentThread().setContextClassLoader(classLoader); return null; } }); } else { Thread.currentThread().setContextClassLoader(classLoader); } } public static ClassLoader getServletContextClassloader(final ServletContextEvent sce) { if(System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() {
return sce.getServletContext().getClassLoader(); } }); } else { return sce.getServletContext().getClassLoader(); } } /** * Switch the current Thread ClassLoader to the ProcessEngine's * to assure the loading of the engine classes during job execution. * * @return the current Thread ClassLoader */ public static ClassLoader switchToProcessEngineClassloader() { ClassLoader currentClassloader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(ProcessEngine.class.getClassLoader()); return currentClassloader; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ClassLoaderUtil.java
1
请完成以下Java代码
private void onRuleChainToRuleNodeMsg(RuleChainToRuleNodeMsg envelope) { TbMsg msg = envelope.getMsg(); if (!msg.isValid()) { if (log.isTraceEnabled()) { log.trace("Skip processing of message: {} because it is no longer valid!", msg); } return; } if (log.isDebugEnabled()) { log.debug("[{}][{}][{}] Going to process rule engine msg: {}", ruleChainId, id, processor.getComponentName(), msg); } try { processor.onRuleChainToRuleNodeMsg(envelope); increaseMessagesProcessedCount(); } catch (Exception e) { logAndPersist("onRuleMsg", e); } } public static class ActorCreator extends ContextBasedCreator { private final TenantId tenantId; private final RuleChainId ruleChainId; private final String ruleChainName; private final RuleNodeId ruleNodeId; public ActorCreator(ActorSystemContext context, TenantId tenantId, RuleChainId ruleChainId, String ruleChainName, RuleNodeId ruleNodeId) { super(context); this.tenantId = tenantId; this.ruleChainId = ruleChainId; this.ruleChainName = ruleChainName;
this.ruleNodeId = ruleNodeId; } @Override public TbActorId createActorId() { return new TbEntityActorId(ruleNodeId); } @Override public TbActor createActor() { return new RuleNodeActor(context, tenantId, ruleChainId, ruleChainName, ruleNodeId); } } @Override protected RuleChainId getRuleChainId() { return ruleChainId; } @Override protected String getRuleChainName() { return ruleChainName; } @Override protected long getErrorPersistFrequency() { return systemContext.getRuleNodeErrorPersistFrequency(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleNodeActor.java
1
请完成以下Java代码
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Temporal MRP & CRP. @param T_MRP_CRP_ID Temporal MRP & CRP */
public void setT_MRP_CRP_ID (int T_MRP_CRP_ID) { if (T_MRP_CRP_ID < 1) set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, null); else set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, Integer.valueOf(T_MRP_CRP_ID)); } /** Get Temporal MRP & CRP. @return Temporal MRP & CRP */ public int getT_MRP_CRP_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_T_MRP_CRP_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_T_MRP_CRP.java
1
请在Spring Boot框架中完成以下Java代码
public class BooleanExpressionsController { @RequestMapping(value = "/booleans", method = RequestMethod.GET) public String getDates(Model model) { // "truthy" values model.addAttribute("trueValue", true); model.addAttribute("one", 1); model.addAttribute("nonZeroCharacter", 'a'); model.addAttribute("emptyString", ""); model.addAttribute("foo", "foo"); model.addAttribute("object", new Object()); model.addAttribute("arrayOfZeros", new Integer[] { 0, 0 }); model.addAttribute("arrayOfZeroAndOne", new Integer[] { 0, 1 }); model.addAttribute("arrayOfOnes", new Integer[] { 1, 1 }); // "falsy" values
model.addAttribute("nullValue", null); model.addAttribute("falseValue", false); model.addAttribute("zero", 0); model.addAttribute("zeroCharacter", '\0'); model.addAttribute("falseString", "false"); model.addAttribute("no", "no"); model.addAttribute("off", "off"); model.addAttribute("isRaining", true); model.addAttribute("isSunny", true); model.addAttribute("isCold", false); model.addAttribute("isWarm", true); return "booleans.html"; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\booleanexpressions\BooleanExpressionsController.java
2
请完成以下Java代码
public class BigDecimalVariableType extends VariableType { public static final String VALIDATION_ERROR_FORMAT = "%s is not a numeric type"; private static final Logger logger = LoggerFactory.getLogger(BigDecimalVariableType.class); @Override public Object parseFromValue(Object value) throws ActivitiException { if (value instanceof BigDecimal) { return value; } try { if (value instanceof String) { return new BigDecimal((String) value); }
return BigDecimal.valueOf(((Number) value).doubleValue()); } catch (ClassCastException | NumberFormatException e) { throw new ActivitiException("Error parsing bigdecimal value from " + value + ": " + e.getMessage(), e); } } @Override public void validate(Object var, List<ActivitiException> errors) { if (!Number.class.isAssignableFrom(var.getClass())) { String message = String.format(VALIDATION_ERROR_FORMAT, var.getClass()); errors.add(new ActivitiException(message)); logger.error(message); } } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\variable\types\BigDecimalVariableType.java
1
请完成以下Java代码
public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getCategory() { throw new UnsupportedOperationException(); } @Override public CamundaFormDefinitionEntity getPreviousDefinition() { throw new UnsupportedOperationException(); } @Override public void setCategory(String category) { throw new UnsupportedOperationException(); } @Override public String getDiagramResourceName() { throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms"); } @Override public void setDiagramResourceName(String diagramResourceName) { throw new UnsupportedOperationException("deployment of diagrams not supported for Camunda Forms"); }
@Override public Integer getHistoryTimeToLive() { throw new UnsupportedOperationException("history time to live not supported for Camunda Forms"); } @Override public void setHistoryTimeToLive(Integer historyTimeToLive) { throw new UnsupportedOperationException("history time to live not supported for Camunda Forms"); } @Override public Object getPersistentState() { // properties of this entity are immutable return CamundaFormDefinitionEntity.class; } @Override public void updateModifiableFieldsFromEntity(CamundaFormDefinitionEntity updatingDefinition) { throw new UnsupportedOperationException("properties of Camunda Form Definitions are immutable"); } @Override public String getName() { throw new UnsupportedOperationException("name property not supported for Camunda Forms"); } @Override public void setName(String name) { throw new UnsupportedOperationException("name property not supported for Camunda Forms"); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CamundaFormDefinitionEntity.java
1
请完成以下Spring Boot application配置
server: port: 8761 eureka: instance: hostname: registry prefer-ip-address: true client: registerWithEureka: false fetchRegistry: false service-url: defaultZone: http://${security.user.name}:${security.user.password}@${eureka.instance.h
ostname}:${server.port}/eureka/ security: user: name: user password: ${REGISTRY_SERVER_PASSWORD:password}
repos\spring-boot-cloud-master\registry\src\main\resources\application.yml
2
请完成以下Java代码
public class Http2ClientInitializer extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; private final int maxContentLength; private Http2SettingsHandler settingsHandler; private Http2ClientResponseHandler responseHandler; private String host; private int port; public Http2ClientInitializer(SslContext sslCtx, int maxContentLength, String host, int port) { this.sslCtx = sslCtx; this.maxContentLength = maxContentLength; this.host = host; this.port = port; } @Override public void initChannel(SocketChannel ch) throws Exception { settingsHandler = new Http2SettingsHandler(ch.newPromise()); responseHandler = new Http2ClientResponseHandler();
if (sslCtx != null) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslCtx.newHandler(ch.alloc(), host, port)); pipeline.addLast(Http2Util.getClientAPNHandler(maxContentLength, settingsHandler, responseHandler)); } } public Http2SettingsHandler getSettingsHandler() { return settingsHandler; } public Http2ClientResponseHandler getResponseHandler() { return responseHandler; } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\netty\http2\client\Http2ClientInitializer.java
1